feat: Return correct status codes for invalid requests

This commit is contained in:
Joachim Van Herwegen
2022-01-14 14:54:28 +01:00
parent bc6203f3e8
commit 1afed65368
12 changed files with 179 additions and 17 deletions

View File

@@ -0,0 +1,52 @@
import type { Operation } from '../../../../src/http/Operation';
import { BasicRepresentation } from '../../../../src/http/representation/BasicRepresentation';
import { NotImplementedHttpError } from '../../../../src/util/errors/NotImplementedHttpError';
import type { AsyncHandler } from '../../../../src/util/handlers/AsyncHandler';
import {
MethodFilterHandler,
} from '../../../../src/util/handlers/MethodFilterHandler';
describe('A MethodFilterHandler', (): void => {
const modes = [ 'PATCH', 'POST' ];
const result = 'RESULT';
let operation: Operation;
let source: jest.Mocked<AsyncHandler<Operation, string>>;
let handler: MethodFilterHandler<Operation, string>;
beforeEach(async(): Promise<void> => {
operation = {
method: 'PATCH',
preferences: {},
permissionSet: {},
target: { path: 'http://example.com/foo' },
body: new BasicRepresentation(),
};
source = {
canHandle: jest.fn(),
handle: jest.fn().mockResolvedValue(result),
} as any;
handler = new MethodFilterHandler(modes, source);
});
it('rejects unknown methods.', async(): Promise<void> => {
operation.method = 'GET';
await expect(handler.canHandle(operation)).rejects.toThrow(NotImplementedHttpError);
});
it('checks if the source handle supports the request.', async(): Promise<void> => {
operation.method = 'PATCH';
await expect(handler.canHandle(operation)).resolves.toBeUndefined();
operation.method = 'POST';
await expect(handler.canHandle(operation)).resolves.toBeUndefined();
source.canHandle.mockRejectedValueOnce(new Error('not supported'));
await expect(handler.canHandle(operation)).rejects.toThrow('not supported');
expect(source.canHandle).toHaveBeenLastCalledWith(operation);
});
it('calls the source extractor.', async(): Promise<void> => {
await expect(handler.handle(operation)).resolves.toBe(result);
expect(source.handle).toHaveBeenLastCalledWith(operation);
});
});

View File

@@ -0,0 +1,15 @@
import { BadRequestHttpError } from '../../../../src/util/errors/BadRequestHttpError';
import { StaticThrowHandler } from '../../../../src/util/handlers/StaticThrowHandler';
describe('A StaticThrowHandler', (): void => {
const error = new BadRequestHttpError();
const handler = new StaticThrowHandler(error);
it('can handle all requests.', async(): Promise<void> => {
await expect(handler.canHandle({})).resolves.toBeUndefined();
});
it('always throws the given error.', async(): Promise<void> => {
await expect(handler.handle()).rejects.toThrow(error);
});
});