Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 23 additions & 3 deletions native/consumer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,14 @@ Napi::Value PactffiFetchLogBuffer(const Napi::CallbackInfo& info) {

const char* buffer = pactffi_fetch_log_buffer(log_id.c_str());

return Napi::String::New(env, buffer);
if (buffer == NULL) {
return env.Null();
}

Napi::String logs = Napi::String::New(env, buffer);
pactffi_string_delete((char*)buffer);

return logs;
}

/**
Expand Down Expand Up @@ -184,6 +191,12 @@ Napi::Value PactffiMockServerMismatches(const Napi::CallbackInfo& info) {
int32_t port = info[0].As<Napi::Number>().Int32Value();
char* res = pactffi_mock_server_mismatches(port);

// NULL when there is no mock server on the port, or the core panicked.
// Napi::String::New(env, NULL) would throw "Error in native callback".
if (res == NULL) {
return env.Null();
}

return Napi::String::New(env, res);
}

Expand Down Expand Up @@ -1957,9 +1970,16 @@ Napi::Value PactffiMessageReify(const Napi::CallbackInfo& info) {

MessageHandle handle = info[0].As<Napi::Number>().Uint32Value();

auto res = pactffi_message_reify(handle);
const char* res = pactffi_message_reify(handle);

return Napi::String::New(env, res);
if (res == NULL) {
return env.Null();
}

Napi::String reified = Napi::String::New(env, res);
pactffi_string_delete((char*)res);

return reified;
}

/**
Expand Down
28 changes: 27 additions & 1 deletion src/consumer/checkErrors.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import logger from '../logger';
import { wrapWithCheck } from './checkErrors';
import { wrapAllWithResultCheck, wrapWithCheck } from './checkErrors';

describe('checkErrors', () => {
const originalPactCrash = logger.pactCrash;
Expand Down Expand Up @@ -33,4 +33,30 @@ describe('checkErrors', () => {
expect(result).toBe(1);
expect(called).toBe(true);
});

describe('wrapAllWithResultCheck', () => {
it('checks status results and returns other results unchanged', () => {
const crashes: string[] = [];
logger.pactCrash = (message: string) => {
crashes.push(message);
};
const contents = Buffer.from('contents');

const wrapped = wrapAllWithResultCheck({
given: () => false,
setKey: () => true,
reifyMessage: () => '{"a":1}',
getRequestContents: () => contents,
withMetadata: () => undefined,
});

expect(wrapped.given()).toBe(false);
expect(wrapped.setKey()).toBe(true);
expect(wrapped.reifyMessage()).toBe('{"a":1}');
expect(wrapped.getRequestContents()).toBe(contents);
expect(wrapped.withMetadata()).toBeUndefined();
expect(crashes).toHaveLength(1);
expect(crashes[0]).toContain("at 'given'");
});
});
});
42 changes: 35 additions & 7 deletions src/consumer/checkErrors.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,26 @@
import logger from '../logger';

const checkResult = (result: unknown, contextMessage: string): void => {
if (typeof result !== 'boolean' && typeof result !== 'number') {
return;
}
const failed = typeof result === 'number' ? result !== 0 : !result;
if (failed) {
logger.pactCrash(
`The pact consumer core returned false at '${contextMessage}'. This\nshould only happen if the core methods were invoked out of order`,
);
}
};

export const wrapWithCheck =
<F extends (...args: never[]) => boolean | number>(
f: CheckableFunction<F>,
contextMessage: string,
) =>
(...args: Parameters<F>): ReturnType<F> => {
const result = f(...args);
const failed = typeof result === 'number' ? result !== 0 : !result;
if (failed) {
logger.pactCrash(
`The pact consumer core returned false at '${contextMessage}'. This\nshould only happen if the core methods were invoked out of order`,
);
}
return result;
checkResult(result, contextMessage);
return result as ReturnType<F>;
};

type CheckableFunction<T> = T extends (...args: infer A) => boolean | number
Expand All @@ -38,3 +45,24 @@ export const wrapAllWithCheck = <T extends CheckableFunctions<T>>(
(acc, curr) => Object.assign(acc, curr),
{} as CheckableFunctions<T>,
) as T;

/**
* Like `wrapAllWithCheck`, for objects whose functions don't all return a
* status (such as messages, which also return contents). Boolean and numeric
* results are checked; any other result is returned unchanged.
*/
export const wrapAllWithResultCheck = <
T extends Record<string, (...args: never[]) => unknown>,
>(
o: T,
): T =>
Object.fromEntries(
Object.entries(o).map(([key, f]) => [
key,
(...args: never[]) => {
const result = f(...args);
checkResult(result, key);
return result;
},
]),
) as T;
125 changes: 65 additions & 60 deletions src/consumer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,12 @@ import {
logErrorAndThrow,
setLogLevel,
} from '../logger';
import { wrapAllWithCheck, wrapWithCheck } from './checkErrors';
import { mockServerMismatches, writePact } from './internals';
import {
wrapAllWithCheck,
wrapAllWithResultCheck,
wrapWithCheck,
} from './checkErrors';
import { mockServerMismatches, reifyMessage, writePact } from './internals';
import type {
AsynchronousMessage,
ConsumerInteraction,
Expand Down Expand Up @@ -76,60 +80,61 @@ const asyncMessage = (
pactPtr: number,
messageCount: number,
index: number,
) => ({
// todo count the number of messages (and ref them?)
// Required to get contents
withPluginRequestInteractionContents: (
contentType: string,
contents: string,
) => {
return setPluginInteractionContents(
ffi,
interactionPtr,
INTERACTION_PART_REQUEST,
contentType,
contents,
);
},
expectsToReceive: (description: string) =>
ffi.pactffiMessageExpectsToReceive(interactionPtr, description),
given: (state: string) => ffi.pactffiMessageGiven(interactionPtr, state),
givenWithParam: (state: string, name: string, value: string) =>
ffi.pactffiMessageGivenWithParam(interactionPtr, state, name, value),
givenWithParams: (state: string, params: string) =>
ffi.pactffiMessageGivenWithParams(interactionPtr, state, params),
setPending: (pending: boolean) =>
ffi.pactffiSetPending(interactionPtr, pending),
setKey: (value: string) => ffi.pactffiSetKey(interactionPtr, value),
setComment: (key: string, value: string) =>
ffi.pactffiSetComment(interactionPtr, key, value),
addTextComment: (comment: string) =>
ffi.pactffiAddTextComment(interactionPtr, comment),
addInteractionReference: (group: string, name: string, value: string) =>
ffi.pactffiAddInteractionReference(interactionPtr, group, name, value),
setInteractionTestName: (name: string) =>
ffi.pactffiInteractionTestName(interactionPtr, name),
withContents: (body: string, contentType: string) =>
ffi.pactffiMessageWithContents(interactionPtr, contentType, body),
withBinaryContents: (body: Buffer, contentType: string) =>
ffi.pactffiMessageWithBinaryContents(
interactionPtr,
contentType,
body,
body.length,
),
withMatchingRules: (rules: string) =>
ffi.pactffiWithMatchingRules(
interactionPtr,
INTERACTION_PART_REQUEST,
rules,
),
reifyMessage: () => ffi.pactffiMessageReify(interactionPtr),
withMetadata: (name: string, value: string) =>
ffi.pactffiMessageWithMetadata(interactionPtr, name, value),
getRequestContents: () =>
ffi.pactffiGetAsyncMessageRequestContents(pactPtr, messageCount, index),
});
): AsynchronousMessage =>
wrapAllWithResultCheck<AsynchronousMessage>({
// todo count the number of messages (and ref them?)
// Required to get contents
withPluginRequestInteractionContents: (
contentType: string,
contents: string,
) => {
return setPluginInteractionContents(
ffi,
interactionPtr,
INTERACTION_PART_REQUEST,
contentType,
contents,
);
},
expectsToReceive: (description: string) =>
ffi.pactffiMessageExpectsToReceive(interactionPtr, description),
given: (state: string) => ffi.pactffiMessageGiven(interactionPtr, state),
givenWithParam: (state: string, name: string, value: string) =>
ffi.pactffiMessageGivenWithParam(interactionPtr, state, name, value),
givenWithParams: (state: string, params: string) =>
ffi.pactffiMessageGivenWithParams(interactionPtr, state, params),
setPending: (pending: boolean) =>
ffi.pactffiSetPending(interactionPtr, pending),
setKey: (value: string) => ffi.pactffiSetKey(interactionPtr, value),
setComment: (key: string, value: string) =>
ffi.pactffiSetComment(interactionPtr, key, value),
addTextComment: (comment: string) =>
ffi.pactffiAddTextComment(interactionPtr, comment),
addInteractionReference: (group: string, name: string, value: string) =>
ffi.pactffiAddInteractionReference(interactionPtr, group, name, value),
setInteractionTestName: (name: string) =>
ffi.pactffiInteractionTestName(interactionPtr, name),
withContents: (body: string, contentType: string) =>
ffi.pactffiMessageWithContents(interactionPtr, contentType, body),
withBinaryContents: (body: Buffer, contentType: string) =>
ffi.pactffiMessageWithBinaryContents(
interactionPtr,
contentType,
body,
body.length,
),
withMatchingRules: (rules: string) =>
ffi.pactffiWithMatchingRules(
interactionPtr,
INTERACTION_PART_REQUEST,
rules,
),
reifyMessage: () => reifyMessage(ffi, interactionPtr),
withMetadata: (name: string, value: string) =>
ffi.pactffiMessageWithMetadata(interactionPtr, name, value),
getRequestContents: () =>
ffi.pactffiGetAsyncMessageRequestContents(pactPtr, messageCount, index),
});

