-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathhttpServer.test.js
More file actions
360 lines (294 loc) · 11.1 KB
/
httpServer.test.js
File metadata and controls
360 lines (294 loc) · 11.1 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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
// Import Node.js Dependencies
import fs from "node:fs";
import { fileURLToPath } from "node:url";
import { after, before, describe, test } from "node:test";
import { once } from "node:events";
import path from "node:path";
import assert from "node:assert";
// Import Third-party Dependencies
import { get, post, MockAgent, getGlobalDispatcher, setGlobalDispatcher } from "@myunisoft/httpie";
import zup from "zup";
import * as i18n from "@nodesecure/i18n";
import * as flags from "@nodesecure/flags";
import enableDestroy from "server-destroy";
import esmock from "esmock";
import cacache from "cacache";
// Require Internal Dependencies
import { buildServer } from "../src/http-server/index.js";
import { CACHE_PATH } from "../src/http-server/cache.js";
// CONSTANTS
const HTTP_PORT = 17049;
const HTTP_URL = new URL(`http://localhost:${HTTP_PORT}`);
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const JSON_PATH = path.join(__dirname, "fixtures", "httpServer.json");
const INDEX_HTML = fs.readFileSync(path.join(__dirname, "..", "views", "index.html"), "utf-8");
const kConfigKey = "___config";
const kGlobalDispatcher = getGlobalDispatcher();
const kMockAgent = new MockAgent();
const kBundlephobiaPool = kMockAgent.get("https://bundlephobia.com");
const kDefaultPayloadPath = path.join(process.cwd(), "nsecure-result.json");
describe("httpServer", { concurrency: 1 }, () => {
let httpServer;
before(async() => {
setGlobalDispatcher(kMockAgent);
await i18n.extendFromSystemPath(
path.join(__dirname, "..", "i18n")
);
httpServer = buildServer(JSON_PATH, {
port: HTTP_PORT,
openLink: false,
enableWS: false
});
await once(httpServer.server, "listening");
enableDestroy(httpServer.server);
if (fs.existsSync(kDefaultPayloadPath) === false) {
// When running tests on CI, we need to create the nsecure-result.json file
const payload = fs.readFileSync(JSON_PATH, "utf-8");
fs.writeFileSync(kDefaultPayloadPath, payload);
}
}, { timeout: 5000 });
after(async() => {
httpServer.server.destroy();
kBundlephobiaPool.close();
setGlobalDispatcher(kGlobalDispatcher);
});
test("'/' should return index.html content", async() => {
const i18nLangName = await i18n.getLocalLang();
const result = await get(HTTP_URL);
assert.equal(result.statusCode, 200);
assert.equal(result.headers["content-type"], "text/html");
const templateStr = zup(INDEX_HTML)({
lang: i18n.getTokenSync("lang"),
i18nLangName,
token: (tokenName) => i18n.getTokenSync(`ui.${tokenName}`)
});
assert.equal(result.data, templateStr);
});
test("'/' should fail", async() => {
const errors = [];
const module = await esmock("../src/http-server/endpoints/root.js", {
"@polka/send-type": {
default: (_res, _status, { error }) => errors.push(error)
}
});
await module.get({}, ({
writeHead: () => {
throw new Error("fake error");
}
}));
assert.deepEqual(errors, ["fake error"]);
});
test("'/flags' should return the flags list as JSON", async() => {
const result = await get(new URL("/flags", HTTP_URL));
assert.equal(result.statusCode, 200);
assert.equal(result.headers["content-type"], "application/json;charset=utf-8");
});
test("'/flags/description/isGit' should return the isGit HTML description", async() => {
const result = await get(new URL("/flags/description/isGit", HTTP_URL));
assert.equal(result.statusCode, 200);
assert.equal(result.headers["content-type"], "text/html");
assert.equal(result.data, await flags.eagerFetchFlagFile("isGit"));
});
test("'/flags/description/foobar' should return a 404 error", async() => {
await assert.rejects(async() => {
await get(new URL("/flags/description/foobar", HTTP_URL));
}, {
name: "HttpieOnHttpError",
statusCode: 404,
statusMessage: "Not Found"
});
});
test("'/flags/description/:title' should fail", async() => {
const module = await esmock("../src/http-server/endpoints/flags.js", {
stream: {
pipeline: (_stream, _res, err) => err("fake error")
},
fs: {
createReadStream: () => "foo"
}
});
const logs = [];
console.error = (data) => logs.push(data);
await module.get({ params: { title: "hasWarnings" } }, ({ writeHead: () => true }));
assert.deepEqual(logs, ["fake error"]);
});
test("'/data' should return the fixture payload we expect", async() => {
const result = await get(new URL("/data", HTTP_URL));
assert.equal(result.statusCode, 200);
assert.equal(result.headers["content-type"], "application/json;charset=utf-8");
});
test("'/bundle/:name/:version' should return the bundle size", async() => {
kBundlephobiaPool.intercept({
path: () => true
}).reply(200, {
gzip: 1,
size: 1,
dependencySizes: {
foo: 1
}
}, { headers: { "content-type": "application/json" } });
const result = await get(new URL("/bundle/flatstr/1.0.12", HTTP_URL));
assert.equal(result.statusCode, 200);
assert.equal(result.headers["content-type"], "application/json;charset=utf-8");
checkBundleResponse(result.data);
});
test("'/bundle/:name/:version' should return an error if it fails", async() => {
kBundlephobiaPool.intercept({
path: () => true
}).reply(404);
const wrongVersion = undefined;
await assert.rejects(async() => {
await get(new URL(`/bundle/flatstr/${wrongVersion}`, HTTP_URL));
},
{
name: "HttpieOnHttpError",
statusCode: 404,
statusMessage: "Not Found"
});
});
test("'/bundle/:name' should return the bundle size of the last version", async() => {
kBundlephobiaPool.intercept({
path: () => true
}).reply(200, {
gzip: 1,
size: 1,
dependencySizes: {
foo: 1
}
}, { headers: { "content-type": "application/json" } });
const result = await get(new URL("/bundle/flatstr", HTTP_URL));
assert.equal(result.statusCode, 200);
assert.equal(result.headers["content-type"], "application/json;charset=utf-8");
checkBundleResponse(result.data);
});
test("'/bundle/:name' should return an error if it fails", async() => {
kBundlephobiaPool.intercept({
path: () => true
}).reply(404);
const wrongPackageName = "br-br-br-brah";
await assert.rejects(async() => {
await get(new URL(`/bundle/${wrongPackageName}`, HTTP_URL));
}, {
name: "HttpieOnHttpError",
statusCode: 404,
statusMessage: "Not Found"
});
});
test("GET '/config' should return the config", async() => {
const { data: actualConfig } = await get(new URL("/config", HTTP_URL));
await cacache.put(CACHE_PATH, kConfigKey, JSON.stringify({ foo: "bar", standalone: false }));
const result = await get(new URL("/config", HTTP_URL));
assert.deepEqual(result.data, { foo: "bar", standalone: false });
await fetch(new URL("/config", HTTP_URL), {
method: "PUT",
body: JSON.stringify(actualConfig),
headers: { "Content-Type": "application/json" }
});
});
test("PUT '/config' should update the config", async() => {
const { data: actualConfig } = await get(new URL("/config", HTTP_URL));
// FIXME: use @mynusift/httpie instead of fetch. Atm it throws with put().
// https://github.com/nodejs/undici/issues/583
const { status } = await fetch(new URL("/config", HTTP_URL), {
method: "PUT",
body: JSON.stringify({ fooz: "baz" }),
headers: { "Content-Type": "application/json" }
});
assert.equal(status, 204);
const inCache = await cacache.get(CACHE_PATH, kConfigKey);
assert.deepEqual(JSON.parse(inCache.data.toString()), { fooz: "baz" });
await fetch(new URL("/config", HTTP_URL), {
method: "PUT",
body: JSON.stringify(actualConfig),
headers: { "Content-Type": "application/json" }
});
});
test("GET '/i18n' should return i18n", async() => {
const result = await get(new URL("/i18n", HTTP_URL));
assert.equal(result.statusCode, 200);
const keys = Object.keys(result.data);
assert.deepEqual(keys, ["english", "french"]);
});
test("'/download/:pkgName' should return package downloads", async() => {
const result = await get(new URL("/downloads/fastify", HTTP_URL));
assert.equal(result.statusCode, 200);
assert.equal(result.data.package, "fastify");
assert.ok(result.data.downloads);
assert.ok(result.data.start);
assert.ok(result.data.end);
});
test("'/download/:pkgName' should not find package", async() => {
const wrongPackageName = "br-br-br-brah";
await assert.rejects(async() => {
await get(new URL(`/downloads/${wrongPackageName}`, HTTP_URL));
}, {
name: "HttpieOnHttpError",
statusCode: 404,
statusMessage: "Not Found"
});
});
test("'/scorecard/:org/:pkgName' should return scorecard data", async() => {
const result = await get(new URL("/scorecard/NodeSecure/cli", HTTP_URL));
assert.equal(result.statusCode, 200);
assert.equal(result.data.data.repo.name, "github.com/NodeSecure/cli");
});
test("'/scorecard/:org/:pkgName' should return scorecard data for GitLab repo", async() => {
const result = await get(new URL("/scorecard/gitlab-org/gitlab-ui?platform=gitlab.com", HTTP_URL));
assert.equal(result.statusCode, 200);
assert.equal(result.data.data.repo.name, "gitlab.com/gitlab-org/gitlab-ui");
});
test("'/scorecard/:org/:pkgName' should not find repo", async() => {
const wrongPackageName = "br-br-br-brah";
await assert.rejects(async() => {
await get(new URL(`/scorecard/NodeSecure/${wrongPackageName}`, HTTP_URL));
}, {
name: "HttpieOnHttpError",
statusCode: 404,
statusMessage: "Not Found"
});
});
test("'/report' should return a Buffer", async() => {
const result = await post(new URL("/report", HTTP_URL), { body: { title: "foo" } });
assert.equal(result.statusCode, 200);
const json = JSON.parse(result.data);
assert.strictEqual(json.data.type, "Buffer");
});
test("'/search' should return the package list", async() => {
const result = await get(new URL("/search/nodesecure", HTTP_URL));
assert.equal(result.statusCode, 200);
assert.ok(result.data);
assert.ok(Array.isArray(result.data.result));
assert.ok(result.data.count);
});
});
describe("httpServer without options", () => {
let httpServer;
let opened = false;
// We want to disable WS
process.env.NODE_ENV = "test";
before(async() => {
const module = await esmock("../src/http-server/index.js", {
open: () => (opened = true)
});
httpServer = module.buildServer(JSON_PATH);
await once(httpServer.server, "listening");
enableDestroy(httpServer.server);
});
after(async() => {
httpServer.server.destroy();
});
test("should listen on random port", () => {
assert.ok(httpServer.server.address().port > 0);
});
test("should have openLink to true", () => {
assert.equal(opened, true);
});
});
/**
* HELPERS
*/
function checkBundleResponse(payload) {
assert.ok(payload.gzip);
assert.ok(payload.size);
assert.ok(payload.dependencySizes);
}