-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathhttpServer.test.ts
More file actions
390 lines (323 loc) · 11.8 KB
/
httpServer.test.ts
File metadata and controls
390 lines (323 loc) · 11.8 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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
// 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 stream from "node:stream";
// Import Third-party Dependencies
import { get, post, MockAgent, getGlobalDispatcher, setGlobalDispatcher } from "@myunisoft/httpie";
import { CACHE_PATH } from "@nodesecure/cache";
import * as i18n from "@nodesecure/i18n";
import * as flags from "@nodesecure/flags";
import enableDestroy from "server-destroy";
import cacache from "cacache";
import { type Polka } from "polka";
// Import Internal Dependencies
import { buildServer } from "../index.js";
import * as rootEndpoint from "../src/endpoints/root.js";
import * as flagsEndpoint from "../src/endpoints/flags.js";
// CONSTANTS
const kHttpPort = 17049;
const kHttpURL = new URL(`http://localhost:${kHttpPort}`);
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const JSON_PATH = path.join(__dirname, "fixtures", "httpServer.json");
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");
const kProjectRootDir = path.join(import.meta.dirname, "..", "..", "..");
const kComponentsDir = path.join(kProjectRootDir, "public", "components");
describe("httpServer", { concurrency: 1 }, () => {
let httpServer: Polka;
before(async() => {
setGlobalDispatcher(kMockAgent);
await i18n.extendFromSystemPath(
path.join(__dirname, "..", "..", "..", "i18n")
);
httpServer = buildServer(JSON_PATH, {
projectRootDir: kProjectRootDir,
componentsDir: kComponentsDir,
i18n: {
english: {
ui: {}
},
french: {
ui: {}
}
}
});
httpServer.listen(kHttpPort);
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 result = await get(kHttpURL);
assert.equal(result.statusCode, 200);
assert.ok(result.headers["content-type"]!.startsWith("text/html"));
});
test("'/' should fail", async(ctx) => {
class Response {
body: string;
headers: Record<string, string>;
statusCode: number;
constructor() {
this.body = "";
this.headers = {};
this.statusCode = 200;
}
end(str: string) {
this.body = str;
}
writeHead(int: number) {
this.statusCode = int;
}
getHeader(key: string) {
return this.headers[key];
}
}
const fakeError = "fake error";
function toThrow() {
throw new Error(fakeError);
}
ctx.mock.method(Response.prototype, "writeHead", toThrow, { times: 1 });
const response: any = new Response();
await rootEndpoint.get({} as any, response);
assert.strictEqual(response.body, JSON.stringify({ error: fakeError }));
assert.strictEqual(response.statusCode, 500);
});
test("'/flags' should return the flags list as JSON", async() => {
const result = await get(new URL("/flags", kHttpURL));
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", kHttpURL));
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", kHttpURL));
}, {
name: "HttpieOnHttpError",
statusCode: 404,
statusMessage: "Not Found"
});
});
test("'/flags/description/:title' should fail", async(ctx) => {
ctx.mock.method(stream, "pipeline", (_stream, _res, err) => err("fake error"));
const logs: string[] = [];
console.error = (data: string) => logs.push(data);
await flagsEndpoint.get({ params: { title: "hasWarnings" } } as any, ({ writeHead: () => true }) as any);
assert.deepEqual(logs, ["fake error"]);
});
test("'/data' should return the fixture payload we expect", async() => {
const result = await get(new URL("/data", kHttpURL));
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", kHttpURL));
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}`, kHttpURL));
},
{
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", kHttpURL));
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}`, kHttpURL));
}, {
name: "HttpieOnHttpError",
statusCode: 404,
statusMessage: "Not Found"
});
});
test("GET '/config' should return the config", async() => {
const { data: actualConfig } = await get(new URL("/config", kHttpURL));
const expectedConfig = {
defaultPackageMenu: "foo",
ignore: {
flags: ["foo"],
warnings: ["bar"]
},
lang: "english",
theme: "galaxy",
disableExternalRequests: true
};
await cacache.put(CACHE_PATH, kConfigKey, JSON.stringify(expectedConfig));
const result = await get(new URL("/config", kHttpURL));
assert.deepEqual(result.data, expectedConfig);
await fetch(new URL("/config", kHttpURL), {
method: "PUT",
body: JSON.stringify(actualConfig),
headers: { "Content-Type": "application/json" }
});
});
test("PUT '/config' should update the config", async() => {
const lang = await i18n.getLocalLang();
const { data: actualConfig } = await get(new URL("/config", kHttpURL));
// 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", kHttpURL), {
method: "PUT",
body: JSON.stringify({ fooz: "baz", lang }),
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", lang });
await fetch(new URL("/config", kHttpURL), {
method: "PUT",
body: JSON.stringify(actualConfig),
headers: { "Content-Type": "application/json" }
});
});
test("GET '/i18n' should return i18n", async() => {
const result = await get<any>(new URL("/i18n", kHttpURL));
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<any>(new URL("/downloads/fastify", kHttpURL));
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}`, kHttpURL));
}, {
name: "HttpieOnHttpError",
statusCode: 404,
statusMessage: "Not Found"
});
});
test("'/scorecard/:org/:pkgName' should return scorecard data", async() => {
const result = await get<any>(new URL("/scorecard/NodeSecure/cli", kHttpURL));
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<any>(new URL("/scorecard/gitlab-org/gitlab-ui?platform=gitlab.com", kHttpURL));
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}`, kHttpURL));
}, {
name: "HttpieOnHttpError",
statusCode: 404,
statusMessage: "Not Found"
});
});
test("'/report' should return a Buffer", async() => {
const result = await post<any>(new URL("/report", kHttpURL), { 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<any>(new URL("/search/nodesecure", kHttpURL));
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;
// We want to disable WS
process.env.NODE_ENV = "test";
before(async() => {
httpServer = buildServer(JSON_PATH, {
projectRootDir: kProjectRootDir,
componentsDir: kComponentsDir,
i18n: {
english: {
ui: {}
},
french: {
ui: {}
}
}
});
httpServer.listen();
await once(httpServer.server, "listening");
enableDestroy(httpServer.server);
});
after(async() => {
httpServer.server.destroy();
});
test("should listen on random port", async() => {
assert.ok(httpServer.server.address().port > 0);
});
});
/**
* HELPERS
*/
function checkBundleResponse(payload) {
assert.ok(payload.gzip);
assert.ok(payload.size);
assert.ok(payload.dependencySizes);
}