-
Notifications
You must be signed in to change notification settings - Fork 257
Expand file tree
/
Copy pathserverless-express.test.js
More file actions
289 lines (248 loc) · 7.89 KB
/
serverless-express.test.js
File metadata and controls
289 lines (248 loc) · 7.89 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
/**
* @jest-environment node
*/
// require the raw source files to avoid getting the built files - otherwise
// we'd need to rebuild these packages to see any changes reflected in this file
const Bugsnag = require('../../node/src/notifier')
const BugsnagPluginAwsLambda = require('../../plugin-aws-lambda/src/index')
const BugsnagPluginExpress = require('../../plugin-express/src/express')
const serverlessExpress = require('@vendia/serverless-express')
const express = require('express')
let sentEvents
let sentSessions
describe('serverless express', function () {
beforeAll(() => {
jest.spyOn(console, 'debug').mockImplementation(() => {})
})
beforeEach(function () {
sentEvents = []
sentSessions = []
})
it('sets the correct request data for each request', async function () {
const client = makeClient()
const lambdaHandler = makeLambdaHandler(client)
const lambdaEvent = makeAwsLambdaEvent('/abc?a=b&c=d&e=f')
const lambdaContext = makeAwsLambdaContext()
const response = await lambdaHandler(lambdaEvent, lambdaContext)
expect(response.body).toEqual('abc')
expect(response.statusCode).toEqual(200)
expect(sentEvents).toHaveLength(1)
expect(sentSessions).toHaveLength(1)
expect(sentEvents[0].events).toHaveLength(1)
const event = sentEvents[0].events[0]
expect(event.errors).toHaveLength(1)
expect(event.errors[0].errorMessage).toEqual('abc')
expect(event._metadata.request.path).toEqual('/abc')
expect(event._metadata.request.query).toEqual({ a: 'b', c: 'd', e: 'f' })
expect(event.request).toEqual({
body: undefined,
clientIp: '127.0.0.1',
headers: {
accept: '*/*',
host: 'localhost:3000',
'user-agent': 'bugsnag aws lambda test',
'x-forwarded-port': '3000',
'x-forwarded-proto': 'http'
},
httpMethod: 'GET',
url: 'https://localhost/abc?a=b&c=d&e=f',
referer: undefined
})
expect(event._session.toJSON()).toEqual({
events: {
handled: 1,
unhandled: 0
},
id: expect.any(String),
startedAt: expect.any(Date)
})
const lambdaEvent2 = makeAwsLambdaEvent('/xyz?x=a&y=b&z=c')
const response2 = await lambdaHandler(lambdaEvent2, lambdaContext)
expect(response2.body).toEqual('xyz')
expect(response2.statusCode).toEqual(200)
expect(sentEvents).toHaveLength(2)
expect(sentSessions).toHaveLength(2)
expect(sentEvents[1].events).toHaveLength(1)
const event2 = sentEvents[1].events[0]
expect(event2.errors).toHaveLength(1)
expect(event2.errors[0].errorMessage).toEqual('xyz')
expect(event2._metadata.request.path).toEqual('/xyz')
expect(event2._metadata.request.query).toEqual({ x: 'a', y: 'b', z: 'c' })
expect(event2.request).toEqual({
body: undefined,
clientIp: '127.0.0.1',
headers: {
accept: '*/*',
host: 'localhost:3000',
'user-agent': 'bugsnag aws lambda test',
'x-forwarded-port': '3000',
'x-forwarded-proto': 'http'
},
httpMethod: 'GET',
url: 'https://localhost/xyz?x=a&y=b&z=c',
referer: undefined
})
expect(event2._session.toJSON()).toEqual({
events: {
handled: 1,
unhandled: 0
},
id: expect.any(String),
startedAt: expect.any(Date)
})
const lambdaEvent3 = makeAwsLambdaEvent('/aaa?a=1&z=2')
const response3 = await lambdaHandler(lambdaEvent3, lambdaContext)
expect(response3.body).toEqual(':^)')
expect(response3.statusCode).toEqual(200)
expect(sentEvents).toHaveLength(3)
expect(sentSessions).toHaveLength(3)
expect(sentEvents[2].events).toHaveLength(1)
const event3 = sentEvents[2].events[0]
expect(event3.errors).toHaveLength(1)
expect(event3.errors[0].errorMessage).toEqual('aaa')
expect(event3._metadata.request.path).toEqual('/aaa')
expect(event3._metadata.request.query).toEqual({ a: '1', z: '2' })
expect(event3.request).toEqual({
body: undefined,
clientIp: '127.0.0.1',
headers: {
accept: '*/*',
host: 'localhost:3000',
'user-agent': 'bugsnag aws lambda test',
'x-forwarded-port': '3000',
'x-forwarded-proto': 'http'
},
httpMethod: 'GET',
url: 'https://localhost/aaa?a=1&z=2',
referer: undefined
})
expect(event3._session.toJSON()).toEqual({
events: {
handled: 1,
unhandled: 0
},
id: expect.any(String),
startedAt: expect.any(Date)
})
})
})
function makeClient () {
const client = Bugsnag.createClient({
apiKey: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
plugins: [BugsnagPluginAwsLambda, BugsnagPluginExpress]
})
client._setDelivery(() => ({
sendEvent (payload, callback = () => {}) {
sentEvents.push(payload)
callback()
},
sendSession (payload, callback = () => {}) {
sentSessions.push(payload)
callback()
}
}))
return client
}
function makeExpressApp (client) {
const app = express()
const middleware = client.getPlugin('express')
app.use(middleware.requestHandler)
app.get('/', function (req, res) {
throw new Error('oh no')
})
app.get('/abc', function (req, res) {
req.bugsnag.notify(new Error('abc'))
res.send('abc')
})
app.get('/xyz', function (req, res) {
req.bugsnag.notify(new Error('xyz'))
res.send('xyz')
})
app.get('/aaa', function (req, res) {
req.bugsnag.notify(new Error('aaa'))
res.send(':^)')
})
app.use(middleware.errorHandler)
return app
}
function makeLambdaHandler (client) {
const app = makeExpressApp(client)
const bugsnagHandler = client.getPlugin('awsLambda').createHandler()
return bugsnagHandler(serverlessExpress({ app }))
}
function makeAwsLambdaEvent (path = '/') {
const url = new URL(path, 'http://localhost:3000')
const queryStringParameters = {}
const multiValueQueryStringParameters = {}
for (const name of url.searchParams.keys()) {
queryStringParameters[name] = url.searchParams.get(name)
multiValueQueryStringParameters[name] = url.searchParams.getAll(name)
}
return {
body: null,
headers: {
Accept: '*/*',
Host: url.host,
'User-Agent': 'bugsnag aws lambda test',
'X-Forwarded-Port': url.port,
'X-Forwarded-Proto': 'http'
},
httpMethod: 'GET',
isBase64Encoded: true,
multiValueHeaders: {
Accept: ['*/*'],
Host: [url.host],
'User-Agent': ['bugsnag aws lambda test'],
'X-Forwarded-Port': [url.port],
'X-Forwarded-Proto': ['http']
},
multiValueQueryStringParameters,
path: url.pathname,
pathParameters: {
proxy: url.pathname.replace(/^\//, '')
},
queryStringParameters,
requestContext: {
accountId: '123456789012',
apiId: '1234567890',
domainName: url.host,
extendedRequestId: null,
httpMethod: 'GET',
identity: {
accountId: null,
apiKey: null,
caller: null,
cognitoAuthenticationProvider: null,
cognitoAuthenticationType: null,
cognitoIdentityPoolId: null,
sourceIp: '127.0.0.1',
user: null,
userAgent: 'Custom User Agent String',
userArn: null
},
path: '/{proxy+}',
protocol: 'HTTP/1.1',
requestId: '96b29547-f073-41b7-98f0-96040733b229',
requestTime: '01/Dec/2022:08:55:43 +0000',
requestTimeEpoch: 1669884943,
resourceId: '123456',
resourcePath: '/{proxy+}',
stage: 'prod'
},
resource: '/{proxy+}',
stageVariables: null,
version: 1.0
}
}
function makeAwsLambdaContext () {
return {
awsRequestId: 'f0d6ee94-8baa-46bc-a4fe-22bf52a1fb28',
callbackWaitsForEmptyEventLoop: true,
functionName: 'ExpressFunction',
functionVersion: '$LATEST',
invokedFunctionArn: 'arn:aws:lambda:us-east-1:012345678912:function:ExpressFunction',
logGroupName: 'aws/lambda/ExpressFunction',
logStreamName: '$LATEST',
memoryLimitInMB: 128
}
}