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
29 changes: 29 additions & 0 deletions src/httpPact/ffi.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { ConsumerInteraction } from '@pact-foundation/pact-core';
import { vi } from 'vitest';
import { term } from '../dsl/matchers';
import { contentTypeFromHeaders, setQuery } from './ffi';

describe('Pact FFI', () => {
Expand All @@ -15,6 +16,34 @@ describe('Pact FFI', () => {
});
});

describe('when the header is a matcher', () => {
it('uses the example value', () => {
const headers = {
'Content-Type': term({
generate: 'application/json',
matcher: 'application/json.*',
}),
};
expect(contentTypeFromHeaders(headers, 'text/plain')).toBe(
'application/json',
);
});
});

describe('when the header has more than one value', () => {
it('uses the first value', () => {
const headers = {
'Content-Type': [
term({ generate: 'application/xml', matcher: 'application/.*xml' }),
'text/plain',
],
};
expect(contentTypeFromHeaders(headers, 'application/json')).toBe(
'application/xml',
);
});
});

describe(`when the no content-type header is set`, () => {
it('uses a default', () => {
expect(contentTypeFromHeaders({}, 'application/json')).toBe(
Expand Down
14 changes: 11 additions & 3 deletions src/httpPact/ffi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,12 @@ import type {
RequestOptions,
ResponseOptions,
} from '../dsl/interaction';
import { type MatcherV2, matcherValueOrString } from '../dsl/matchers';
import {
extractPayload,
isMatcher,
type MatcherV2,
matcherValueOrString,
} from '../dsl/matchers';

enum InteractionPart {
REQUEST = 1,
Expand All @@ -22,10 +27,13 @@ export const contentTypeFromHeaders = (
headers: Headers | undefined,
defaultContentType: string,
): string => {
let contentType: string | MatcherV2<string> = defaultContentType;
let contentType = defaultContentType;
forEachObjIndexed((v, k) => {
if (`${k}`.toLowerCase() === CONTENT_TYPE_HEADER) {
contentType = matcherValueOrString(v);
const headerValue = Array.isArray(v) ? v[0] : v;
contentType = isMatcher(headerValue)
? `${extractPayload(headerValue)}`
: headerValue;
}
}, headers || {});

Expand Down
49 changes: 49 additions & 0 deletions src/messageProviderPact.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import express from 'express';
import type { Message } from './dsl/message';
import {
MessageProviderPact,
providerWithMetadata,
setupProxyServer,
waitForServerReady,
} from './messageProviderPact';
Expand Down Expand Up @@ -187,5 +188,53 @@ describe('MessageProvider', () => {
(provider as any).setupProxyApplication.bind(provider);
expect(setupProxyApplication().listen).toBeTypeOf('function');
});

describe('when a message has a content type in its metadata', () => {
const messageFor = async (description: string) => {
const app = new MessageProviderPact({
logLevel: 'error',
messageProviders: {
text: providerWithMetadata(() => '07/14/2023', {
contentType: 'text/plain',
}),
json: providerWithMetadata(() => 'yay', {
'Content-Type': 'application/json',
}),
},
provider: 'myprovider',
// biome-ignore lint/suspicious/noExplicitAny: accessing private method for test coverage
}) as any;
const server = setupProxyServer(app.setupProxyApplication());
await waitForServerReady(server);
try {
const { port } = server.address() as { port: number };
const res = await fetch(`http://localhost:${port}/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ description }),
});
return {
contentType: res.headers.get('content-type'),
body: await res.text(),
};
} finally {
server.close();
}
};

it('sends a text message as it is, with that content type', async () => {
expect(await messageFor('text')).toEqual({
contentType: 'text/plain; charset=utf-8',
body: '07/14/2023',
});
});

it('still sends a JSON message as JSON', async () => {
expect(await messageFor('json')).toEqual({
contentType: 'application/json; charset=utf-8',
body: '"yay"',
});
});
});
});
});
33 changes: 31 additions & 2 deletions src/messageProviderPact.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,32 @@ const hasMetadata = (
): o is MessageFromProviderWithMetadata =>
Boolean((o as MessageFromProviderWithMetadata).__pactMessageMetadata);

const metadataContentType = (
metadata: Record<string, unknown>,
): string | undefined => {
const key = Object.keys(metadata).find((k) =>
['contenttype', 'content-type'].includes(k.toLowerCase()),
);
return key ? `${metadata[key]}` : undefined;
};

// A text or binary message is sent as it is, with the content type from its
// metadata, so the verifier doesn't compare it as a JSON string (pact-js#1112)
const sendMessage = (
res: express.Response,
message: unknown,
contentType?: string,
) => {
if (
contentType &&
!/json/i.test(contentType) &&
(typeof message === 'string' || Buffer.isBuffer(message))
) {
return res.type(contentType).send(message);
}
return res.json(message);
};

export const providerWithMetadata =
(
provider: MessageProvider,
Expand Down Expand Up @@ -134,7 +160,11 @@ export class MessageProviderPact {
res.header('Pact-Message-Metadata', metadata);
res.header('PACT_MESSAGE_METADATA', metadata);

return res.json(messageFromHandler.message);
return sendMessage(
res,
messageFromHandler.message,
metadataContentType(messageFromHandler.__pactMessageMetadata),
);
}
return res.json(messageFromHandler);
})
Expand All @@ -149,7 +179,6 @@ export class MessageProviderPact {
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use((_req, res, next) => {
// TODO: this seems to override the metadata for content-type
res.header('Content-Type', 'application/json; charset=utf-8');
next();
});
Expand Down
41 changes: 39 additions & 2 deletions src/v3/ffi.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { contentTypeFromHeaders } from './ffi';
import { regex } from './matchers';
import { bodyAndMatchingRules, contentTypeFromHeaders } from './ffi';
import { like, regex, string } from './matchers';

describe('V3 Pact FFI', () => {
describe('#contentTypeFromHeaders', () => {
Expand All @@ -16,4 +16,41 @@ describe('V3 Pact FFI', () => {
);
});
});

describe('#bodyAndMatchingRules', () => {
it('sends a matcher on a text body as its example and a rule on the body', () => {
expect(bodyAndMatchingRules(string('07/14/2023'), 'text/plain')).toEqual({
body: '07/14/2023',
rules: JSON.stringify({
body: {
$: { combine: 'AND', matchers: [{ match: 'type' }] },
},
}),
});
});

it('keeps the regex of a regex matcher', () => {
const { body, rules } = bodyAndMatchingRules(
regex('\\d+', '123'),
'text/plain; charset=utf-8',
);
expect(body).toBe('123');
expect(JSON.parse(rules as string).body.$.matchers).toEqual([
{ regex: '\\d+', match: 'regex' },
]);
});

it('sends a matcher on a JSON body as matcher JSON', () => {
const matcher = like({ a: 1 });
expect(bodyAndMatchingRules(matcher, 'application/hal+json')).toEqual({
body: JSON.stringify(matcher),
});
});

it('sends a plain text body as it is', () => {
expect(bodyAndMatchingRules('hello', 'text/plain')).toEqual({
body: 'hello',
});
});
});
});
40 changes: 39 additions & 1 deletion src/v3/ffi.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import type { ConsumerInteraction } from '@pact-foundation/pact-core';
import { forEachObjIndexed } from 'ramda';
import logger from '../common/logger';
import { convertStatusMatcherToFFI } from '../common/matchingRules';
import * as MatchersV3 from './matchers';
import type { Matcher, TemplateHeaders, V3Request, V3Response } from './types';
import { convertStatusMatcherToFFI } from '../common/matchingRules';

type TemplateHeaderArrayValue = string[] | Matcher<string>[];

Expand Down Expand Up @@ -82,3 +83,40 @@ export const contentTypeFromHeaders = (

return contentType;
};

const isJsonContentType = (contentType: string): boolean =>
/json/i.test(contentType);

/**
* pact_ffi only reads matchers embedded in a JSON body. When the whole body is a single matcher and the content
* type is not JSON (for example `text/plain`), send the example as the body and the matcher as a rule on `$`, so
* the body is not written as the matcher's JSON (pact-js#1107).
*/
export const bodyAndMatchingRules = (
body: unknown,
contentType: string,
): { body: string; rules?: string } => {
if (
!MatchersV3.isMatcher(body) ||
isJsonContentType(contentType) ||
typeof body.value === 'object'
) {
return { body: MatchersV3.matcherValueOrString(body) };
}

const {
'pact:matcher:type': match,
'pact:generator:type': generator,
value,
...attributes
} = body as Matcher<unknown> & Record<string, unknown>;
if (generator) {
logger.warn(
`the ${generator} generator is not supported for a ${contentType} body, only the matcher will be used`,
);
}
const rules = {
body: { $: { combine: 'AND', matchers: [{ ...attributes, match }] } },
};
return { body: `${value}`, rules: JSON.stringify(rules) };
};
24 changes: 15 additions & 9 deletions src/v3/pact.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ import logger from '../common/logger';
import { convertRulesToFFI, validateRules } from '../common/matchingRules';
import { filterMissingFeatureFlag, generateMockServerError } from './display';
import {
bodyAndMatchingRules,
contentTypeFromHeaders,
setRequestDetails,
setResponseDetails,
} from './ffi';
import { matcherValueOrString } from './matchers';
import {
type PactV3Options,
type Rules,
Expand Down Expand Up @@ -115,11 +115,14 @@ export class PactV3 {

public withRequest(req: V3Request): PactV3 {
if (req.body) {
this.interaction.withRequestBody(
matcherValueOrString(req.body),
const contentType =
req.contentType ||
contentTypeFromHeaders(req.headers, 'application/json'),
);
contentTypeFromHeaders(req.headers, 'application/json');
const { body, rules } = bodyAndMatchingRules(req.body, contentType);
this.interaction.withRequestBody(body, contentType);
if (rules) {
this.interaction.withRequestMatchingRules(rules);
}
}

setRequestDetails(this.interaction, req);
Expand Down Expand Up @@ -203,11 +206,14 @@ export class PactV3 {
public willRespondWith(res: V3Response): PactV3 {
setResponseDetails(this.interaction, res);
if (res.body) {
this.interaction.withResponseBody(
matcherValueOrString(res.body),
const contentType =
res.contentType ||
contentTypeFromHeaders(res.headers, 'application/json'),
);
contentTypeFromHeaders(res.headers, 'application/json');
const { body, rules } = bodyAndMatchingRules(res.body, contentType);
this.interaction.withResponseBody(body, contentType);
if (rules) {
this.interaction.withResponseMatchingRules(rules);
}
}
this.states = [];
return this;
Expand Down
Loading