controller.class.test.ts 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. import { assert, assertEquals } from 'test-deps';
  2. import { HTTPStatus } from 'deps';
  3. import Controller, {
  4. ControllerHandler,
  5. } from 'if/controllers/controller.class.ts';
  6. import { Logger } from 'infra/logger.ts';
  7. const testLogger = Logger.getInstance('test');
  8. Deno.test('Controller class', async () => {
  9. const mockHandler = (req: Request) => new Response('Hello, world!');
  10. const mockHandlers = {
  11. '/_GET': mockHandler,
  12. '/x_POST': mockHandler,
  13. };
  14. const controller = new Controller({}, testLogger);
  15. controller.setHandlers(mockHandlers);
  16. // Test that the handler was stored correctly
  17. assert(controller.hasHandler('/', 'GET'), 'specific handler found');
  18. assertEquals(controller.getHandlers(), mockHandlers, 'all handlers found');
  19. // Test the response method
  20. const req = new Request('http://localhost/');
  21. const res = controller.response(req, 'Hello, world!');
  22. assertEquals(res.status, 200, 'response http status is OK');
  23. assertEquals(
  24. new TextDecoder().decode(new Uint8Array(await res.arrayBuffer())),
  25. 'Hello, world!',
  26. 'response body is correct',
  27. );
  28. // Test the responseJSON method
  29. const jsonRes = controller.responseJSON(req, { message: 'Hello, world!' });
  30. assertEquals(jsonRes.status, 200, 'json response http status is OK');
  31. assertEquals(
  32. await jsonRes.json(),
  33. { message: 'Hello, world!' },
  34. 'response json body is correct',
  35. );
  36. // Test basic auth username / password
  37. const authReq = new Request('http://localhost/', {
  38. headers: {
  39. Authorization: 'Basic ZGVtbzpwQDU1dzByZA==',
  40. },
  41. });
  42. const authRes = controller.response(authReq, 'Hello, world!');
  43. assertEquals(authRes.status, 200, 'response http status is OK');
  44. const lastMessage = testLogger.getLastMessage();
  45. assert(
  46. lastMessage?.startsWith('[INFO] demo "GET /" '),
  47. 'username is shown in logging message',
  48. );
  49. });
  50. Deno.test('Controller class error handling', async () => {
  51. const error = new Error('Test error');
  52. const errorHandler = (
  53. req: Request,
  54. error?: string,
  55. headers?: Record<string, string>,
  56. ): Response => {
  57. return controller.response(req, error ?? 'Unknown error', {
  58. status: HTTPStatus.InternalServerError,
  59. });
  60. };
  61. const controller = new Controller({}, testLogger);
  62. controller.setHandler('/', 'GET', errorHandler);
  63. // Test that the handler was stored correctly
  64. assert(controller.hasHandler('/', 'GET'), 'handler found');
  65. // Test the error response method
  66. const req = new Request('http://localhost/');
  67. const handler = controller.getHandler('/', 'GET');
  68. if (handler) {
  69. const res = await handler(req, error.message);
  70. assertEquals(
  71. res.status,
  72. HTTPStatus.InternalServerError,
  73. 'response http status is 500',
  74. );
  75. assertEquals(
  76. new TextDecoder().decode(new Uint8Array(await res.arrayBuffer())),
  77. error.message,
  78. 'response body is correct',
  79. );
  80. } else {
  81. assert(false, 'Handler not found');
  82. }
  83. });
  84. Deno.test({
  85. name: 'Controller should log debug message for health check user agent',
  86. fn: async () => {
  87. const userAgent = Deno.env.get('DOCKER_USER_AGENT') ?? '';
  88. const req = new Request('http://localhost', {
  89. method: 'GET',
  90. headers: userAgent
  91. ? new Headers({
  92. 'User-Agent': userAgent,
  93. })
  94. : undefined,
  95. });
  96. const handler: ControllerHandler = (req: Request) => {
  97. return controller.response(req, 'Hello, World!');
  98. };
  99. const controller = new Controller({ '/_GET': handler }, testLogger);
  100. const response = await controller.getHandler('/', 'GET')(req);
  101. // Check if the expected debug message was logged
  102. const debugMessage = testLogger.getMessages().find((message) =>
  103. message.startsWith('[DEBUG] ') && message.endsWith(`"${userAgent}"`)
  104. );
  105. assert(debugMessage !== undefined, 'expected debug message was not logged');
  106. assertEquals(response.status, 200, 'response http status is OK');
  107. },
  108. });