-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtestSqs.test.ts
More file actions
312 lines (253 loc) · 10.7 KB
/
testSqs.test.ts
File metadata and controls
312 lines (253 loc) · 10.7 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
import {
describe,
it,
expect,
vi,
beforeEach
} from "vitest"
import {Logger} from "@aws-lambda-powertools/logger"
import {PostDatedSQSMessage} from "../src/types"
import {createMockPostModifiedDataItem} from "./testUtils"
type Spy = ReturnType<typeof vi.spyOn>
const {mockSend} = vi.hoisted(() => ({
mockSend: vi.fn()
}))
vi.mock("@aws-sdk/client-sqs", async () => {
const sqs = await vi.importActual<typeof import("@aws-sdk/client-sqs")>("@aws-sdk/client-sqs")
return {
...sqs,
SQSClient: vi.fn(class {
send = mockSend
})
}
})
const {
getPostDatedQueueUrl,
reportQueueStatus,
receivePostDatedSQSMessages,
removeSQSMessage,
returnMessageToQueue,
forwardSQSMessageToNotificationQueue
} = await import("../src/sqs")
const ORIGINAL_ENV = {...process.env}
describe("sqs", () => {
let logger: Logger
let infoSpy: Spy
let errorSpy: Spy
beforeEach(() => {
vi.resetModules()
vi.clearAllMocks()
// Reset environment
process.env = {...ORIGINAL_ENV}
delete process.env.SQS_SALT
// Fresh logger and spies
logger = new Logger({serviceName: "test-service"})
infoSpy = vi.spyOn(logger, "info")
errorSpy = vi.spyOn(logger, "error")
})
describe("getPostDatedQueueUrl", () => {
it("Should return the SQS queue URL from environment variables", () => {
const testUrl = "https://sqs.us-east-1.amazonaws.com/123456789012/test-queue"
process.env.POST_DATED_PRESCRIPTIONS_SQS_QUEUE_URL = testUrl
const result = getPostDatedQueueUrl(logger)
expect(result).toBe(testUrl)
})
it("Should throw an error if the SQS queue URL is not configured", () => {
delete process.env.POST_DATED_PRESCRIPTIONS_SQS_QUEUE_URL
expect(() => getPostDatedQueueUrl(logger)).toThrow("POST_DATED_PRESCRIPTIONS_SQS_QUEUE_URL not set")
expect(errorSpy).toHaveBeenCalledWith("Post-dated prescriptions SQS URL not configured")
})
})
describe("reportQueueStatus", () => {
it("Should report the current status of the SQS queue", async () => {
const testUrl = "https://sqs.us-east-1.amazonaws.com/123456789012/test-queue"
process.env.POST_DATED_PRESCRIPTIONS_SQS_QUEUE_URL = testUrl
// Mock SQS response
mockSend.mockReturnValueOnce({
Attributes: {
ApproximateNumberOfMessages: "5",
ApproximateNumberOfMessagesNotVisible: "2",
ApproximateNumberOfMessagesDelayed: "1"
}
})
await reportQueueStatus(logger)
expect(mockSend).toHaveBeenCalledTimes(1)
expect(infoSpy).toHaveBeenCalledWith(
"Current post-dated queue attributes (if a value failed to fetch, it will be reported as -1):",
{
ApproximateNumberOfMessages: 5,
ApproximateNumberOfMessagesNotVisible: 2,
ApproximateNumberOfMessagesDelayed: 1
}
)
})
it("Should handle missing attributes gracefully", async () => {
const testUrl = "https://sqs.us-east-1.amazonaws.com/123456789012/test-queue"
process.env.POST_DATED_PRESCRIPTIONS_SQS_QUEUE_URL = testUrl
// Mock SQS response with missing attributes
mockSend.mockReturnValueOnce({
Attributes: {}
})
await reportQueueStatus(logger)
expect(mockSend).toHaveBeenCalledTimes(1)
expect(infoSpy).toHaveBeenCalledWith(
"Current post-dated queue attributes (if a value failed to fetch, it will be reported as -1):",
{
ApproximateNumberOfMessages: -1,
ApproximateNumberOfMessagesNotVisible: -1,
ApproximateNumberOfMessagesDelayed: -1
}
)
})
})
describe("receivePostDatedSQSMessages", () => {
it("Should receive messages from the SQS queue", async () => {
const testUrl = "https://sqs.us-east-1.amazonaws.com/123456789012/test-queue"
process.env.POST_DATED_PRESCRIPTIONS_SQS_QUEUE_URL = testUrl
// Mock SQS response with messages
const mockMessages = [
{
MessageId: "1",
Body: JSON.stringify({PrescriptionID: "presc1"}),
Attributes: {MessageDeduplicationId: "dedup1", MessageGroupId: "group1"}
},
{
MessageId: "2",
Body: JSON.stringify({PrescriptionID: "presc2"}),
Attributes: {MessageDeduplicationId: "dedup2", MessageGroupId: "group2"}
}
]
mockSend.mockReturnValueOnce({
Messages: mockMessages
})
const result = await receivePostDatedSQSMessages(logger)
expect(mockSend).toHaveBeenCalledTimes(1)
const receiveCommand = mockSend.mock.calls[0][0] as {
input: {MessageAttributeNames?: Array<string>; MessageSystemAttributeNames?: Array<string>}
}
expect(receiveCommand.input.MessageSystemAttributeNames).toEqual(["MessageDeduplicationId", "MessageGroupId"])
expect(receiveCommand.input.MessageAttributeNames).toEqual(["All"])
expect(result).toHaveLength(2)
expect(result[0].MessageId).toBe("1")
expect(result[0].prescriptionData.PrescriptionID).toBe("presc1")
expect(result[1].MessageId).toBe("2")
expect(result[1].prescriptionData.PrescriptionID).toBe("presc2")
})
it("Should return an empty array if no messages are received", async () => {
const testUrl = "https://sqs.us-east-1.amazonaws.com/123456789012/test-queue"
process.env.POST_DATED_PRESCRIPTIONS_SQS_QUEUE_URL = testUrl
// Mock SQS response with no messages
mockSend.mockReturnValueOnce({
Messages: []
})
const result = await receivePostDatedSQSMessages(logger)
expect(mockSend).toHaveBeenCalledTimes(1)
expect(result).toHaveLength(0)
})
})
describe("forwardSQSMessageToNotificationQueue", () => {
it("should send a matured post-dated message to the notifications queue", async () => {
const notifyUrl = "https://sqs.eu-west-2.amazonaws.com/123456789012/notify"
process.env.NHS_NOTIFY_PRESCRIPTIONS_SQS_QUEUE_URL = notifyUrl
const message: PostDatedSQSMessage = {
MessageId: "1",
ReceiptHandle: "handle-1",
prescriptionData: createMockPostModifiedDataItem({RequestID: "req-1"}),
Attributes: {MessageDeduplicationId: "dedup1", MessageGroupId: "group1"}
}
mockSend.mockReturnValueOnce({
Successful: [{Id: "0", MessageId: "notify-msg-1"}],
Failed: []
})
const result = await forwardSQSMessageToNotificationQueue(logger, message)
expect(mockSend).toHaveBeenCalledTimes(1)
const command = mockSend.mock.calls[0][0] as {input: {QueueUrl: string; Entries: Array<{MessageBody: string}>}}
expect(command.input.QueueUrl).toBe(notifyUrl)
expect(command.input.Entries[0].MessageBody).toBe(JSON.stringify(message.prescriptionData))
expect(result).toBe("notify-msg-1")
})
it("should throw an error if the deduplication ID is missing", async () => {
process.env.NHS_NOTIFY_PRESCRIPTIONS_SQS_QUEUE_URL = "https://sqs.eu-west-2.amazonaws.com/123456789012/notify"
const message: PostDatedSQSMessage = {
MessageId: "1",
ReceiptHandle: "handle-1",
prescriptionData: createMockPostModifiedDataItem({RequestID: "req-1"}),
Attributes: {} // Missing MessageDeduplicationId
}
await expect(
forwardSQSMessageToNotificationQueue(logger, message)
).rejects.toThrow("Missing MessageDeduplicationId in SQS message attributes")
expect(mockSend).not.toHaveBeenCalled()
})
})
describe("removeSQSMessage", () => {
it("Should remove a message from the SQS queue", async () => {
const testUrl = "https://sqs.us-east-1.amazonaws.com/123456789012/test-queue"
process.env.POST_DATED_PRESCRIPTIONS_SQS_QUEUE_URL = testUrl
const messageToRemove = {MessageId: "1", ReceiptHandle: "handle1"}
// Mock SQS delete response
mockSend.mockReturnValueOnce({
Successful: [{Id: messageToRemove.MessageId}],
Failed: []
})
await removeSQSMessage(logger, messageToRemove)
expect(mockSend).toHaveBeenCalledTimes(1)
expect(infoSpy).toHaveBeenCalledWith("Successfully removed 1 messages from SQS")
})
it("Should log errors but not throw if deletion fails", async () => {
// We don't want to throw on failed deletions, as this would cause
// later batches to be skipped unnecessarily.
// The messages that are failed to delete will become visible and be processed again after the visibility timeout
const testUrl = "https://sqs.us-east-1.amazonaws.com/123456789012/test-queue"
process.env.POST_DATED_PRESCRIPTIONS_SQS_QUEUE_URL = testUrl
const messageToRemove = {MessageId: "1", ReceiptHandle: "handle1"}
// Mock SQS delete response with failures
mockSend.mockReturnValueOnce({
Successful: [],
Failed: [{Id: "1", Message: "Some error"}]
})
await removeSQSMessage(logger, messageToRemove)
expect(mockSend).toHaveBeenCalledTimes(1)
expect(errorSpy).toHaveBeenCalledWith("Some messages failed to delete", {
failed: [{Id: "1", Message: "Some error"}]
})
})
})
describe("returnMessageToQueue", () => {
it("Should return a message to the SQS queue by updating its visibility timeout", async () => {
const testUrl = "https://sqs.us-east-1.amazonaws.com/123456789012/test-queue"
process.env.POST_DATED_PRESCRIPTIONS_SQS_QUEUE_URL = testUrl
const messageToReturn: PostDatedSQSMessage = {
MessageId: "1",
ReceiptHandle: "handle1",
prescriptionData: createMockPostModifiedDataItem({})
}
// Mock SQS change visibility response
mockSend.mockReturnValueOnce({
// No specific return value needed for ChangeMessageVisibilityBatch
})
await returnMessageToQueue(logger, messageToReturn)
expect(mockSend).toHaveBeenCalledTimes(1)
expect(infoSpy).toHaveBeenCalledWith("Returning message to queue with timeouts", {
sqsMessage: messageToReturn,
visibilityTimeout: 300
})
expect(errorSpy).not.toHaveBeenCalled()
})
it("should log an error if SQS change visibility fails", async () => {
const testUrl = "https://sqs.us-east-1.amazonaws.com/123456789012/test-queue"
process.env.POST_DATED_PRESCRIPTIONS_SQS_QUEUE_URL = testUrl
const messageToReturn: PostDatedSQSMessage = {
MessageId: "1",
ReceiptHandle: "handle1",
prescriptionData: createMockPostModifiedDataItem({})
}
// Mock SQS change visibility to throw an error
const expectedError = new Error("SQS change visibility failed")
mockSend.mockReturnValueOnce(Promise.reject(expectedError))
await returnMessageToQueue(logger, messageToReturn)
expect(mockSend).toHaveBeenCalledTimes(1)
expect(errorSpy).toHaveBeenCalledWith("SQS change visibility failed", {error: expectedError})
})
})
})