-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtestNhsNotifyLambda.test.ts
More file actions
337 lines (282 loc) · 11.3 KB
/
testNhsNotifyLambda.test.ts
File metadata and controls
337 lines (282 loc) · 11.3 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
import {
vi,
describe,
it,
expect,
beforeAll,
beforeEach,
afterEach
} from "vitest"
import {constructPSUDataItem, constructPSUDataItemMessage} from "./testHelpers"
const {
mockGetParameter,
mockAddPrescriptionMessagesToNotificationStateStore,
mockRemoveSQSMessages,
mockReportQueueStatus,
mockDrainQueue,
mockCheckCooldownForUpdate,
mockMakeBatchNotifyRequest,
mockInfo,
mockError,
mockWarn
} = vi.hoisted(() => ({
mockGetParameter: vi.fn().mockImplementation(() => "parameter_value"),
mockAddPrescriptionMessagesToNotificationStateStore: vi.fn(),
mockRemoveSQSMessages: vi.fn(),
mockReportQueueStatus: vi.fn(),
mockDrainQueue: vi.fn(),
mockCheckCooldownForUpdate: vi.fn(),
mockMakeBatchNotifyRequest: vi.fn(),
mockInfo: vi.fn(),
mockError: vi.fn(),
mockWarn: vi.fn()
}))
vi.mock(
"@aws-lambda-powertools/parameters/ssm",
async () => ({
__esModule: true,
getParameter: mockGetParameter
})
)
vi.mock(
"../src/utils",
async () => ({
__esModule: true,
reportQueueStatus: mockReportQueueStatus,
drainQueue: mockDrainQueue,
addPrescriptionMessagesToNotificationStateStore: mockAddPrescriptionMessagesToNotificationStateStore,
removeSQSMessages: mockRemoveSQSMessages,
checkCooldownForUpdate: mockCheckCooldownForUpdate,
handleNotifyRequests: mockMakeBatchNotifyRequest
})
)
vi.mock(
"@aws-lambda-powertools/logger",
async () => ({
__esModule: true,
Logger: vi.fn(class {
info = mockInfo
error = mockError
warn = mockWarn
})
})
)
let lambdaHandler: typeof import("../src/nhsNotifyLambda").lambdaHandler
beforeAll(async () => {
({lambdaHandler} = await import("../src/nhsNotifyLambda"))
})
import {mockEventBridgeEvent} from "@psu-common/testing"
const ORIGINAL_ENV = {...process.env}
describe("Unit test for NHS Notify lambda handler", () => {
beforeEach(() => {
mockGetParameter.mockReset()
mockGetParameter.mockImplementation(() => "parameter_value")
})
afterEach(() => {
process.env = {...ORIGINAL_ENV}
vi.clearAllMocks()
})
it("When the getParameter call fails, the handler throws an error", async () => {
mockGetParameter.mockImplementationOnce(() => Promise.resolve(undefined))
await expect(lambdaHandler(mockEventBridgeEvent)).rejects.toThrow("No Routing Plan ID found")
})
it("When drainQueue throws an error, the handler throws an error", async () => {
mockDrainQueue.mockImplementation(() => Promise.reject(new Error("Failed")))
await expect(lambdaHandler(mockEventBridgeEvent)).rejects.toThrow("Failed")
})
it("When drainQueue returns no messages, the request succeeds", async () => {
mockDrainQueue.mockImplementation(() => Promise.resolve({messages: [], isEmpty: true}))
await expect(lambdaHandler(mockEventBridgeEvent)).resolves.not.toThrow()
expect(mockCheckCooldownForUpdate).not.toHaveBeenCalled()
expect(mockInfo).toHaveBeenCalledWith("No messages to process")
})
it("Clears completed messages after successful processing", async () => {
const item1 = constructPSUDataItem({TaskID: "t1", RequestID: "r1"})
const item2 = constructPSUDataItem({TaskID: "t2", RequestID: "r2"})
const msg1 = constructPSUDataItemMessage({PSUDataItem: item1})
const msg2 = constructPSUDataItemMessage({PSUDataItem: item2})
// drainQueue returns two messages
mockDrainQueue.mockImplementationOnce(() => Promise.resolve({messages: [msg1, msg2], isEmpty: true}))
// deletion succeeds
mockRemoveSQSMessages.mockImplementation(() => Promise.resolve())
// Checking cooldown
mockCheckCooldownForUpdate.mockImplementation(() => Promise.resolve(true))
// Notify request succeeds
mockMakeBatchNotifyRequest.mockImplementationOnce(() => Promise.resolve(
[
{...msg1, success: true, notifyMessageId: "message1"},
{...msg2, success: true, notifyMessageId: "message2"}
]
))
await expect(lambdaHandler(mockEventBridgeEvent)).resolves.not.toThrow()
expect(mockCheckCooldownForUpdate).toHaveBeenCalledTimes(2)
expect(mockMakeBatchNotifyRequest).toHaveBeenCalledTimes(1)
// ensure removeSQSMessages was called with the original messages array
expect(mockRemoveSQSMessages).toHaveBeenCalledWith(
expect.any(Object), // the logger instance
[
expect.objectContaining({
...msg1,
success: true,
notifyMessageId: expect.any(String)
}),
expect.objectContaining({
...msg2,
success: true,
notifyMessageId: expect.any(String)
})
]
)
})
it("Throws and logs if removeSQSMessages fails", async () => {
const item = constructPSUDataItem({TaskID: "tx", RequestID: "rx"})
const msg = constructPSUDataItemMessage({PSUDataItem: item})
mockDrainQueue.mockImplementationOnce(() => Promise.resolve({messages: [msg], isEmpty: true}))
mockCheckCooldownForUpdate.mockImplementation(() => Promise.resolve(true))
// Notify request succeeds
mockMakeBatchNotifyRequest.mockImplementationOnce(() => Promise.resolve(
[
{...msg, success: true, notifyMessageId: "message"}
]
))
const deletionError = new Error("Delete failed")
mockRemoveSQSMessages.mockImplementationOnce(() => Promise.reject(deletionError))
await expect(lambdaHandler(mockEventBridgeEvent)).rejects.toThrow("Delete failed")
})
it("Throws and logs if addPrescriptionMessagesToNotificationStateStore fails", async () => {
const msg = constructPSUDataItemMessage()
mockDrainQueue.mockImplementationOnce(
() => Promise.resolve({messages: [msg], isEmpty: true})
)
mockCheckCooldownForUpdate.mockImplementation(() => Promise.resolve(true))
const thrownError = new Error("Failed")
mockAddPrescriptionMessagesToNotificationStateStore.mockImplementationOnce(
() => Promise.reject(thrownError)
)
// Notify request succeeds
mockMakeBatchNotifyRequest.mockImplementationOnce(() => Promise.resolve(
[{...msg, success: true, notifyMessageId: "message"}]
))
await expect(lambdaHandler(mockEventBridgeEvent)).rejects.toThrow("Failed")
})
it("When drainQueue returns only valid messages, all are processed", async () => {
const validItem = constructPSUDataItem({
PrescriptionID: "abc123",
TaskID: "task-1",
RequestID: "req-1"
})
const message = constructPSUDataItemMessage({PSUDataItem: validItem})
mockDrainQueue.mockImplementation(
() => Promise.resolve({messages: [message], isEmpty: true})
)
mockCheckCooldownForUpdate.mockImplementation(() => Promise.resolve(true))
// Notify request succeeds
mockMakeBatchNotifyRequest.mockImplementationOnce(() => Promise.resolve(
[
{...message, success: true, notifyMessageId: "message"}
]
))
await expect(lambdaHandler(mockEventBridgeEvent)).resolves.not.toThrow()
expect(mockError).not.toHaveBeenCalled()
expect(mockGetParameter).toHaveBeenCalledWith(process.env.NHS_NOTIFY_ROUTING_ID_PARAM)
})
it("Filters out messages inside cooldown", async () => {
const fresh = constructPSUDataItem({RequestID: "fresh", TaskID: "t1"})
const stale = constructPSUDataItem({RequestID: "stale", TaskID: "t2"})
const msgFresh = constructPSUDataItemMessage({PSUDataItem: fresh})
const msgStale = constructPSUDataItemMessage({PSUDataItem: stale})
mockDrainQueue.mockImplementation(
() => Promise.resolve({messages: [msgFresh, msgStale], isEmpty: true})
)
// returns true if the request ID is "fresh"
mockCheckCooldownForUpdate.mockImplementation((logger, update) => {
const u = update as {RequestID: string}
return Promise.resolve(u.RequestID === "fresh")
})
// Notify request succeeds
mockMakeBatchNotifyRequest.mockImplementationOnce(() => Promise.resolve(
[
{...msgFresh, success: true, notifyMessageId: "message"}
]
))
mockRemoveSQSMessages.mockImplementation(() => Promise.resolve())
mockAddPrescriptionMessagesToNotificationStateStore.mockImplementation(() => Promise.resolve())
await expect(lambdaHandler(mockEventBridgeEvent)).resolves.not.toThrow()
// we should only persist & delete the fresh one
expect(mockAddPrescriptionMessagesToNotificationStateStore)
.toHaveBeenCalledWith(expect.any(Object),
[
expect.objectContaining({
...msgFresh,
success: true,
notifyMessageId: expect.any(String)
})
]
)
expect(mockRemoveSQSMessages)
.toHaveBeenCalledWith(expect.any(Object),
[
expect.objectContaining({
...msgFresh,
success: true,
notifyMessageId: expect.any(String)
})
]
)
// and log how many were suppressed
expect(mockInfo).toHaveBeenCalledWith(
"Suppressed 1 messages due to cooldown",
{suppressedCount: 1, totalFetched: 2}
)
})
it("Logs a message when all messages are inside cooldown", async () => {
const stale = constructPSUDataItem({RequestID: "stale", TaskID: "t1"})
const msgStale = constructPSUDataItemMessage({PSUDataItem: stale})
mockDrainQueue.mockImplementation(
() => Promise.resolve({messages: [msgStale], isEmpty: true})
)
// returns true if the request ID is "fresh"
mockCheckCooldownForUpdate.mockImplementation((logger, update) => {
const u = update as {RequestID: string}
return Promise.resolve(u.RequestID === "fresh")
})
mockRemoveSQSMessages.mockImplementation(() => Promise.resolve())
mockAddPrescriptionMessagesToNotificationStateStore.mockImplementation(() => Promise.resolve())
mockMakeBatchNotifyRequest.mockImplementation(() => Promise.resolve([])) // This function never returns undefined
await lambdaHandler(mockEventBridgeEvent)
expect(mockAddPrescriptionMessagesToNotificationStateStore).not.toHaveBeenCalled()
expect(mockRemoveSQSMessages).toHaveBeenCalledWith(
expect.any(Object),
[expect.objectContaining(msgStale)]
)
// and log that everything was suppressed
expect(mockInfo)
.toHaveBeenCalledWith(
"All messages suppressed by cooldown; nothing to notify",
{suppressedCount: 1, totalFetched: 1}
)
})
it("Stops draining after 14 minutes", async () => {
const msg = constructPSUDataItemMessage()
// call returns a non‐empty batch so the loop should continue
mockDrainQueue.mockImplementation(() =>
Promise.resolve({messages: [msg], isEmpty: false})
)
const nowSpy = vi.spyOn(Date, "now")
.mockImplementationOnce(() => 0) // start time
.mockImplementationOnce(() => (14 * 60 * 1000) + 1)
// Happy‐path for everything else
mockCheckCooldownForUpdate.mockReturnValueOnce(Promise.resolve(true))
mockMakeBatchNotifyRequest.mockReturnValueOnce(Promise.resolve([
{...msg, success: true, notifyMessageId: "m1"}
]))
mockAddPrescriptionMessagesToNotificationStateStore.mockReturnValueOnce(() => Promise.resolve())
mockRemoveSQSMessages.mockReturnValueOnce(() => Promise.resolve())
await expect(lambdaHandler(mockEventBridgeEvent)).resolves.not.toThrow()
// Calls a warning
expect(mockWarn).toHaveBeenCalledTimes(1)
// Since the timer advances before the promise resolves, this never gets called
expect(mockDrainQueue).toHaveBeenCalledTimes(0)
nowSpy.mockRestore()
})
})