-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathhttp.ts
More file actions
201 lines (186 loc) · 6.48 KB
/
http.ts
File metadata and controls
201 lines (186 loc) · 6.48 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
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import * as assert from 'assert';
import * as sinon from 'sinon';
import * as supertest from 'supertest';
import * as functions from '../../src/index';
import {getTestServer} from '../../src/testing';
import {Request, Response, NextFunction} from 'express';
import * as express from 'express';
import {getServer} from '../../src/server';
describe('HTTP Function', () => {
let callCount = 0;
before(() => {
functions.http('testHttpFunction', (req, res) => {
++callCount;
if (req.query.crash) {
throw 'I crashed';
}
res.send({
result: req.body.text,
query: req.query.param,
});
});
});
beforeEach(() => {
callCount = 0;
// Prevent log spew from the PubSub emulator request.
sinon.stub(console, 'error');
});
afterEach(() => {
(console.error as sinon.SinonSpy).restore();
});
const testData = [
{
name: 'POST to empty path',
httpVerb: 'POST',
path: '/',
expectedBody: {result: 'hello'},
expectedStatus: 200,
expectedCallCount: 1,
},
{
name: 'POST to empty path',
httpVerb: 'POST',
path: '/foo',
expectedBody: {result: 'hello'},
expectedStatus: 200,
expectedCallCount: 1,
},
{
name: 'GET with query params',
httpVerb: 'GET',
path: '/foo?param=val',
expectedBody: {query: 'val'},
expectedStatus: 200,
expectedCallCount: 1,
},
{
name: 'GET throws exception',
httpVerb: 'GET',
path: '/foo?crash=true',
expectedBody: {},
expectedStatus: 500,
expectedCallCount: 1,
},
{
name: 'GET favicon.ico',
httpVerb: 'GET',
path: '/favicon.ico',
expectedBody: {},
expectedStatus: 404,
expectedCallCount: 0,
},
{
name: 'with robots.txt',
httpVerb: 'GET',
path: '/robots.txt',
expectedBody: {},
expectedStatus: 404,
expectedCallCount: 0,
},
];
testData.forEach(test => {
it(test.name, async () => {
const st = supertest(getTestServer('testHttpFunction'));
const response = await (
test.httpVerb === 'GET'
? st.get(test.path)
: st.post(test.path).send({text: 'hello'})
).set('Content-Type', 'application/json');
assert.deepStrictEqual(response.body, test.expectedBody);
assert.strictEqual(response.status, test.expectedStatus);
assert.equal(response.get('etag'), null);
assert.strictEqual(callCount, test.expectedCallCount);
});
});
it('default error handler', async () => {
const app = express();
app.post('/foo', async (req, res) => {
res.send('Foo!');
});
app.use(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
(_err: Error, _req: Request, res: Response, _next: NextFunction) => {
res.status(500).send('Caught error!');
}
);
functions.http('testHttpFunction', app);
const malformedBody = '{"key": "value", "anotherKey": }';
const st = supertest(
getServer(app, {
port: '',
target: '',
sourceLocation: '',
signatureType: 'http',
printHelp: false,
enableExecutionId: false,
timeoutMilliseconds: 0,
ignoredRoutes: null,
propagateFrameworkErrors: false,
})
);
const resBody =
'<!DOCTYPE html>\n' +
'<html lang="en">\n' +
'<head>\n' +
'<meta charset="utf-8">\n' +
'<title>Error</title>\n' +
'</head>\n' +
'<body>\n' +
'<pre>SyntaxError: Unexpected token '}', ..."therKey": }" is not valid JSON<br> at JSON.parse (<anonymous>)<br> at parse (/Users/gregei/IdeaProjects/functions-framework-nodejs/node_modules/body-parser/lib/types/json.js:92:19)<br> at /Users/gregei/IdeaProjects/functions-framework-nodejs/node_modules/body-parser/lib/read.js:128:18<br> at AsyncResource.runInAsyncScope (node:async_hooks:211:14)<br> at invokeCallback (/Users/gregei/IdeaProjects/functions-framework-nodejs/node_modules/raw-body/index.js:238:16)<br> at done (/Users/gregei/IdeaProjects/functions-framework-nodejs/node_modules/raw-body/index.js:227:7)<br> at IncomingMessage.onEnd (/Users/gregei/IdeaProjects/functions-framework-nodejs/node_modules/raw-body/index.js:287:7)<br> at IncomingMessage.emit (node:events:518:28)<br> at IncomingMessage.emit (node:domain:552:15)<br> at endReadableNT (node:internal/streams/readable:1698:12)<br> at process.processTicksAndRejections (node:internal/process/task_queues:90:21)</pre>\n' +
'</body>\n' +
'</html>\n';
const response = await st
.post('/foo')
.set('Content-Type', 'application/json')
.send(malformedBody);
assert.strictEqual(response.status, 400);
assert.equal(response.text, resBody);
});
it('user application error handler', async () => {
const app = express();
const resBody = 'Caught error!';
app.post('/foo', async (req, res) => {
res.send('Foo!');
});
app.use(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
(_err: Error, _req: Request, res: Response, _next: NextFunction) => {
res.status(500).send(resBody);
}
);
functions.http('testHttpFunction', app);
const malformedBody = '{"key": "value", "anotherKey": }';
const st = supertest(
getServer(app, {
port: '',
target: '',
sourceLocation: '',
signatureType: 'http',
printHelp: false,
enableExecutionId: false,
timeoutMilliseconds: 0,
ignoredRoutes: null,
propagateFrameworkErrors: true,
})
);
const response = await st
.post('/foo')
.set('Content-Type', 'application/json')
.send(malformedBody);
assert.strictEqual(response.status, 500);
assert.equal(response.text, resBody);
});
});