Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JUG-11 Add custom response definition #31

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
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
1 change: 1 addition & 0 deletions src/adapters/express/AppEnv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,6 @@ export const makeAppEnv = (config: Config): TE.TaskEither<Error, AppEnv> =>
mock,
requestResponseReader: requestResponseStore,
requestResponseWriter: requestResponseStore,
listCustomResponseDefinition: () => [],
}))
);
4 changes: 2 additions & 2 deletions src/adapters/express/getRequestResponseRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ const makeAPIRequestResponse = (
body: input.request.body || {},
},
response: {
status: input.response.status,
status: input.response.statusCode,
headers: input.response.headers || {},
body: input.response.data || {},
body: input.response.body || {},
},
});

Expand Down
12 changes: 6 additions & 6 deletions src/adapters/express/mockHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ import { pipe } from 'fp-ts/lib/function';
import * as O from 'fp-ts/lib/Option';
import * as RTE from 'fp-ts/lib/ReaderTaskEither';
import * as RR from 'fp-ts/lib/ReadonlyRecord';
import { MockRequest } from '../../domain/Mock';
import { HttpRequest } from '../../domain/RequestResponse';
import { processRequest } from '../../useCases/processRequest';
import { AppEnv } from './AppEnv';
import { problemDetail500 } from './errors';

