-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.js
290 lines (239 loc) · 8.04 KB
/
test.js
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
'use strict'
import test from 'node:test'
import assert from 'node:assert'
import {EventEmitter} from 'node:events'
import {idempotencyMiddleware, hashSha256} from './index.js'
// A simple mock cache implementation
function createMockCache({
getValue = null,
getError = null,
setError = null,
} = {}) {
return {
get: async (key) => {
if (getError) throw getError
return getValue
},
set: async (key, value, options) => {
if (setError) throw setError
return true
},
}
}
// A helper to create a mock logger
function createMockLogger() {
return {
errorCalls: [],
error: function (...args) {
this.errorCalls.push(args)
},
}
}
// A helper to create a mock request and response
function createMockReqRes({headers = {}, statusCode = 200} = {}) {
const req = {headers}
req.method = 'POST'
// Mock response as an EventEmitter to simulate the 'end' event.
const res = new EventEmitter()
res.headers = {}
res.setHeader = (name, value) => {
res.headers[name.toLowerCase()] = value
}
res.getHeaders = () => res.headers
res.endCalled = false
res.statusCode = statusCode
res.end = (body) => {
res.endCalled = true
// Simulate 'end' event after a tick
process.nextTick(() => {
// We replicate `onEnd` behavior: the middleware already attached a listener.
// The `on-http-end` library would pass payload with status and body.
const payload = {
status: res.statusCode,
data: body,
}
res.emit('end', payload)
})
}
return {req, res}
}
test('idempotencyMiddleware - no idempotency key provided', async (t) => {
const cache = createMockCache()
const logger = createMockLogger()
let nextCalled = false
const middleware = idempotencyMiddleware({
cache,
ttl: 3600,
logger,
idempotencyHeaderKey: null,
})
const {req, res} = createMockReqRes()
middleware(req, res, () => {
nextCalled = true
})
assert.ok(
nextCalled,
'Next should be called if no idempotency key is present',
)
assert.strictEqual(res.endCalled, false, 'Response should not end')
})
test('idempotencyMiddleware - idempotency key present and cache hit', async (t) => {
const cache = createMockCache({getValue: true})
const logger = createMockLogger()
const middleware = idempotencyMiddleware({cache, ttl: 3600, logger})
const {req, res} = createMockReqRes({headers: {'x-request-id': '123'}})
let nextCalled = false
middleware(req, res, () => {
nextCalled = true
})
// sleep for 5 ms
await new Promise((resolve) => setTimeout(resolve, 5))
assert.strictEqual(
nextCalled,
false,
'Next should not be called if cache hit',
)
assert.strictEqual(
res.statusCode,
204,
'Should return 204 Not Modified if cache hit',
)
assert.strictEqual(
res.headers['content-type'],
'text/plain; charset=utf-8',
'Should set Content-Type header',
)
assert.ok(res.endCalled, 'Should end response')
})
test('idempotencyMiddleware - idempotency key present and cache miss', async (t) => {
const cache = createMockCache({getValue: null})
const logger = createMockLogger()
const middleware = idempotencyMiddleware({cache, ttl: 3600, logger})
const {req, res} = createMockReqRes({headers: {'x-request-id': '123'}})
let nextCalled = false
middleware(req, res, () => {
nextCalled = true
})
// sleep for 5 ms
await new Promise((resolve) => setTimeout(resolve, 5))
assert.ok(nextCalled, 'Next should be called if cache miss')
// Simulate the actual response sending after next (like a route handler)
res.end('Hello World')
// Wait a tick for onEnd to trigger
await new Promise(setImmediate)
// Since status code is 200 (a 2xx), it should set the cache
// We cannot directly assert this without a spy on cache.set
// However, if we simulate a set error scenario in another test, we know it tries to set.
// For now, assume success since no error is thrown.
})
test('idempotencyMiddleware - cache read error', async (t) => {
const cacheError = new Error('Cache Read Error')
const cache = createMockCache({getError: cacheError})
const logger = createMockLogger()
const middleware = idempotencyMiddleware({cache, ttl: 3600, logger})
const {req, res} = createMockReqRes({headers: {'x-request-id': '123'}})
let nextCalled = false
middleware(req, res, () => {
nextCalled = true
})
// sleep for 5 ms
await new Promise((resolve) => setTimeout(resolve, 5))
assert.ok(nextCalled, 'Next should be called even on cache error')
assert.deepStrictEqual(logger.errorCalls[0], [
'IdempotencyMiddleware - Cache READ Error:',
cacheError,
])
})
test('idempotencyMiddleware - cache write error', async (t) => {
const cacheWriteError = new Error('Cache Write Error')
const cache = createMockCache({setError: cacheWriteError})
const logger = createMockLogger()
const middleware = idempotencyMiddleware({cache, ttl: 3600, logger})
const {req, res} = createMockReqRes({headers: {'x-request-id': '123'}})
let nextCalled = false
middleware(req, res, () => {
nextCalled = true
})
// sleep for 5 ms
await new Promise((resolve) => setTimeout(resolve, 5))
assert.ok(nextCalled, 'Next should be called on cache miss')
res.end('Hello World')
await new Promise(setImmediate)
// The cache write should fail
assert.equal(
logger.errorCalls[0][0],
'IdempotencyMiddleware - Cache WRITE Error:',
)
})
test('idempotencyMiddleware - non-2xx response does not cache', async (t) => {
const cache = createMockCache()
const logger = createMockLogger()
const middleware = idempotencyMiddleware({cache, ttl: 3600, logger})
const {req, res} = createMockReqRes({
headers: {'x-request-id': '123'},
statusCode: 400,
})
let nextCalled = false
middleware(req, res, () => {
nextCalled = true
})
// sleep for 5 ms
await new Promise((resolve) => setTimeout(resolve, 5))
assert.ok(nextCalled, 'Next should be called on cache miss')
// End with a 4xx error
res.end('Bad Request')
await new Promise(setImmediate)
// Since status code is not 2xx, it should not attempt to set cache.
// We can't easily verify this without a spy; but at least no errors or logs occur.
assert.strictEqual(logger.errorCalls.length, 0, 'No error logs expected')
})
test('idempotencyMiddleware - should skip GET method', async (t) => {
const cache = createMockCache()
const logger = createMockLogger()
const middleware = idempotencyMiddleware({cache, ttl: 3600, logger})
const {req, res} = createMockReqRes({
headers: {'x-request-id': '123'},
})
let nextCalled = false
req.method = 'GET'
middleware(req, res, () => {
nextCalled = true
})
// sleep for 5 ms
await new Promise((resolve) => setTimeout(resolve, 5))
assert.ok(nextCalled, 'Next should be called on GET method')
})
test('idempotencyMiddleware - should trigger error when cache.get is not a function', async (t) => {
const cache = {}
const logger = createMockLogger()
assert.throws(() => idempotencyMiddleware({cache, ttl: 3600, logger}), {
name: 'Error',
message:
'IdempotencyMiddleware: A valid cache instance with .get and .set methods is required.',
})
})
test('idempotencyMiddleware - should trigger error when cache.set is not a function', async (t) => {
const cache = {}
const logger = createMockLogger()
assert.throws(() => idempotencyMiddleware({cache, ttl: 3600, logger}), {
name: 'Error',
message:
'IdempotencyMiddleware: A valid cache instance with .get and .set methods is required.',
})
})
test('idempotencyMiddleware - should trigger error ttl is not a number', async (t) => {
const cache = createMockCache()
const logger = createMockLogger()
assert.throws(() => idempotencyMiddleware({cache, ttl: '3600', logger}), {
name: 'Error',
message:
'IdempotencyMiddleware: A positive numeric ttl (in milliseconds) is required.',
})
})
test('idempotencyMiddleware - hashSha256 function', async (t) => {
const hash = hashSha256('123')
assert.strictEqual(
hash,
'a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3',
)
})