-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtestHandler.test.ts
More file actions
591 lines (496 loc) · 21.5 KB
/
testHandler.test.ts
File metadata and controls
591 lines (496 loc) · 21.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
/* eslint-disable max-len */
/* eslint-disable @typescript-eslint/no-explicit-any */
import {APIGatewayProxyEvent, APIGatewayProxyResult} from "aws-lambda"
import {
expect,
describe,
it,
vi,
beforeEach
} from "vitest"
import {
APPLICATION_NAME,
DEFAULT_DATE,
FULL_URL_0,
FULL_URL_1,
generateBody,
generateExpectedItems,
generateMockEvent,
TASK_VALUES,
getTestPrescriptions
} from "./utils/testUtils"
import requestDispatched from "../../specification/examples/request-dispatched.json"
import requestMultipleItems from "../../specification/examples/request-multiple-items.json"
import requestMissingFields from "../../specification/examples/request-missing-fields.json"
import requestMultipleMissingFields from "../../specification/examples/request-multiple-missing-fields.json"
import requestNoItems from "../../specification/examples/request-no-items.json"
import requestDuplicateItems from "../../specification/examples/request-duplicate-items.json"
import responseSingleItem from "../../specification/examples/response-single-item.json"
import responseMultipleItems from "../../specification/examples/response-multiple-items.json"
import {
badRequest,
bundleWrap,
serverError,
timeoutResponse
} from "../src/utils/responses"
import {QueryCommand, TransactionCanceledException, TransactWriteItemsCommand} from "@aws-sdk/client-dynamodb"
const {dynamoDBMockSend, mockPushPrescriptionToNotificationSQS, mockGetParametersByName, mockInitiatedSSMProvider} =
vi.hoisted(() => {
const mockGetParametersByName = vi.fn(async () => Promise.resolve(
{[process.env.ENABLE_NOTIFICATIONS_PARAM!]: "false"}
))
return {
dynamoDBMockSend: vi.fn(),
mockPushPrescriptionToNotificationSQS: vi.fn().mockImplementation(async () => Promise.resolve()),
mockGetParametersByName,
mockInitiatedSSMProvider: {getParametersByName: mockGetParametersByName}
}
})
vi.mock("@aws-sdk/client-dynamodb", async (importOriginal) => {
const mod = await importOriginal<typeof import("@aws-sdk/client-dynamodb")>()
return {
...mod,
DynamoDBClient: vi.fn(class {
send = dynamoDBMockSend
})
}
})
vi.mock("../src/utils/sqsClient", async () => ({
__esModule: true,
pushPrescriptionToNotificationSQS: mockPushPrescriptionToNotificationSQS
}))
vi.mock("@psu-common/utilities", async (importOriginal) => {
const mod = await importOriginal<typeof import("@psu-common/utilities")>()
return {
...mod,
getTestPrescriptions: getTestPrescriptions,
initiatedSSMProvider: mockInitiatedSSMProvider
}
})
const {handler, logger} = await import("../src/updatePrescriptionStatus")
const LAMBDA_TIMEOUT_MS = 9500 // 9.5 sec
const ORIGINAL_ENV = {...process.env}
describe("Integration tests for updatePrescriptionStatus handler", () => {
beforeEach(() => {
vi.resetModules()
process.env = {...ORIGINAL_ENV}
vi.clearAllMocks()
vi.clearAllTimers()
vi.useFakeTimers().setSystemTime(DEFAULT_DATE)
dynamoDBMockSend.mockReset()
dynamoDBMockSend.mockImplementation(async (command: unknown) => {
if (command instanceof QueryCommand) {
return {Items: []}
}
return {}
})
mockPushPrescriptionToNotificationSQS.mockReset()
mockPushPrescriptionToNotificationSQS.mockImplementation(async () => Promise.resolve())
mockGetParametersByName.mockReset()
mockGetParametersByName.mockImplementation(async () => Promise.resolve(
{[process.env.ENABLE_NOTIFICATIONS_PARAM!]: "false"}
))
})
it("when request doesn't have correct resourceType and type, expect 400 status code and appropriate message", async () => {
const body = {resourceType: "NotBundle", type: "not_transaction"}
const event: APIGatewayProxyEvent = generateMockEvent(body)
const response: APIGatewayProxyResult = await handler(event, {})
expect(response.statusCode).toEqual(400)
expect(JSON.parse(response.body)).toEqual(
bundleWrap([
badRequest(
"Request body does not have resourceType of 'Bundle' and type of 'transaction'."
)
])
)
})
it("when single item in request, expect a single item sent to DynamoDB", async () => {
const body = generateBody()
const event: APIGatewayProxyEvent = generateMockEvent(body)
const expectedItems = generateExpectedItems()
const response: APIGatewayProxyResult = await handler(event, {})
expect(response.statusCode).toEqual(201)
expect(JSON.parse(response.body)).toEqual(responseSingleItem)
expect(dynamoDBMockSend).toHaveBeenCalledWith(
expect.objectContaining(expectedItems)
)
})
it("when input field is absent in a single item request, expect DynamoDB item without RepeatNo field", async () => {
const body = generateBody()
const entryResource: any = body.entry?.[0]?.resource
if (entryResource?.input) {
delete entryResource.input
}
const event: APIGatewayProxyEvent = generateMockEvent(body)
const expectedItems = generateExpectedItems()
const transactItem: any =
expectedItems.input?.TransactItems?.[0]?.Put?.Item
if (transactItem?.RepeatNo) {
delete transactItem.RepeatNo
}
const response: APIGatewayProxyResult = await handler(event, {})
expect(response.statusCode).toEqual(201)
expect(JSON.parse(response.body)).toEqual(responseSingleItem)
expect(expectedItems.input.TransactItems[0].Put.Item.RepeatNo).toEqual(undefined)
expect(dynamoDBMockSend).toHaveBeenCalledWith(
expect.objectContaining(expectedItems)
)
})
it("when input field is present in a single item request, expect DynamoDB item with RepeatNo field", async () => {
const body = generateBody()
const entryResource: any = body.entry?.[0]?.resource
if (!entryResource.input) {
entryResource.input = [{valueInteger: 1}]
}
const event: APIGatewayProxyEvent = generateMockEvent(body)
const expectedItems = generateExpectedItems()
const transactItem: any =
expectedItems.input?.TransactItems?.[0]?.Put?.Item
transactItem.RepeatNo = 1
const response: APIGatewayProxyResult = await handler(event, {})
expect(response.statusCode).toEqual(201)
expect(JSON.parse(response.body)).toEqual(responseSingleItem)
expect(expectedItems.input.TransactItems[0].Put.Item.RepeatNo).toEqual(1)
expect(dynamoDBMockSend).toHaveBeenCalledWith(
expect.objectContaining(expectedItems)
)
})
it("when multiple items in request, expect multiple items sent to DynamoDB in a single call", async () => {
const body = generateBody(2)
const event: APIGatewayProxyEvent = generateMockEvent(body)
const expectedItems = generateExpectedItems(2)
const response: APIGatewayProxyResult = await handler(event, {})
expect(response.statusCode).toEqual(201)
expect(JSON.parse(response.body)).toEqual(responseMultipleItems)
expect(dynamoDBMockSend).toHaveBeenCalledWith(
expect.objectContaining(expectedItems)
)
})
it.each([
{
example: requestDispatched,
httpResponseCode: 201,
scenarioDescription: "201 with response bundle for a single item"
},
{
example: requestMultipleItems,
httpResponseCode: 201,
scenarioDescription: "201 with response bundle for multiple items"
},
{
example: requestNoItems,
httpResponseCode: 200,
scenarioDescription: "200 status code if there are no entries to process"
}
])(
"should return $scenarioDescription",
async ({example, httpResponseCode}) => {
const event: APIGatewayProxyEvent = generateMockEvent(example)
const response: APIGatewayProxyResult = await handler(event, {})
const responseBody = JSON.parse(response.body)
expect(response.statusCode).toBe(httpResponseCode)
expect(responseBody).toHaveProperty("resourceType", "Bundle")
expect(responseBody).toHaveProperty("type", "transaction-response")
}
)
it("when missing fields, expect 400 status code and message indicating missing fields", async () => {
const event: APIGatewayProxyEvent = generateMockEvent(requestMissingFields)
const response: APIGatewayProxyResult = await handler(event, {})
expect(response.statusCode).toBe(400)
expect(JSON.parse(response.body)).toEqual(
bundleWrap([
badRequest(
"Missing required field(s) - PharmacyODSCode, TaskID.",
FULL_URL_0
)
])
)
})
const testInvalidODSCode = async (invalidODSCode: string, expectedErrorCode: string) => {
const body = generateBody()
const entryResource: any = body.entry?.[0]?.resource
if (entryResource?.owner?.identifier) {
entryResource.owner.identifier.value = invalidODSCode
}
const event: APIGatewayProxyEvent = generateMockEvent(body)
const response: APIGatewayProxyResult = await handler(event, {})
expect(response.statusCode).toBe(400)
expect(JSON.parse(response.body)).toEqual(
bundleWrap([
badRequest(`Received invalid ODS codes: ["${expectedErrorCode}"]`)
])
)
}
it("When the ODS code contains a special character, the handler returns a 400 error", async () => {
await testInvalidODSCode("AB1$%2", "AB1$%2")
})
it("When the ODS code is a space character, the handler returns a 400 error", async () => {
await testInvalidODSCode(" ", "")
})
it("when dynamo call fails, expect 500 status code and internal server error message", async () => {
const event = generateMockEvent(requestDispatched)
dynamoDBMockSend.mockRejectedValue(new Error() as never)
const response: APIGatewayProxyResult = await handler(event, {})
expect(response.statusCode).toEqual(500)
expect(JSON.parse(response.body)).toEqual(bundleWrap([serverError()]))
})
it("when data store update times out, expect 504 status code and relevant error message", async () => {
dynamoDBMockSend.mockImplementation((command) => new Promise((resolve) => {
if (!(command instanceof TransactWriteItemsCommand)) {
resolve(false)
}
// else leave the promise unresolved to simulate a timeout
}))
const event: APIGatewayProxyEvent = generateMockEvent(requestDispatched)
const eventHandler: Promise<APIGatewayProxyResult> = handler(event, {})
await vi.advanceTimersByTimeAsync(LAMBDA_TIMEOUT_MS)
const response = await eventHandler
expect(response.statusCode).toBe(504)
expect(JSON.parse(response.body)).toEqual(bundleWrap([timeoutResponse()]))
})
it("when multiple tasks have missing fields, expect 400 status code and messages indicating missing fields", async () => {
const body: any = {...requestMultipleMissingFields}
const event: APIGatewayProxyEvent = generateMockEvent(body)
const response: APIGatewayProxyResult = await handler(event, {})
expect(response.statusCode).toEqual(400)
expect(JSON.parse(response.body)).toEqual(
bundleWrap([
badRequest(
"Missing required field(s) - PharmacyODSCode, TaskID.",
FULL_URL_0
),
badRequest("Missing required field(s) - PharmacyODSCode.", FULL_URL_1)
])
)
})
it("when x-request-id header is present but empty, expect 400 status code and relevant error message", async () => {
const body = generateBody()
const event: APIGatewayProxyEvent = generateMockEvent(body)
event.headers["x-request-id"] = undefined
const response: APIGatewayProxyResult = await handler(event, {})
expect(response.statusCode).toEqual(400)
expect(JSON.parse(response.body)).toEqual(
bundleWrap([badRequest("Missing or empty x-request-id header.")])
)
})
it("when x-request-id header is missing, expect 400 status code and relevant error message", async () => {
const body = generateBody()
const event: APIGatewayProxyEvent = generateMockEvent(body)
delete event.headers["x-request-id"]
const response: APIGatewayProxyResult = await handler(event, {})
expect(response.statusCode).toEqual(400)
expect(JSON.parse(response.body)).toEqual(
bundleWrap([badRequest("Missing or empty x-request-id header.")])
)
})
it("when x-request-id header is mixed case, expect it to work", async () => {
const body = generateBody()
const event: APIGatewayProxyEvent = generateMockEvent(body)
delete event.headers["x-request-id"]
event.headers["X-Request-id"] = "43313002-debb-49e3-85fa-34812c150242"
const response: APIGatewayProxyResult = await handler(event, {})
expect(response.statusCode).toEqual(201)
})
it("when duplicates are introduced, expect only 409 status with a message, while the other response gives a 200 with message", async () => {
const body = generateBody()
const mockEvent: APIGatewayProxyEvent = generateMockEvent(body)
dynamoDBMockSend.mockRejectedValue(
new TransactionCanceledException({
message:
"DynamoDB transaction cancelled due to conditional check failure.",
$metadata: {},
CancellationReasons: [
{
Code: "ConditionalCheckFailed",
Item: {
TaskID: {S: "d70678c-81e4-6665-8c67-17596fd0aa87"}
},
Message: "The conditional request failed"
}
]
}) as never
)
const response: APIGatewayProxyResult = await handler(mockEvent, {})
const responseBody = JSON.parse(response.body)
expect(response.statusCode).toBe(409)
expect(responseBody.entry).toHaveLength(2)
expect(responseBody.entry[0].fullUrl).toEqual(
"urn:uuid:4d70678c-81e4-4ff4-8c67-17596fd0aa46"
)
expect(responseBody.entry[0].response.status).toEqual("200 OK")
expect(responseBody.entry[0].response.outcome.issue[0].diagnostics).toEqual(
"Data not committed due to issues in other entries."
)
expect(responseBody.entry[1].response.location).toEqual(
"Task/d70678c-81e4-6665-8c67-17596fd0aa87"
)
expect(responseBody.entry[1].response.status).toEqual("409 Conflict")
expect(responseBody.entry[1].response.outcome.issue[0].diagnostics).toEqual(
"Request contains a task id and prescription id identical to a record already in the data store."
)
expect(responseBody.entry[1].response.status).not.toEqual("200 OK")
})
it("when duplicates are introduced without any other entry, expect only 409 status with a message", async () => {
const mockEvent: APIGatewayProxyEvent = generateMockEvent(
requestDuplicateItems
)
dynamoDBMockSend.mockRejectedValue(
new TransactionCanceledException({
message:
"DynamoDB transaction cancelled due to conditional check failure.",
$metadata: {},
CancellationReasons: [
{
Code: "ConditionalCheckFailed",
Item: {
TaskID: {S: "d70678c-81e4-6665-8c67-17596fd0aa87"}
},
Message: "The conditional request failed"
}
]
}) as never
)
const response: APIGatewayProxyResult = await handler(mockEvent, {})
const responseBody = JSON.parse(response.body)
expect(response.statusCode).toBe(409)
expect(responseBody.entry).toHaveLength(1)
expect(responseBody.entry[0].response.location).toEqual(
"Task/d70678c-81e4-6665-8c67-17596fd0aa87"
)
expect(responseBody.entry[0].response.status).toEqual("409 Conflict")
expect(responseBody.entry[0].response.outcome.issue[0].diagnostics).toEqual(
"Request contains a task id and prescription id identical to a record already in the data store."
)
expect(responseBody.entry[0].response.status).not.toEqual("200 OK")
})
function itemQueryResult(taskID: string, status: string, businessStatus: string, lastModified: string) {
return {
PrescriptionID: {S: TASK_VALUES[0].prescriptionID},
PatientNHSNumber: {S: TASK_VALUES[0].nhsNumber},
PharmacyODSCode: {S: TASK_VALUES[0].odsCode},
LineItemID: {S: TASK_VALUES[0].lineItemID},
TaskID: {S: taskID},
TerminalStatus: {S: status},
Status: {S: businessStatus},
LastModified: {S: lastModified}
}
}
it("when updates already exist for an item, logs transitions", async () => {
const body = generateBody()
const mockEvent: APIGatewayProxyEvent = generateMockEvent(body)
const loggerSpy = vi.spyOn(logger, "info")
dynamoDBMockSend.mockImplementation(
async (command) => {
if (command instanceof QueryCommand) {
return new Object({
Items: [
itemQueryResult("71a3cf0d-c096-4b72-be0c-b1dd5f94ab0b", "in-progress", "With Pharmacy", "2023-09-11T10:09:12Z"),
itemQueryResult("c523a80a-5346-46b3-81d2-a7420959c26b", "in-progress", "Ready to Dispatch", "2023-09-11T10:10:12Z"),
itemQueryResult(TASK_VALUES[0].id, TASK_VALUES[0].status, TASK_VALUES[0].businessStatus, TASK_VALUES[0].lastModified)
]
})
}
}
)
const response: APIGatewayProxyResult = await handler(mockEvent, {})
expect(response.statusCode).toBe(201)
expect(loggerSpy).toHaveBeenCalledWith(
"Transitioning item status.",
{
prescriptionID: TASK_VALUES[0].prescriptionID,
lineItemID: TASK_VALUES[0].lineItemID,
nhsNumber: TASK_VALUES[0].nhsNumber,
pharmacyODSCode: TASK_VALUES[0].odsCode,
applicationName: APPLICATION_NAME,
when: "2023-09-11T10:11:12Z",
interval: 60,
newStatus: TASK_VALUES[0].businessStatus,
previousStatus: "Ready to Dispatch",
newTerminalStatus: TASK_VALUES[0].status,
previousTerminalStatus: "in-progress"
}
)
})
it("when the notification SQS push fails, the response still succeeds", async () => {
mockGetParametersByName.mockImplementation(async () => {
return {
[process.env.ENABLE_NOTIFICATIONS_PARAM!]: "true"
}
})
mockPushPrescriptionToNotificationSQS.mockImplementation(
async () => {
throw new Error("Test error")
}
)
const {handler: tmpfn} = await import("../src/updatePrescriptionStatus")
const event: APIGatewayProxyEvent = generateMockEvent(requestDispatched)
const response: APIGatewayProxyResult = await tmpfn(event, {})
expect(response.statusCode).toBe(500)
expect(mockPushPrescriptionToNotificationSQS).toHaveBeenCalled()
})
it("when SQS push throws an error, the response still succeeds", async () => {
mockGetParametersByName.mockImplementation(async () => {
return {
[process.env.ENABLE_NOTIFICATIONS_PARAM!]: "true"
}
})
mockPushPrescriptionToNotificationSQS.mockImplementation(
async () => {
throw new Error("Test error")
}
)
const {handler: tmpfn} = await import("../src/updatePrescriptionStatus")
const event: APIGatewayProxyEvent = generateMockEvent(requestDispatched)
const response: APIGatewayProxyResult = await tmpfn(event, {})
expect(response.statusCode).toBe(500)
expect(mockPushPrescriptionToNotificationSQS).toHaveBeenCalled()
})
it("When the get parameter call throws an error, the request succeeds and the sqs queue is untouched", async () => {
mockGetParametersByName.mockImplementation(async () => Promise.reject(new Error("Failed")))
const {handler: tmpfn} = await import("../src/updatePrescriptionStatus")
const rejected_event: APIGatewayProxyEvent = generateMockEvent(requestDispatched)
const rejected_response: APIGatewayProxyResult = await tmpfn(rejected_event, {})
expect(rejected_response.statusCode).toBe(201)
expect(mockPushPrescriptionToNotificationSQS).not.toHaveBeenCalled()
})
it("When the enable notifications parameter is false, the push to SQS is skipped", async () => {
mockGetParametersByName.mockImplementation(async () => {
return {
[process.env.ENABLE_NOTIFICATIONS_PARAM!]: "false"
}
})
const {handler: tmpfn} = await import("../src/updatePrescriptionStatus")
const bypass_event: APIGatewayProxyEvent = generateMockEvent(requestDispatched)
const bypass_response: APIGatewayProxyResult = await tmpfn(bypass_event, {})
expect(bypass_response.statusCode).toBe(201)
expect(mockPushPrescriptionToNotificationSQS).not.toHaveBeenCalled()
})
it("When the enable notifications parameter is true, the push to SQS is done", async () => {
mockGetParametersByName.mockImplementation(async () => {
return {
[process.env.ENABLE_NOTIFICATIONS_PARAM!]: "true"
}
})
const {handler: tmpfn} = await import("../src/updatePrescriptionStatus")
const successful_event: APIGatewayProxyEvent = generateMockEvent(requestDispatched)
const successful_response: APIGatewayProxyResult = await tmpfn(successful_event, {})
expect(successful_response.statusCode).toBe(201)
expect(mockPushPrescriptionToNotificationSQS).toHaveBeenCalled()
})
it("When the application-name header is missing but required, the lambda returns 400", async () => {
process.env.REQUIRE_APPLICATION_NAME = "TRUE"
const {handler: tmpfn} = await import("../src/updatePrescriptionStatus")
let event: APIGatewayProxyEvent = generateMockEvent(requestDispatched)
event.headers["attribute-name"] = undefined
const response: APIGatewayProxyResult = await tmpfn(event, {})
expect(response.statusCode).toBe(400)
})
it("When the application-name header is missing and NOT required, the lambda returns 201", async () => {
process.env.REQUIRE_APPLICATION_NAME = "false"
const {handler: tmpfn} = await import("../src/updatePrescriptionStatus")
let event: APIGatewayProxyEvent = generateMockEvent(requestDispatched)
event.headers["attribute-name"] = APPLICATION_NAME // explicitly check this is set
const response: APIGatewayProxyResult = await tmpfn(event, {})
expect(response.statusCode).toBe(201)
})
})