Files
persionalBrand/deploy/static-server.test.mjs

60 lines
2.7 KiB
JavaScript

import assert from "node:assert/strict";
import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import test from "node:test";
import { createStaticServer } from "./static-server.mjs";
test("static server serves the admin, template preview, and root public assets", async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), "personal-brand-static-"));
const adminRoot = path.join(directory, "dist");
await mkdir(path.join(adminRoot, "assets", "owner"), { recursive: true });
await mkdir(path.join(adminRoot, "template-preview"), { recursive: true });
await writeFile(path.join(adminRoot, "index.html"), "admin entry");
await writeFile(path.join(adminRoot, "template-preview", "index.html"), "preview entry");
await writeFile(path.join(adminRoot, "assets", "app-12345678.js"), "console.log('ok')");
await writeFile(path.join(adminRoot, "assets", "owner", "portrait.jpg"), "portrait");
const server = createStaticServer({ adminRoot });
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
const baseUrl = "http://127.0.0.1:" + address.port;
try {
const admin = await fetch(baseUrl + "/admin/");
assert.equal(admin.status, 200);
assert.match(admin.headers.get("content-type"), /text\/html/);
assert.equal(await admin.text(), "admin entry");
const adminRoute = await fetch(baseUrl + "/admin/brand", {
headers: { accept: "text/html" },
});
assert.equal(await adminRoute.text(), "admin entry");
const preview = await fetch(baseUrl + "/template-preview/");
assert.equal(await preview.text(), "preview entry");
const script = await fetch(baseUrl + "/admin/assets/app-12345678.js");
assert.match(script.headers.get("content-type"), /javascript/);
assert.match(script.headers.get("cache-control"), /immutable/);
const image = await fetch(baseUrl + "/assets/owner/portrait.jpg");
assert.equal(image.headers.get("content-type"), "image/jpeg");
assert.equal(await image.text(), "portrait");
const missingAsset = await fetch(baseUrl + "/admin/assets/missing.js");
assert.equal(missingAsset.status, 404);
assert.match(missingAsset.headers.get("content-type"), /text\/plain/);
const traversal = await fetch(baseUrl + "/admin/%2e%2e/%2e%2e/etc/passwd");
assert.equal(traversal.status, 404);
const unsupportedMethod = await fetch(baseUrl + "/admin/", { method: "POST" });
assert.equal(unsupportedMethod.status, 405);
} finally {
await new Promise((resolve, reject) =>
server.close((error) => (error ? reject(error) : resolve())),
);
await rm(directory, { recursive: true, force: true });
}
});