-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtestUtils.test.ts
More file actions
1157 lines (982 loc) · 35.4 KB
/
testUtils.test.ts
File metadata and controls
1157 lines (982 loc) · 35.4 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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
vi,
describe,
it,
expect,
beforeEach,
afterEach,
afterAll
} from "vitest"
import nock from "nock"
import axiosRetry from "axios-retry"
import {Logger} from "@aws-lambda-powertools/logger"
import {DynamoDBDocumentClient, PutCommand} from "@aws-sdk/lib-dynamodb"
import {GetQueueAttributesCommand, DeleteMessageBatchCommand, Message} from "@aws-sdk/client-sqs"
import {LOG_MESSAGES} from "@psu-common/utilities"
import {constructMessage, constructPSUDataItemMessage, mockSQSClient} from "./testHelpers"
const {mockSend: sqsMockSend} = mockSQSClient()
const TEST_URL = "https://example.com"
const {
mockGetParametersByName,
mockGetSecret,
mockTokenExchange,
mockNotifyRequestMaxItems,
mockNotifyRequestMaxBytes
} = vi.hoisted(() => ({
mockGetParametersByName: vi.fn(async () => ({
[process.env.NOTIFY_API_BASE_URL_PARAM!]: "https://example.com",
[process.env.MAKE_REAL_NOTIFY_REQUESTS_PARAM!]: "true"
})),
mockGetSecret: vi.fn().mockImplementation(() => "secret_value"),
mockTokenExchange: vi.fn().mockImplementation(() => Promise.resolve("bearer token")),
mockNotifyRequestMaxItems: 5,
mockNotifyRequestMaxBytes: 5 * 1024 * 1024
}))
vi.mock(
"@aws-lambda-powertools/parameters/ssm",
async () => ({
__esModule: true,
SSMProvider: vi.fn(class {
getParametersByName = mockGetParametersByName
})
})
)
vi.mock(
"@aws-lambda-powertools/parameters/secrets",
async () => ({
__esModule: true,
getSecret: mockGetSecret
})
)
vi.mock(
"../src/utils/auth",
async () => ({
__esModule: true,
tokenExchange: mockTokenExchange
})
)
vi.mock(
"../src/utils/constants",
async () => ({
__esModule: true,
NOTIFY_REQUEST_MAX_ITEMS: mockNotifyRequestMaxItems,
NOTIFY_REQUEST_MAX_BYTES: mockNotifyRequestMaxBytes,
DUMMY_NOTIFY_DELAY_MS: 100,
TTL_DELTA: 60 * 60 * 24 * 14 // Keep records for 2 weeks
})
)
const {
addPrescriptionMessagesToNotificationStateStore,
removeSQSMessages,
checkCooldownForUpdate,
reportQueueStatus,
drainQueue,
handleNotifyRequests
} = await import("../src/utils")
type Spy = ReturnType<typeof vi.spyOn>
const ORIGINAL_ENV = {...process.env}
describe("NHS notify lambda helper functions", () => {
describe("drainQueue", () => {
let logger: Logger
let errorSpy: Spy
let infoSpy: Spy
beforeEach(() => {
vi.resetModules()
vi.clearAllMocks()
process.env = {...ORIGINAL_ENV}
logger = new Logger({serviceName: "test-service"})
errorSpy = vi.spyOn(logger, "error")
infoSpy = vi.spyOn(logger, "info")
})
it("Does not throw an error when the SQS fetch succeeds", async () => {
const payload = {Messages: Array.from({length: 10}, () => (constructMessage()))}
sqsMockSend.mockImplementationOnce(() => Promise.resolve(payload))
const {messages, isEmpty} = await drainQueue(logger, 10)
expect(isEmpty).toBeFalsy()
expect(sqsMockSend).toHaveBeenCalledTimes(1)
expect(messages).toHaveLength(10)
expect(infoSpy).toHaveBeenCalledWith(
"Received some messages from the queue. Parsing them...",
expect.objectContaining({pollingIteration: 1, MessageIDs: expect.any(Array)})
)
})
it("Batches multiple fetches until maxTotal is reached and stops on empty response", async () => {
// First fetch returns 5, second fetch returns 5, third fetch empty
const first = {Messages: Array.from({length: 5}, () => constructMessage())}
const second = {Messages: Array.from({length: 5}, () => constructMessage())}
const empty = {Messages: []}
sqsMockSend
.mockImplementationOnce(() => Promise.resolve(first))
.mockImplementationOnce(() => Promise.resolve(second))
.mockImplementationOnce(() => Promise.resolve(empty))
const {messages, isEmpty} = await drainQueue(logger, 15)
expect(isEmpty).toBeTruthy()
expect(sqsMockSend).toHaveBeenCalledTimes(3)
expect(messages).toHaveLength(10)
expect(infoSpy).toHaveBeenCalledTimes(4)
})
it("Does not return more than the maximum number of messages, even if more are available", async () => {
const mockQueue = () => Promise.resolve({Messages: Array.from({length: 10}, () => constructMessage())})
sqsMockSend.mockImplementation(mockQueue)
const {messages, isEmpty} = await drainQueue(logger, 20)
expect(isEmpty).toBeFalsy()
expect(sqsMockSend).toHaveBeenCalledTimes(2)
expect(messages).toHaveLength(20)
expect(infoSpy).toHaveBeenCalledTimes(3)
})
it("Stops polling the queue if not enough messages are returned from the queue", async () => {
const first = {Messages: Array.from({length: 10}, () => constructMessage())}
const second = {Messages: Array.from({length: 4}, () => constructMessage())}
sqsMockSend
.mockImplementationOnce(() => Promise.resolve(first))
.mockImplementationOnce(() => Promise.resolve(second))
const {messages, isEmpty} = await drainQueue(logger, 20)
expect(isEmpty).toBeTruthy()
expect(sqsMockSend).toHaveBeenCalledTimes(2)
expect(messages).toHaveLength(14)
})
it("returns empty array if queue is empty on first fetch", async () => {
sqsMockSend.mockImplementationOnce(() => Promise.resolve({Messages: []}))
const {messages, isEmpty} = await drainQueue(logger, 5)
expect(isEmpty).toBeTruthy()
expect(messages).toEqual([])
expect(sqsMockSend).toHaveBeenCalledTimes(1)
})
it("Throws an error if the SQS fetch fails", async () => {
sqsMockSend.mockImplementation(() => Promise.reject(new Error("Fetch failed")))
await expect(drainQueue(logger, 10)).rejects.toThrow("Fetch failed")
})
it("Throws no error if a message has no Body", async () => {
const badMsg = constructMessage({Body: undefined})
sqsMockSend.mockImplementationOnce(() => Promise.resolve({Messages: [badMsg]}))
await drainQueue(logger, 1)
expect(errorSpy).toHaveBeenCalledWith(
"Received an invalid SQS message (missing Body) - omitting from processing.",
{offendingMessage: badMsg}
)
})
it("Throws an error if the SQS URL is not configured", async () => {
delete process.env.NHS_NOTIFY_PRESCRIPTIONS_SQS_QUEUE_URL
const {drainQueue: dq} = await import("../src/utils")
await expect(dq(logger)).rejects.toThrow(
"NHS_NOTIFY_PRESCRIPTIONS_SQS_QUEUE_URL not set"
)
expect(errorSpy).toHaveBeenCalledWith("Notifications SQS URL not configured")
})
it("logs error and skips messages with invalid JSON body", async () => {
const invalidMessage = constructMessage({
MessageId: "msg1",
Body: "not-valid-json{"
})
const invalidMessageResponse = {
Messages: [invalidMessage]
}
sqsMockSend.mockResolvedValueOnce(invalidMessageResponse as never)
const result = await drainQueue(logger)
expect(result.messages).toEqual([])
expect(errorSpy).toHaveBeenCalledWith(
"Failed to parse SQS message body as JSON - omitting from processing.",
expect.objectContaining({
offendingMessage: expect.any(Object),
parseError: expect.any(Error)
})
)
})
it("logs error and skips messages without MessageDeduplicationId", async () => {
const messageWithoutDedup = {
MessageId: "msg1",
Body: JSON.stringify({
RequestID: "r1",
PatientNHSNumber: "n1",
PharmacyODSCode: "o1",
TaskID: "t1",
Status: "s1"
}),
Attributes: {}
}
const messageWithoutDedupResponse = {
Messages: [messageWithoutDedup]
}
sqsMockSend.mockResolvedValueOnce(messageWithoutDedupResponse as never)
const result = await drainQueue(logger)
expect(result.messages).toEqual([])
expect(errorSpy).toHaveBeenCalledWith(
"SQS message missing MessageDeduplicationId. Skipping this message",
expect.objectContaining({
messageId: "msg1",
badMessage: expect.any(Object)
})
)
})
it("logs warning and skips duplicate MessageDeduplicationId", async () => {
const dedupId = "dedup-123"
const message1 = constructMessage({
MessageId: "msg1",
Body: JSON.stringify({
RequestID: "r1",
PatientNHSNumber: "n1",
PharmacyODSCode: "o1",
TaskID: "t1",
Status: "s1"
}),
Attributes: {MessageDeduplicationId: dedupId}
})
const message2 = constructMessage({
MessageId: "msg2",
Body: JSON.stringify({
RequestID: "r2",
PatientNHSNumber: "n2",
PharmacyODSCode: "o2",
TaskID: "t2",
Status: "s2"
}),
Attributes: {MessageDeduplicationId: dedupId}
})
const duplicateMessagesResponse = {
Messages: [message1, message2]
}
sqsMockSend.mockResolvedValueOnce(duplicateMessagesResponse as never)
const warnSpy = vi.spyOn(logger, "warn")
const result = await drainQueue(logger)
expect(result.messages).toHaveLength(1)
expect(result.messages[0].MessageId).toBe("msg1")
expect(warnSpy).toHaveBeenCalledWith(
"Duplicate MessageDeduplicationId encountered; skipping duplicate",
expect.objectContaining({
messageId: "msg2",
deduplicationId: dedupId
})
)
})
})
describe("removeSQSMessages", () => {
let logger: Logger
let errorSpy: Spy
let infoSpy: Spy
beforeEach(() => {
vi.resetModules()
vi.clearAllMocks()
process.env = {...ORIGINAL_ENV}
logger = new Logger({serviceName: "test-service"})
errorSpy = vi.spyOn(logger, "error")
infoSpy = vi.spyOn(logger, "info")
})
it("deletes messages in a single batch successfully", async () => {
const messages: Array<Message> = [
constructMessage({MessageId: "msg1", ReceiptHandle: "rh1"}),
constructMessage({MessageId: "msg2", ReceiptHandle: "rh2"})
]
// successful delete (no .Failed)
sqsMockSend.mockImplementationOnce(() => Promise.resolve({}))
await expect(removeSQSMessages(logger, messages))
.resolves
.toBeUndefined()
expect(sqsMockSend).toHaveBeenCalledTimes(1)
const cmd = sqsMockSend.mock.calls[0][0]
expect(cmd).toBeInstanceOf(DeleteMessageBatchCommand)
expect((cmd as DeleteMessageBatchCommand).input).toEqual({
QueueUrl: process.env.NHS_NOTIFY_PRESCRIPTIONS_SQS_QUEUE_URL,
Entries: [
{Id: "msg1", ReceiptHandle: "rh1"},
{Id: "msg2", ReceiptHandle: "rh2"}
]
})
expect(errorSpy).not.toHaveBeenCalled()
})
it("splits into batches of 10 when over the SQS limit", async () => {
const messages: Array<Message> = Array.from({length: 12}, (_, i) =>
constructMessage({MessageId: `msg${i}`, ReceiptHandle: `rh${i}`})
)
// succeed both batches
sqsMockSend.mockImplementation(() => Promise.resolve({}))
await removeSQSMessages(logger, messages)
expect(sqsMockSend).toHaveBeenCalledTimes(2)
// first batch of 10
const firstCmd = sqsMockSend.mock.calls[0][0] as DeleteMessageBatchCommand
expect(firstCmd.input.Entries).toHaveLength(10)
// second batch of 2
const secondCmd = sqsMockSend.mock.calls[1][0] as DeleteMessageBatchCommand
expect(secondCmd.input.Entries).toHaveLength(2)
expect(infoSpy).toHaveBeenCalledWith(
"Deleting batch 1/2",
expect.objectContaining({batchSize: 10, messageIds: expect.any(Array)})
)
expect(infoSpy).toHaveBeenCalledWith(
"Deleting batch 2/2",
expect.objectContaining({batchSize: 2, messageIds: expect.any(Array)})
)
})
it("logs and throws if some deletions fail", async () => {
const messages: Array<Message> = [constructMessage({MessageId: "msg1", ReceiptHandle: "rh1"})]
const failedEntries = [
{Id: "msg1", SenderFault: true, Code: "Error", Message: "fail"}
]
// partial failure
sqsMockSend.mockImplementationOnce(() => Promise.resolve({Failed: failedEntries}))
await removeSQSMessages(logger, messages)
expect(errorSpy).toHaveBeenCalledWith(
"Some messages failed to delete in this batch",
{failed: failedEntries}
)
})
it("Throws an error if the SQS URL is not configured", async () => {
delete process.env.NHS_NOTIFY_PRESCRIPTIONS_SQS_QUEUE_URL
const {removeSQSMessages: clearFunc} = await import("../src/utils")
await expect(clearFunc(logger, [])).rejects.toThrow("NHS_NOTIFY_PRESCRIPTIONS_SQS_QUEUE_URL not set")
expect(errorSpy).toHaveBeenCalledWith("Notifications SQS URL not configured")
})
})
describe("addPrescriptionMessagesToNotificationStateStore", () => {
let logger: Logger
let infoSpy: Spy
let errorSpy: Spy
let sendSpy: Spy
beforeEach(() => {
vi.resetModules()
vi.clearAllMocks()
process.env = {...ORIGINAL_ENV}
logger = new Logger({serviceName: "test-service"})
infoSpy = vi.spyOn(logger, "info")
errorSpy = vi.spyOn(logger, "error")
sendSpy = vi.spyOn(DynamoDBDocumentClient.prototype, "send") as unknown as Spy
})
it("throws and logs error if TABLE_NAME is not set", async () => {
delete process.env.TABLE_NAME
const {addPrescriptionMessagesToNotificationStateStore: addFn} = await import("../src/utils")
await expect(
addFn(logger, [constructPSUDataItemMessage()])
).rejects.toThrow("TABLE_NAME not set")
expect(errorSpy).toHaveBeenCalledWith(
"DynamoDB table not configured"
)
// ensure we never attempted to send
expect(sendSpy).not.toHaveBeenCalled()
})
it("throws and logs error when a DynamoDB write fails", async () => {
const item = constructPSUDataItemMessage()
const awsErr = new Error("AWS error")
sendSpy.mockImplementationOnce(() => Promise.reject(awsErr))
await expect(
addPrescriptionMessagesToNotificationStateStore(logger, [item])
).rejects.toThrow("AWS error")
expect(sendSpy).toHaveBeenCalledTimes(1)
// error log includes the item that failed, and the error
expect(errorSpy).toHaveBeenCalledWith(
"Failed to write to DynamoDB",
{
error: awsErr,
item: expect.any(Object)
}
)
})
it("puts data in DynamoDB and logs correctly when configured", async () => {
const item = constructPSUDataItemMessage()
sendSpy.mockImplementationOnce(() => Promise.resolve({}))
await addPrescriptionMessagesToNotificationStateStore(logger, [item])
expect(infoSpy).toHaveBeenCalledWith(
"Attempting to push data to DynamoDB",
{count: 1}
)
// send was called exactly once with a PutCommand
expect(sendSpy).toHaveBeenCalledTimes(1)
const cmd = sendSpy.mock.calls[0][0] as PutCommand
expect(cmd).toBeInstanceOf(PutCommand)
// No errors
expect(errorSpy).not.toHaveBeenCalled()
})
it("does nothing when passed an empty array", async () => {
await addPrescriptionMessagesToNotificationStateStore(logger, [])
expect(infoSpy).toHaveBeenCalledTimes(1)
expect(infoSpy).toHaveBeenCalledWith("No data to push into DynamoDB.")
expect(sendSpy).not.toHaveBeenCalled()
})
})
describe("checkCooldownForUpdate", () => {
let logger: Logger
let infoSpy: Spy
let errorSpy: Spy
let sendSpy: Spy
beforeEach(async () => {
vi.resetModules()
vi.clearAllMocks()
process.env = {...ORIGINAL_ENV}
logger = new Logger({serviceName: "test-service"})
infoSpy = vi.spyOn(logger, "info")
errorSpy = vi.spyOn(logger, "error")
sendSpy = vi.spyOn(DynamoDBDocumentClient.prototype, "send") as unknown as Spy
})
afterEach(() => {
sendSpy.mockRestore()
})
afterAll(() => {
process.env = {...ORIGINAL_ENV}
})
it("throws if TABLE_NAME is not set", async () => {
delete process.env.TABLE_NAME
const {checkCooldownForUpdate: fn} = await import("../src/utils")
const update = constructPSUDataItemMessage().PSUDataItem
await expect(fn(logger, update)).rejects.toThrow("TABLE_NAME not set")
expect(errorSpy).toHaveBeenCalledWith("DynamoDB table not configured")
})
it("returns true if no previous record exists", async () => {
// send resolves with no item
sendSpy.mockImplementationOnce(() => Promise.resolve({}))
const update = constructPSUDataItemMessage().PSUDataItem
const result = await checkCooldownForUpdate(logger, update, 900)
expect(sendSpy).toHaveBeenCalledTimes(1)
expect(result).toBe(true)
})
it("returns true when last notification is older than default cooldown", async () => {
const pastTs = new Date(Date.now() - (1000 * 901)).toISOString() // 901s ago
sendSpy.mockImplementationOnce(() => {
return {
Items: [
{LastNotificationRequestTimestamp: {S: new Date(Date.now() - 1000 * 5000).toISOString()}}, // very old
{LastNotificationRequestTimestamp: {S: pastTs}}
]
}
})
const update = constructPSUDataItemMessage().PSUDataItem
const result = await checkCooldownForUpdate(logger, update, 900)
expect(result).toBe(true)
})
it("returns false when ANY item is within the cooldown window", async () => {
const recentTs = new Date(Date.now() - 1000 * 300).toISOString() // 300s ago
const oldTs = new Date(Date.now() - 1000 * 10_000).toISOString() // old
sendSpy.mockImplementationOnce(() => {
return {
Items: [
{LastNotificationRequestTimestamp: {S: oldTs}},
{LastNotificationRequestTimestamp: {S: recentTs}} // within cooldown → should suppress
]
}
})
const update = constructPSUDataItemMessage().PSUDataItem
const result = await checkCooldownForUpdate(logger, update, 900)
expect(result).toBe(false)
})
it("honours a custom cooldownPeriod", async () => {
// custom cooldown = 60 seconds, but timestamp is only 30s ago
const recentTs = new Date(Date.now() - 30000).toISOString()
sendSpy.mockImplementationOnce(() => {
return {
Items: [{LastNotificationRequestTimestamp: {S: recentTs}}]
}
})
const update = constructPSUDataItemMessage().PSUDataItem
const result = await checkCooldownForUpdate(logger, update, 60)
expect(result).toBe(false)
})
it("returns false when items exist but none have valid timestamps", async () => {
sendSpy.mockImplementationOnce(() => {
return {
Items: [
{}, // no timestamp attribute
{SomeOtherField: {S: "foo"}}
]
}
})
const update = constructPSUDataItemMessage().PSUDataItem
const result = await checkCooldownForUpdate(logger, update, 900)
expect(result).toBe(false)
})
it("propagates and logs errors from DynamoDB", async () => {
const awsErr = new Error("DDB failure")
sendSpy.mockImplementationOnce(() => Promise.reject(awsErr))
const update = constructPSUDataItemMessage().PSUDataItem
await expect(checkCooldownForUpdate(logger, update)).rejects.toThrow("DDB failure")
})
it("does nothing when passed an empty array", async () => {
await addPrescriptionMessagesToNotificationStateStore(logger, [])
expect(infoSpy).toHaveBeenCalledTimes(1)
expect(infoSpy).toHaveBeenCalledWith("No data to push into DynamoDB.")
expect(sendSpy).not.toHaveBeenCalled()
})
})
describe("handleNotifyRequests", () => {
let logger: Logger
let errorSpy: Spy
let infoSpy: Spy
beforeEach(() => {
process.env = {...ORIGINAL_ENV}
vi.resetModules()
vi.clearAllMocks()
nock.cleanAll()
logger = new Logger({serviceName: "test-service"})
errorSpy = vi.spyOn(logger, "error")
infoSpy = vi.spyOn(logger, "info")
})
afterEach(() => {
process.env = {...ORIGINAL_ENV}
try {
vi.runOnlyPendingTimers()
} catch {
// Ignore when fake timers were not enabled in a test.
}
vi.useRealTimers()
})
it("sends a batch and maps successful messages correctly", async () => {
const data = [
constructPSUDataItemMessage({
PSUDataItem: {
PrescriptionID: "prescription-id",
RequestID: "r1",
PatientNHSNumber: "n1",
PharmacyODSCode: "o1",
TaskID: "t1",
Status: "s1"
}
}),
constructPSUDataItemMessage({
PSUDataItem: {
PrescriptionID: "prescription-id",
RequestID: "r2",
PatientNHSNumber: "n2",
PharmacyODSCode: "o2",
TaskID: "t2",
Status: "s2"
}
})
]
const returnedMessages = [
{
messageReference: data[0].messageReference,
id: "msg-id-1"
}
]
// nock the POST
nock(TEST_URL)
.post("/comms/v1/message-batches")
.reply(201, {
data: {attributes: {messages: returnedMessages}}
})
const result = await handleNotifyRequests(
logger,
"plan-123",
data
)
// Should return one success and one failure
expect(result).toHaveLength(2)
expect(result[0]).toMatchObject({
PSUDataItem: data[0].PSUDataItem,
messageStatus: "requested",
notifyMessageId: "msg-id-1",
messageBatchReference: expect.any(String),
messageReference: expect.any(String)
})
expect(result[1]).toMatchObject({
PSUDataItem: data[1].PSUDataItem,
messageStatus: "notify request failed",
notifyMessageId: undefined,
messageBatchReference: expect.any(String),
messageReference: expect.any(String)
})
// Check that both log messages are present
// TODO, first will be removed once reports updated
expect(infoSpy).toHaveBeenCalledWith(
"Requested notifications OK!",
expect.objectContaining({
messageBatchReference: expect.any(String),
messageReferences: expect.any(Array),
messageStatus: "requested"
})
)
expect(infoSpy).toHaveBeenCalledWith(
LOG_MESSAGES.PSU0002,
expect.objectContaining({
messageBatchReference: expect.any(String),
messageIndex: expect.any(Number)
})
)
})
it("handles non-ok response by marking all as failed", async () => {
const data = [
constructPSUDataItemMessage({
PSUDataItem: {
PrescriptionID: "prescription-id",
RequestID: "rA",
PatientNHSNumber: "nx",
PharmacyODSCode: "ox",
TaskID: "tx",
Status: "st"
}
})
]
nock(TEST_URL)
.post("/comms/v1/message-batches")
.reply(500, "Internal Server Error")
vi.useFakeTimers()
// force retryDelay to 0 so retries happen immediately in tests
vi.spyOn(axiosRetry, "exponentialDelay").mockImplementation(() => 0)
const resultPromise = handleNotifyRequests(
logger,
"plan-xyz",
data
)
// flush retries immediately
await vi.runAllTimersAsync()
const result = await resultPromise
expect(result).toMatchObject([
{
PSUDataItem: data[0].PSUDataItem,
messageStatus: "notify request failed",
notifyMessageId: undefined,
messageBatchReference: expect.any(String),
messageReference: expect.any(String)
}
])
expect(errorSpy).toHaveBeenCalledWith(
"Notify batch request failed",
expect.anything()
)
})
it("handles fetch exceptions by marking all as failed and logging error", async () => {
const data = [
constructPSUDataItemMessage({
PSUDataItem: {
PrescriptionID: "prescription-id",
RequestID: "rX",
PatientNHSNumber: "ny",
PharmacyODSCode: "oy",
TaskID: "ty",
Status: "st"
}
}),
constructPSUDataItemMessage({
PSUDataItem: {
PrescriptionID: "prescription-id",
RequestID: "rY",
PatientNHSNumber: "nz",
PharmacyODSCode: "oz",
TaskID: "tz",
Status: "sx"
}
})
]
// Simulate network failure
nock(TEST_URL)
.post("/comms/v1/message-batches")
.replyWithError(new Error("Network failure"))
const result = await handleNotifyRequests(
logger,
"plan-error",
data
)
expect(result).toHaveLength(2)
result.forEach((r) =>
expect(r).toEqual(
expect.objectContaining({
messageStatus: "notify request failed",
notifyMessageId: undefined
})
)
)
expect(errorSpy).toHaveBeenCalledWith(
"Notify batch request failed",
expect.anything()
)
})
it("splits very large payloads into two recursive batch requests", async () => {
const data = Array.from({length: 7}, (_, i) =>
constructPSUDataItemMessage({
PSUDataItem: {
PrescriptionID: "prescription-id",
RequestID: `r${i}`,
PatientNHSNumber: `n${i}`,
PharmacyODSCode: `o${i}`,
TaskID: `t${i}`,
Status: `s${i}`
}
})
)
// every sub-batch returns an empty messages array
nock(TEST_URL)
.post("/comms/v1/message-batches")
.times(2)
.reply(201, {
data: {attributes: {messages: []}}
})
const result = await handleNotifyRequests(
logger,
"plan-large",
data
)
expect(result).toHaveLength(7) // Returns all items
// Don't repeat the token exchange for each sub-batch
expect(mockTokenExchange).toHaveBeenCalledTimes(1)
expect(errorSpy).not.toHaveBeenCalled()
// Two calls
expect(infoSpy).toHaveBeenCalledWith(
expect.anything(), // not a reporting msg
{count: 3, routingPlanId: "plan-large"}
)
expect(infoSpy).toHaveBeenCalledWith(
expect.anything(), // not a reporting msg
{count: 4, routingPlanId: "plan-large"}
)
})
it("retries after 425/429 with Retry-After header", async () => {
vi.useFakeTimers()
const data = [
constructPSUDataItemMessage({
PSUDataItem: {
PrescriptionID: "prescription-id",
RequestID: "r1",
PatientNHSNumber: "n1",
PharmacyODSCode: "o1",
TaskID: "t1",
Status: "s1"
}
}),
constructPSUDataItemMessage({
PSUDataItem: {
PrescriptionID: "prescription-id",
RequestID: "r2",
PatientNHSNumber: "n2",
PharmacyODSCode: "o2",
TaskID: "t2",
Status: "s2"
}
})
]
const returnedMessages = [
{
messageReference: data[0].Attributes?.MessageDeduplicationId,
id: "msg-id-1"
}
]
// First reply 429 with header
nock(TEST_URL)
.post("/comms/v1/message-batches")
.reply(429, "", {"Retry-After": "2"})
// Then the successful one
.post("/comms/v1/message-batches")
.reply(201, {
data: {attributes: {messages: returnedMessages}}
})
const resultPromise = handleNotifyRequests(
logger,
"plan-retry",
data
)
await vi.runAllTimersAsync()
const result = await resultPromise
expect(result).toHaveLength(2)
})
it("uses a dummy call when the MAKE_REAL_NOTIFY_REQUESTS_PARAM is false", async () => {
mockGetParametersByName.mockImplementation(async () => ({
[process.env.NOTIFY_API_BASE_URL_PARAM!]: TEST_URL,
[process.env.MAKE_REAL_NOTIFY_REQUESTS_PARAM!]: "false"
}))
const {handleNotifyRequests: fn} = await import("../src/utils")
const data = [
constructPSUDataItemMessage({
PSUDataItem: {
PrescriptionID: "prescription-id",
RequestID: "r1",
PatientNHSNumber: "n1",
PharmacyODSCode: "o1",
TaskID: "t1",
Status: "s1"
}
}),
constructPSUDataItemMessage({
PSUDataItem: {
PrescriptionID: "prescription-id",
RequestID: "r2",
PatientNHSNumber: "n2",
PharmacyODSCode: "o2",
TaskID: "t2",
Status: "s2"
}
})
]
// nock the POST to fail, so if nock is called the test will fail
nock(TEST_URL)
.post("/comms/v1/message-batches")
.reply(500)
const result = await fn(
logger,
"plan-123",
data
)
// Should return all successes
expect(result).toHaveLength(2)
expect(result[0]).toMatchObject({
PSUDataItem: data[0].PSUDataItem,
messageStatus: "silent running",
notifyMessageId: expect.any(String), // it will be assigned a dummy ID
messageBatchReference: expect.any(String),
messageReference: expect.any(String)
})
expect(result[1]).toMatchObject({
PSUDataItem: data[1].PSUDataItem,
messageStatus: "silent running",
notifyMessageId: expect.any(String),
messageBatchReference: expect.any(String),
messageReference: expect.any(String)
})
// Check that both log messages are present
// TODO, first will be removed once reports updated
expect(infoSpy).toHaveBeenCalledWith(
"Requested notifications OK!",
expect.objectContaining({
messageBatchReference: expect.any(String),
messageReferences: expect.any(Array),
messageStatus: "silent running"
})
)
expect(infoSpy).toHaveBeenCalledWith(
LOG_MESSAGES.PSU0002,
expect.objectContaining({
reportCode: "PSU0002",
messageBatchReference: expect.any(String),
messageIndex: expect.any(Number)
})
)
})
it("returns empty array when data is empty", async () => {
const result = await handleNotifyRequests(logger, "plan-123", [])
expect(result).toEqual([])
expect(infoSpy).not.toHaveBeenCalled()
})
it("logs error and filters out messages without MessageDeduplicationId", async () => {
const dataWithMixed = [
constructPSUDataItemMessage({
PSUDataItem: {
PrescriptionID: "prescription-id",
RequestID: "r1",
PatientNHSNumber: "n1",