Skip to content
refs
History
47 lines · 2.5 KBRaw
1import assert from "node:assert/strict";
2import { execFile } from "node:child_process";
3import { createHash } from "node:crypto";
4import fs from "node:fs";
5import http from "node:http";
6import type net from "node:net";
7import os from "node:os";
8import path from "node:path";
9import { test } from "node:test";
10
11const CLI = new URL("../refs.mjs", import.meta.url).pathname;
12const INSTALLED = "console.log('installed');\n";
13
14async function attemptUpdate(t: test.TestContext, body: string, checksum: string | null) {
15 const home = fs.mkdtempSync(path.join(os.tmpdir(), "refs-update-"));
16 const server = http.createServer((_, response) => response.writeHead(200, checksum ? { "x-refs-sha256": checksum } : {}).end(body));
17 await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
18 t.after(() => (server.close(), fs.rmSync(home, { recursive: true, force: true })));
19 const origin = `http://127.0.0.1:${(server.address() as net.AddressInfo).port}`;
20 fs.mkdirSync(path.join(home, "bin"));
21 fs.writeFileSync(path.join(home, "bin", "refs.mjs"), INSTALLED);
22 fs.writeFileSync(path.join(home, "credentials.json"), JSON.stringify({ origin, accessToken: "oauth", expiresAt: Date.now() / 1000 + 3600 }));
23 const result = await new Promise<{ status: number; stderr: string }>((resolve) =>
24 execFile(process.execPath, [CLI, "update"], { env: { ...process.env, REFS_HOME: home, PATH: "/nonexistent" } }, (error, _stdout, stderr) => resolve({ status: error ? Number(error.code) : 0, stderr })),
25 );
26 return { result, installed: fs.readFileSync(path.join(home, "bin", "refs.mjs"), "utf8"), leftovers: fs.readdirSync(path.join(home, "bin")) };
27}
28
29test("refs update keeps the installed CLI when the download is cut off", async (t) => {
30 const { result, installed, leftovers } = await attemptUpdate(t, "function cut(", null);
31 assert.equal(result.status, 1);
32 assert.equal(installed, INSTALLED);
33 assert.deepEqual(leftovers, ["refs.mjs"]);
34});
35
36test("refs update keeps the installed CLI when the checksum does not match", async (t) => {
37 const { result, installed } = await attemptUpdate(t, "console.log('new');\n", "0".repeat(64));
38 assert.equal(result.status, 1);
39 assert.equal(installed, INSTALLED);
40});
41
42test("refs update replaces the CLI when the download is whole and matches its checksum", async (t) => {
43 const fresh = "console.log('new');\n";
44 const { result, installed } = await attemptUpdate(t, fresh, createHash("sha256").update(fresh).digest("hex"));
45 assert.equal(result.status, 0, result.stderr);
46 assert.equal(installed, fresh);
47});