-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtestSqsClient.test.ts
More file actions
562 lines (489 loc) · 18.8 KB
/
testSqsClient.test.ts
File metadata and controls
562 lines (489 loc) · 18.8 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
import {
describe,
it,
expect,
vi,
beforeEach
} from "vitest"
import type {MockInstance} from "vitest"
import {Logger} from "@aws-lambda-powertools/logger"
import {SendMessageBatchCommand} from "@aws-sdk/client-sqs"
import {createMockDataItem} from "./utils/testUtils"
const {mockSend, mockGetSecret, mockInitiatedSSMProvider} = vi.hoisted(() => {
const mockGetParametersByName = vi.fn(async () => ({
[process.env.ENABLED_SITE_ODS_CODES_PARAM!]: "FA565",
// eslint-disable-next-line max-len
[process.env.ENABLED_SYSTEMS_PARAM!]: "Internal Test System,Apotec Ltd - Apotec CRM - Production,CrxPatientApp,nhsPrescriptionApp,Titan PSU Prod",
[process.env.BLOCKED_SITE_ODS_CODES_PARAM!]: "B3J1Z"
}))
return {
mockSend: vi.fn(),
mockGetSecret: vi.fn().mockImplementation(async () => ({salt: "salt"})),
mockInitiatedSSMProvider: {getParametersByName: mockGetParametersByName}
}
})
vi.mock("@aws-sdk/client-sqs", async (importOriginal: () => Promise<typeof import("@aws-sdk/client-sqs")>) => {
const mod = await importOriginal()
return {
...mod,
SQSClient: vi.fn(class {
send = mockSend
})
}
})
vi.mock("@aws-lambda-powertools/parameters/secrets", async () => ({
__esModule: true,
getSecret: mockGetSecret
}))
vi.mock("@psu-common/utilities", async (importOriginal: () => Promise<typeof import("@psu-common/utilities")>) => {
const mod = await importOriginal()
return {
...mod,
initiatedSSMProvider: mockInitiatedSSMProvider
}
})
const {
pushPrescriptionToNotificationSQS,
saltedHash
} = await import("../src/utils/sqsClient")
const {checkSiteOrSystemIsNotifyEnabled} = await import("../src/validation/notificationSiteAndSystemFilters")
const ORIGINAL_ENV = {...process.env}
describe("Unit tests for pushPrescriptionToNotificationSQS", () => {
let logger: Logger
let infoSpy: MockInstance
let errorSpy: MockInstance
let warnSpy: MockInstance
beforeEach(() => {
vi.resetModules()
vi.clearAllMocks()
// Reset environment
process.env = {...ORIGINAL_ENV}
// Fresh logger and spies
logger = new Logger({serviceName: "test-service"})
infoSpy = vi.spyOn(logger, "info")
errorSpy = vi.spyOn(logger, "error")
warnSpy = vi.spyOn(logger, "warn")
})
it("throws if the SQS URL is not configured", async () => {
process.env.NHS_NOTIFY_PRESCRIPTIONS_SQS_QUEUE_URL = undefined
// Re-import the function so the environment change gets picked up
const {pushPrescriptionToNotificationSQS: tempFunc} = await import("../src/utils/sqsClient")
await expect(
tempFunc("req-123", [], logger)
).rejects.toThrow("Notifications SQS URL not configured")
expect(errorSpy).toHaveBeenCalledWith(
"Notifications SQS URL not found in environment variables"
)
expect(mockSend).not.toHaveBeenCalled()
})
it("throws if the post-dated SQS URL is not configured", async () => {
process.env.POST_DATED_PRESCRIPTIONS_SQS_QUEUE_URL = undefined
const {pushPrescriptionToNotificationSQS: tempFunc} = await import("../src/utils/sqsClient")
await expect(
tempFunc("req-123", [], logger)
).rejects.toThrow("Post-dated Notifications SQS URL not configured")
expect(warnSpy).toHaveBeenCalledWith(
"Post-dated Notifications SQS URL not found in environment variables"
)
expect(mockSend).not.toHaveBeenCalled()
})
it("does nothing when there are no eligible statuses", async () => {
const data = [
{
current: createMockDataItem({Status: "foo_previous"}),
previous: createMockDataItem({Status: "foo"})
},
{
current: createMockDataItem({Status: "bar_previous"}),
previous: createMockDataItem({Status: "bar"})
},
{
current: createMockDataItem({Status: "baz_previous"}),
previous: createMockDataItem({Status: "baz"})
}
]
await expect(
pushPrescriptionToNotificationSQS("req-456", data, logger)
).resolves.toEqual([])
// It logs the initial push attempt, but never actually sends
expect(infoSpy).toHaveBeenCalledWith(
"Checking if any items require notifications",
{numItemsToBeChecked: data.length, sqsUrl: process.env.NHS_NOTIFY_PRESCRIPTIONS_SQS_QUEUE_URL}
)
expect(mockSend).not.toHaveBeenCalled()
})
it("filters out ready to collect items whose status has not changed", async () => {
const data = [
{
current: createMockDataItem({Status: "ready to collect"}),
previous: createMockDataItem({Status: "ready to collect"})
},
{
current: createMockDataItem({Status: "READY TO COLLECT - PARTIAL"}),
previous: createMockDataItem({Status: "ready to collect - partial"})
}
]
await expect(
pushPrescriptionToNotificationSQS("req-no-change", data, logger)
).resolves.toEqual([])
expect(mockSend).not.toHaveBeenCalled()
})
it("sends only 'ready to collect' messages and succeeds", async () => {
const payload = [
{
previous: createMockDataItem({Status: "Old Status"}), // Test case-insensitivity
current: createMockDataItem({Status: "rEaDy To CoLlEcT"})
},
{
previous: createMockDataItem({Status: "Old Status"}),
current: createMockDataItem({Status: "ready to collect - partial"})
},
{
previous: createMockDataItem({Status: "Old Status"}),
current: createMockDataItem({Status: "a status that will never be real"})
}
]
mockSend.mockImplementationOnce(() => Promise.resolve({Successful: [{}]}))
await expect(
pushPrescriptionToNotificationSQS("req-789", payload, logger)
).resolves.toEqual([])
// Should have attempted exactly one SendMessageBatch call
expect(mockSend).toHaveBeenCalledTimes(1)
// Grab the SendMessageBatchCommand that was sent
const sent = mockSend.mock.calls[0][0]
expect(sent).toBeInstanceOf(SendMessageBatchCommand)
if (!(sent instanceof SendMessageBatchCommand)) {
throw new TypeError("Expected a SendMessageBatchCommand")
}
const entries = sent.input.Entries!
expect(entries).toHaveLength(2)
entries.forEach((entry, idx) => {
const original = payload[idx]
expect(entry.Id).toBe(idx.toString())
expect(entry.MessageBody).toBe(
JSON.stringify({...original.current})
)
// FIFO params
expect(entry.MessageGroupId).toBe("req-789")
expect(entry.MessageDeduplicationId).toBe(
saltedHash(`${original.current.PatientNHSNumber}:${original.current.PharmacyODSCode}`, "salt")
)
})
expect(infoSpy).toHaveBeenCalledWith(
"Successfully sent a batch of prescriptions to the SQS",
{result: {Successful: [{}]}, queueUrl: process.env.NHS_NOTIFY_PRESCRIPTIONS_SQS_QUEUE_URL}
)
})
it("routes post-dated and standard notifications to their respective queues", async () => {
const postDatedCurrent = createMockDataItem({
Status: "ready to collect",
PatientNHSNumber: "9999999999",
PharmacyODSCode: "JIM123",
PostDatedLastModifiedSetAt: "2100-01-01T00:00:00Z"
})
const standardCurrent = createMockDataItem({
Status: "ready to collect - partial",
PatientNHSNumber: "8888888888",
PharmacyODSCode: "JIM123"
})
const payload = [
{previous: createMockDataItem({Status: "previous status"}), current: postDatedCurrent},
{previous: createMockDataItem({Status: "previous status"}), current: standardCurrent}
]
mockSend
.mockImplementationOnce(() => Promise.resolve({Successful: [{MessageId: "pd-id"}]}))
.mockImplementationOnce(() => Promise.resolve({Successful: [{MessageId: "std-id"}]}))
const result = await pushPrescriptionToNotificationSQS("req-mixed", payload, logger)
expect(result).toEqual(["pd-id", "std-id"]) // Both have been pushed to SQS, so we get their IDs
expect(mockSend).toHaveBeenCalledTimes(2)
// Check that the send command was called twice, once with each SQS URL
const queueUrls = mockSend.mock.calls.map(call => {
const command = call[0]
expect(command).toBeInstanceOf(SendMessageBatchCommand)
if (!(command instanceof SendMessageBatchCommand)) {
throw new TypeError("Expected a SendMessageBatchCommand")
}
command.input.Entries!.forEach(entry => {
expect(entry.MessageGroupId).toBe("req-mixed")
})
return command.input.QueueUrl
})
expect(queueUrls).toEqual(
expect.arrayContaining([
process.env.POST_DATED_PRESCRIPTIONS_SQS_QUEUE_URL,
process.env.NHS_NOTIFY_PRESCRIPTIONS_SQS_QUEUE_URL
])
)
})
it("rethrows and logs if SendMessageBatchCommand rejects", async () => {
const payload = [
{
previous: createMockDataItem({Status: "previous status"}),
current: createMockDataItem({Status: "ready to collect"})
}
]
const testError = new Error("SQS failure")
mockSend.mockImplementationOnce(() => Promise.reject(testError))
await expect(
pushPrescriptionToNotificationSQS("req-000", payload, logger)
).rejects.toThrow(testError)
expect(errorSpy).toHaveBeenCalledWith(
"Failed to send a batch of prescriptions to the SQS",
{error: testError, queueUrl: process.env.NHS_NOTIFY_PRESCRIPTIONS_SQS_QUEUE_URL}
)
})
it("rejects when the standard queue fails but the post-dated queue succeeds", async () => {
const payload = [
{
previous: createMockDataItem({Status: "previous status"}),
current: createMockDataItem({
Status: "ready to collect",
PatientNHSNumber: "444",
PharmacyODSCode: "DDD",
PostDatedLastModifiedSetAt: "2025-05-01T00:00:00Z"
})
},
{
previous: createMockDataItem({Status: "previous status"}),
current: createMockDataItem({Status: "ready to collect", PatientNHSNumber: "555", PharmacyODSCode: "EEE"})
}
]
const standardQueueError = new Error("Standard queue failure")
mockSend
.mockImplementationOnce(() => Promise.resolve({Successful: [{MessageId: "pd-ok"}]}))
.mockImplementationOnce(() => Promise.reject(standardQueueError))
await expect(
pushPrescriptionToNotificationSQS("req-failure", payload, logger)
).rejects.toThrow(standardQueueError)
expect(errorSpy).toHaveBeenCalledWith(
"Failed to send a batch of prescriptions to the SQS",
{error: standardQueueError, queueUrl: process.env.NHS_NOTIFY_PRESCRIPTIONS_SQS_QUEUE_URL}
)
})
it("Rejects when the post-dated queue fails but the standard queue succeeds", async () => {
const payload = [
{
previous: createMockDataItem({Status: "previous status"}),
current: createMockDataItem({
Status: "ready to collect",
PatientNHSNumber: "777",
PharmacyODSCode: "GGG",
PostDatedLastModifiedSetAt: "2100-12-12T00:00:00Z"
})
},
{
previous: createMockDataItem({Status: "previous status"}),
current: createMockDataItem({Status: "ready to collect", PatientNHSNumber: "888", PharmacyODSCode: "HHH"})
}
]
const postDatedQueueError = new Error("Post-dated queue failure")
mockSend
.mockImplementationOnce(() => Promise.reject(postDatedQueueError))
.mockImplementationOnce(() => Promise.resolve({Successful: [{MessageId: "std-ok"}]}))
await expect(
pushPrescriptionToNotificationSQS("req-failure-2", payload, logger)
).rejects.toThrow(postDatedQueueError)
expect(errorSpy).toHaveBeenCalledWith(
"Failed to send a batch of prescriptions to the SQS",
{error: postDatedQueueError, queueUrl: process.env.POST_DATED_PRESCRIPTIONS_SQS_QUEUE_URL}
)
})
it("chunks large payloads into batches of 10", async () => {
const payload = Array.from({length: 12}, () => {
return {
previous: createMockDataItem({Status: "previous status"}),
current: createMockDataItem({Status: "ready to collect"})
}
})
mockSend
.mockImplementationOnce(() => Promise.resolve({Successful: new Array(10).fill({})}))
.mockImplementationOnce(() => Promise.resolve({Successful: new Array(2).fill({})}))
await pushPrescriptionToNotificationSQS("req-111", payload, logger)
expect(mockSend).toHaveBeenCalledTimes(2)
})
it("Uses the fallback salt value but logs a warning about it", async () => {
mockGetSecret.mockImplementationOnce(async () => {
return {"salt": "DEV SALT"}
})
const payload = Array.from({length: 1}, () => {
return {
previous: createMockDataItem({Status: "previous status"}),
current: createMockDataItem({Status: "ready to collect"})
}
})
mockSend.mockImplementationOnce(() => Promise.resolve({Successful: new Array(2).fill({})}))
await pushPrescriptionToNotificationSQS("req-123", payload, logger)
expect(warnSpy)
.toHaveBeenCalledWith(
"Using the fallback salt value - please update the environment variable `SQS_SALT` to a random value."
)
})
})
describe("Unit tests for getSaltValue", () => {
let getSaltValue: (logger: Logger) => Promise<string>
let logger: Logger
let errorSpy: MockInstance
let warnSpy: MockInstance
const fallbackSalt = "DEV SALT"
beforeEach(async () => {
vi.resetModules()
vi.clearAllMocks()
process.env = {...ORIGINAL_ENV}
logger = new Logger({serviceName: "test-service"})
errorSpy = vi.spyOn(logger, "error")
warnSpy = vi.spyOn(logger, "warn");
({getSaltValue} = await import("../src/utils/sqsClient"))
})
it("returns the fallback salt when SQS_SALT is not configured", async () => {
delete process.env.SQS_SALT
const salt = await getSaltValue(logger)
expect(salt).toBe(fallbackSalt)
expect(warnSpy).toHaveBeenCalledWith(
"Using the fallback salt value - please update the environment variable `SQS_SALT` to a random value."
)
})
it("returns the secret salt when secret has a valid salt field", async () => {
process.env.SQS_SALT = "someSecret"
mockGetSecret.mockImplementationOnce(async () => ({salt: "real-salt"}))
const salt = await getSaltValue(logger)
expect(salt).toBe("real-salt")
expect(warnSpy).not.toHaveBeenCalled()
})
it("falls back and logs an error when secret is missing the salt field", async () => {
process.env.SQS_SALT = "someSecret"
const badValue = {notSalt: "value"}
mockGetSecret.mockImplementationOnce(async () => badValue)
const salt = await getSaltValue(logger)
expect(salt).toBe(fallbackSalt)
expect(errorSpy).toHaveBeenCalledWith(
"Secret did not contain a valid salt field, falling back to DEV SALT",
{secretValue: badValue}
)
expect(warnSpy).toHaveBeenCalledWith(
"Using the fallback salt value - please update the environment variable `SQS_SALT` to a random value."
)
})
it("falls back and logs an error when getSecret throws", async () => {
process.env.SQS_SALT = "someSecret"
const testErr = new Error("failure")
mockGetSecret.mockImplementationOnce(async () => {
throw testErr
})
const salt = await getSaltValue(logger)
expect(salt).toBe(fallbackSalt)
expect(errorSpy).toHaveBeenCalledWith(
"Failed to fetch SQS_SALT from Secrets Manager, using DEV SALT",
{error: testErr}
)
expect(warnSpy).toHaveBeenCalledWith(
"Using the fallback salt value - please update the environment variable `SQS_SALT` to a random value."
)
})
})
describe("Unit tests for checkSiteOrSystemIsNotifyEnabled", () => {
let logger: Logger
let infoSpy: MockInstance
beforeEach(() => {
// Fresh logger and spies
logger = new Logger({serviceName: "test-service"})
infoSpy = vi.spyOn(logger, "info")
})
it("includes an item with an enabled ODS code", async () => {
const previous = createMockDataItem({
PharmacyODSCode: "FA565",
ApplicationName: "not a real test supplier",
Status: "previous"
})
const current = createMockDataItem({
PharmacyODSCode: "FA565",
ApplicationName: "not a real test supplier"
})
const result = await checkSiteOrSystemIsNotifyEnabled([{previous, current}], logger)
expect(result).toStrictEqual([{previous, current}])
expectLogReceivedAndAllowed(infoSpy, 1, 1)
})
it("includes an item with an enabled ApplicationName", async () => {
const previous = createMockDataItem({
PharmacyODSCode: "ZZZ999",
ApplicationName: "Internal Test System",
Status: "previous"
})
const current = createMockDataItem({
PharmacyODSCode: "ZZZ999",
ApplicationName: "Internal Test System"
})
const result = await checkSiteOrSystemIsNotifyEnabled([{previous, current}], logger)
expect(result).toEqual([{previous, current}])
expectLogReceivedAndAllowed(infoSpy, 1, 1)
})
it("is case insensitive for both ODS code and ApplicationName", async () => {
const item1 = createMockDataItem({
PharmacyODSCode: "fa565",
ApplicationName: "not a real test supplier"
})
const item2 = createMockDataItem({
PharmacyODSCode: "zzz999",
ApplicationName: "internal test SYSTEM",
ApplicationID: "550e8400-e29b-41d4-a716-446655440000"
})
const result = await checkSiteOrSystemIsNotifyEnabled([
{
previous: item1,
current: item1
},
{
previous: item2,
current: item2
}
], logger)
expect(result).toEqual([
{
previous: item1,
current: item1
},
{
previous: item2,
current: item2
}
])
})
it("excludes an item when its ODS code is blocked, even if otherwise enabled", async () => {
const previous = createMockDataItem({
PharmacyODSCode: "b3j1z",
ApplicationName: "Internal Test System",
Status: "previous"
})
const current = createMockDataItem({
PharmacyODSCode: "b3j1z",
ApplicationName: "Internal Test System"
})
const result = await checkSiteOrSystemIsNotifyEnabled([{previous, current}], logger)
expect(result).toEqual([])
expectLogReceivedAndAllowed(infoSpy, 1, 0)
})
it("excludes items that are neither enabled nor blocked", async () => {
const previous = createMockDataItem({
PharmacyODSCode: "NOTINLIST",
ApplicationName: "Some Other System",
ApplicationID: "550e8400-e29b-41d4-a716-446655441234",
Status: "previous"
})
const current = createMockDataItem({
PharmacyODSCode: "NOTINLIST",
ApplicationName: "Some Other System",
ApplicationID: "550e8400-e29b-41d4-a716-446655441234"
})
const result = await checkSiteOrSystemIsNotifyEnabled([{previous, current}], logger)
expect(result).toEqual([])
expectLogReceivedAndAllowed(infoSpy, 1, 0)
})
})
function expectLogReceivedAndAllowed(
infoSpy: MockInstance,
numItemsReceived: number,
numItemsAllowed: number) {
expect(infoSpy).toHaveBeenCalledWith(
expect.stringContaining("Filtered out sites and suppliers that are not enabled, or are explicitly disabled"),
expect.objectContaining({numItemsReceived, numItemsAllowed})
)
}