export const makeMethod = (
method: express.Request['method']
): MockRequest['method'] => {
): HttpRequest['method'] => {
switch (method) {
case 'DELETE':
return 'delete';
Expand All @@ -36,7 +36,7 @@ export const makeMethod = (

const makeHeaders = (
headers: express.Request['headers']
): MockRequest['headers'] =>
): HttpRequest['headers'] =>
pipe(
headers,
RR.filterMap(O.fromNullable),
Expand All @@ -49,7 +49,7 @@ const makeHeaders = (
*/
export const makeMockRequestFromExpressRequest = (
request: express.Request
): MockRequest => ({
): HttpRequest => ({
url: {
path: request.path,
},
Expand All @@ -68,8 +68,8 @@ export const makeMockHandler =
processRequest(makeMockRequestFromExpressRequest(req)),
RTE.fold(
(_) => RTE.of(res.status(500).json(problemDetail500)),
({ status, headers, data }) =>
RTE.of(res.status(status).header(headers).send(data))
({ statusCode, headers, body }) =>
RTE.of(res.status(statusCode).header(headers).send(body))
),
RTE.toUnion
)(env)();
9 changes: 8 additions & 1 deletion src/adapters/prism/makeMock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,14 @@ const makePrismHttp = (openapi: string): TE.TaskEither<Error, PrismHttp> =>
*/
export const makeMockFromPrismHttp = (prismHttp: PrismHttp): Mock => ({
generateResponse: (req) =>
TE.tryCatch(() => prismHttp.request(req.url.path, req), E.toError),
pipe(
TE.tryCatch(() => prismHttp.request(req.url.path, req), E.toError),
TE.map(({ status, headers, data }) => ({
statusCode: status,
headers,
body: data,
}))
),
});

/**
Expand Down
2 changes: 2 additions & 0 deletions src/domain/Capabilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
* This file is a capabilities mapper, maps a capability to a given key.
*/

import { ListCustomResponseDefinition } from './CustomResponseDefinition';
import { Mock } from './Mock';
import {
RequestResponseReader,
Expand All @@ -18,4 +19,5 @@ export type Capabilities = {
mock: Mock;
requestResponseReader: RequestResponseReader;
requestResponseWriter: RequestResponseWriter;
listCustomResponseDefinition: ListCustomResponseDefinition;
};
13 changes: 13 additions & 0 deletions src/domain/CustomResponseDefinition.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { HttpRequest, HttpResponse } from './RequestResponse';

export type CustomResponseDefinition = {
match: HttpRequest;
response: HttpResponse;
};

// Return true if match matches request
export const matches = (match: HttpRequest, request: HttpRequest): boolean =>
match.method === request.method && match.url.path === request.url.path;

export type ListCustomResponseDefinition =
() => ReadonlyArray<CustomResponseDefinition>;
12 changes: 2 additions & 10 deletions src/domain/Mock.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,5 @@
import * as TE from 'fp-ts/lib/TaskEither';
import { IHttpRequest } from '@stoplight/prism-http';
import { PrismHttp } from '@stoplight/prism-http/dist/client';

// For now use the types of prism
export type MockRequest = IHttpRequest;
export type MockOutput = Omit<
Awaited<ReturnType<PrismHttp['request']>>,
'config'
>;
import { HttpRequest, HttpResponse } from './RequestResponse';

/**
* This type exposes the capability to create fake responses
Expand All @@ -16,5 +8,5 @@ export type Mock = {
/**
* Given a request, produce a fake response.
*/
generateResponse: (req: MockRequest) => TE.TaskEither<Error, MockOutput>;
generateResponse: (req: HttpRequest) => TE.TaskEither<Error, HttpResponse>;
};
10 changes: 7 additions & 3 deletions src/domain/RequestResponse.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import * as TE from 'fp-ts/TaskEither';
import { MockRequest, MockOutput } from './Mock';
import { IHttpRequest, IHttpResponse } from '@stoplight/prism-http';

// For now use the types of prism
export type HttpRequest = IHttpRequest;
export type HttpResponse = IHttpResponse;

/**
* Represents the request-response pair provided by the Mock.
*/
export type RequestResponse = {
// I didn't found a better term from the RFC 2616.
// https://www.rfc-editor.org/rfc/rfc2616.html#section-4
request: MockRequest;
response: MockOutput;
request: HttpRequest;
response: HttpResponse;
};

/**
Expand Down
24 changes: 24 additions & 0 deletions src/domain/__tests__/CustomResponseDefinition.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { matches } from '../CustomResponseDefinition';
import { data } from './data';

const request = data.requestResponse.aRequestResponse.request;

describe('matches', () => {
it('should match requests without error', () => {
expect(matches(request, request)).toBeTruthy();
expect(matches({ ...request, method: 'post' }, request)).toBeFalsy();
// ignore body during match
expect(
matches(
{
...request,
body: { a: 'a' },
},
{
...request,
body: { b: 'b' },
}
)
).toBeTruthy();
});
});
46 changes: 34 additions & 12 deletions src/domain/__tests__/data.ts
Original file line number Diff line number Diff line change
@@ -1,48 +1,70 @@
import * as TE from 'fp-ts/TaskEither';
import { mock } from 'jest-mock-extended';
import { Capabilities } from '../Capabilities';
import { MockOutput, MockRequest } from '../Mock';
import { CustomResponseDefinition } from '../CustomResponseDefinition';
import { HttpRequest, HttpResponse } from '../RequestResponse';

const aMockRequest: MockRequest = {
const anHttpRequest: HttpRequest = {
method: 'get',
url: { path: 'http://localhost:8080/hello?name=Rupert' },
};

const aMockOutput: MockOutput = {
status: 200,
const anHttpResponse: HttpResponse = {
statusCode: 200,
headers: {},
data: {},
request: aMockRequest,
violations: { input: [], output: [] },
body: {},
};

const customResponseDefinition: CustomResponseDefinition = {
match: {
method: 'post',
url: { path: 'http://localhost:8080/hello?name=Rupert' },
},
response: {
statusCode: 200,
headers: {
'x-custom': 'custom-response-definition',
},
body: {},
},
};

export const data = {
mock: {
aMockRequest,
aMockOutput,
anHttpRequest,
anHttpResponse,
},
requestResponse: {
aRequestResponse: {
request: aMockRequest,
response: aMockOutput,
request: anHttpRequest,
response: anHttpResponse,
},
},
customResponseDefinition: {
anHttpRequest: customResponseDefinition.match,
anHttpResponse: customResponseDefinition.response,
},
};

export const makeFakeCapabilities = (defaultData: typeof data = data) => {
const mocked = {
mock: mock<Capabilities['mock']>(),
requestResponseReader: mock<Capabilities['requestResponseReader']>(),
requestResponseWriter: mock<Capabilities['requestResponseWriter']>(),
listCustomResponseDefinition:
mock<Capabilities>().listCustomResponseDefinition,
};
// default behavior
mocked.mock.generateResponse.mockReturnValue(
TE.right(defaultData.mock.aMockOutput)
TE.right(defaultData.mock.anHttpResponse)
);
mocked.requestResponseWriter.record.mockImplementation(TE.of);
mocked.requestResponseReader.list.mockReturnValue(
TE.of([defaultData.requestResponse.aRequestResponse])
);
mocked.listCustomResponseDefinition.mockReturnValue([
customResponseDefinition,
]);

// return within data
return { env: mocked, envData: defaultData };
Expand Down
14 changes: 12 additions & 2 deletions src/useCases/__tests__/processRequest.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,25 @@ describe('processRequest', () => {
it('should return mock response', async () => {
const { env, envData } = makeFakeCapabilities();

const actual = await processRequest(envData.mock.aMockRequest)(env)();
const actual = await processRequest(envData.mock.anHttpRequest)(env)();
const expected = envData.requestResponse.aRequestResponse.response;
expect(actual).toStrictEqual(E.right(expected));
});
it('should record the request-response pair', async () => {
const { env, envData } = makeFakeCapabilities();

await processRequest(envData.mock.aMockRequest)(env)();
await processRequest(envData.mock.anHttpRequest)(env)();
const expected = envData.requestResponse.aRequestResponse;
expect(env.requestResponseWriter.record).nthCalledWith(1, expected);
});
it('should return the response defined by user if any', async () => {
const { env, envData } = makeFakeCapabilities();

const actual = await processRequest({
...envData.customResponseDefinition.anHttpRequest,
})(env)();
const expected = envData.customResponseDefinition.anHttpResponse;
expect(env.mock.generateResponse).toBeCalledTimes(0);
expect(actual).toStrictEqual(E.right(expected));
});
});
28 changes: 21 additions & 7 deletions src/useCases/processRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,34 @@
*/
import { pipe } from 'fp-ts/lib/function';
import * as TE from 'fp-ts/TaskEither';
import * as RA from 'fp-ts/ReadonlyArray';
import * as O from 'fp-ts/Option';
import * as R from 'fp-ts/Reader';
import { Capabilities } from '../domain/Capabilities';
import { MockRequest } from '../domain/Mock';
import { HttpRequest } from '../domain/RequestResponse';
import { matches } from '../domain/CustomResponseDefinition';

/**
* Process the given request
* This function is the entry point for processing an HTTP request. Its goal is
* to deliver a dummy answer to the specified HTTP request.
*/
export const processRequest = (mockRequest: MockRequest) =>
export const processRequest = (request: HttpRequest) =>
pipe(
R.ask<Pick<Capabilities, 'mock' | 'requestResponseWriter'>>(),
R.map(({ mock, requestResponseWriter }) =>
R.ask<
Pick<
Capabilities,
'mock' | 'requestResponseWriter' | 'listCustomResponseDefinition'
>
>(),
R.map(({ mock, requestResponseWriter, listCustomResponseDefinition }) =>
pipe(
mock.generateResponse(mockRequest),
TE.map((response) => ({ request: mockRequest, response })),
listCustomResponseDefinition(),
RA.findFirst(({ match }) => matches(match, request)),
O.fold(
() => mock.generateResponse(request),
({ response }) => TE.of(response)
),
TE.map((response) => ({ request, response })),
TE.chain(requestResponseWriter.record),
TE.map(({ response }) => response)
)
Expand Down