/**
* Returns the PEM encoded CA certificate used by TLS mock servers, or null if it is
Expand Down Expand Up @@ -268,7 +273,7 @@ export const makeConsumerPact = (
const index = messageCount;
messageCount += 1;

return {
return wrapAllWithResultCheck<SynchronousMessage>({
withPluginRequestInteractionContents: (
contentType: string,
contents: string,
Expand Down Expand Up @@ -382,7 +387,7 @@ export const makeConsumerPact = (
messageCount,
index,
),
};
});
},
pactffiCreateMockServerForTransport(
address: string,
Expand Down Expand Up @@ -661,7 +666,7 @@ export const makeConsumerMessagePact = (
// TODO: will this automatically set the correct spec version?
const interactionPtr = ffi.pactffiNewSyncMessage(pactPtr, description);

return {
return wrapAllWithResultCheck<SynchronousMessage>({
withPluginRequestInteractionContents: (
contentType: string,
contents: string,
Expand Down Expand Up @@ -775,7 +780,7 @@ export const makeConsumerMessagePact = (
messageCount,
index,
),
};
});
},
pactffiCreateMockServerForTransport(
address: string,
Expand Down
59 changes: 59 additions & 0 deletions src/consumer/internals.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import type { Ffi } from '../ffi/types';
import logger from '../logger';
import { mockServerMismatches, reifyMessage } from './internals';

describe('internals', () => {
const originalPactCrash = logger.pactCrash;

beforeEach(() => {
logger.pactCrash = () => {};
});

afterEach(() => {
logger.pactCrash = originalPactCrash;
});

describe('#mockServerMismatches', () => {
it('parses the mismatches from the core', () => {
const ffi = {
pactffiMockServerMismatches: () =>
JSON.stringify([
{
type: 'request-mismatch',
mismatches: ['{"type":"QueryMismatch"}'],
},
]),
} as unknown as Ffi;

expect(mockServerMismatches(ffi, 1234)).toEqual([
{ type: 'request-mismatch', mismatches: [{ type: 'QueryMismatch' }] },
]);
});

it('throws a clear error when the core returns no mismatches', () => {
const ffi = {
pactffiMockServerMismatches: () => null,
} as unknown as Ffi;

expect(() => mockServerMismatches(ffi, 1234)).toThrow(
/mismatches for the mock server on port 1234/,
);
});
});

describe('#reifyMessage', () => {
it('returns the reified message', () => {
const ffi = {
pactffiMessageReify: () => '{"contents":"a"}',
} as unknown as Ffi;

expect(reifyMessage(ffi, 1)).toBe('{"contents":"a"}');
});

it('throws a clear error when the core returns no message', () => {
const ffi = { pactffiMessageReify: () => null } as unknown as Ffi;

expect(() => reifyMessage(ffi, 1)).toThrow(/unable to reify the message/);
});
});
});
Loading
Loading