Skip to content

Commit e50285d

Browse files
committed
fix: keep analyze tests out of the home directory and check the map fetch
1 parent 7d8a519 commit e50285d

3 files changed

Lines changed: 29 additions & 36 deletions

File tree

‎src/commands/analyze.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,12 +64,20 @@ export async function runAnalyze(
6464
return { response: job, exitCode: 1 };
6565
}
6666
// The map is public JSON on the CDN: fetch it without the API key.
67-
const map = (await (await fetch(job.url!)).json()) as MusicMap;
67+
if (!job.url) return fail(job, "analysis finished without a map URL");
68+
const res = await fetch(job.url);
69+
if (!res.ok) return fail(job, `could not fetch the analysis map (${res.status}) from ${job.url}`);
70+
const map = (await res.json()) as MusicMap;
6871
emit(format, map, `done ${formatSummary(map)}`);
6972
if (format !== "json") console.error("Print the full map with --output json.");
7073
return { response: job, exitCode: 0 };
7174
}
7275

76+
function fail(job: Analysis, message: string): CommandResult {
77+
console.error(message);
78+
return { response: job, exitCode: 1 };
79+
}
80+
7381
export function formatSummary(m: MusicMap): string {
7482
const counts = `${m.drops?.length ?? 0} drops, ${m.sections?.length ?? 0} sections`;
7583
if (!m.steady) {

‎src/http/client.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,7 @@ export class ApiError extends Error {
1717
}
1818

1919
export interface ClientOptions {
20-
// Absent for endpoints that take no key.
21-
apiKey?: string;
20+
apiKey: string;
2221
env: ResolvedEnv;
2322
}
2423

@@ -31,7 +30,7 @@ export function createClient(options: ClientOptions) {
3130
const response = await fetch(`${baseUrl}${path}`, {
3231
method,
3332
headers: {
34-
...(options.apiKey !== undefined ? { "x-api-key": options.apiKey } : {}),
33+
"x-api-key": options.apiKey,
3534
"x-shotstack-origin": "cli",
3635
"x-shotstack-environment": options.env.name,
3736
"user-agent": userAgent,

‎tests/analyze.test.ts‎

Lines changed: 18 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { describe, test, expect, mock, spyOn } from "bun:test";
2-
import { analyzeCommand, formatSummary, runAnalyze, type Analysis } from "../src/commands/analyze.ts";
3-
import { createClient, type Client } from "../src/http/client.ts";
2+
import { formatSummary, runAnalyze, type Analysis } from "../src/commands/analyze.ts";
3+
import { type Client } from "../src/http/client.ts";
44

55
const steady = {
66
bpm: 120.01,
@@ -25,7 +25,7 @@ async function capture(run: () => Promise<unknown>) {
2525
const err = spyOn(console, "error").mockImplementation(() => {});
2626
try {
2727
const result = await run();
28-
return { result, lines: log.mock.calls.map((c) => String(c[0])) };
28+
return { result, lines: log.mock.calls.map((c) => String(c[0])), errors: err.mock.calls.map((c) => String(c[0])) };
2929
} finally {
3030
log.mockRestore();
3131
err.mockRestore();
@@ -81,28 +81,26 @@ describe("runAnalyze", () => {
8181
});
8282
});
8383

84-
describe("analyze command", () => {
85-
test("sends the account's API key to /generate but not to the map URL", async () => {
86-
const saved = process.env.SHOTSTACK_API_KEY;
87-
process.env.SHOTSTACK_API_KEY = "test-key";
88-
const log = spyOn(console, "log").mockImplementation(() => {});
89-
const fetchMock = spyOn(globalThis, "fetch").mockImplementation(async (input) =>
90-
String(input).endsWith("/generate")
91-
? new Response(JSON.stringify({ id: "a", status: "done", url: MAP_URL }))
92-
: new Response(JSON.stringify(steady)),
93-
);
84+
describe("map fetch", () => {
85+
test("a non-2xx map response exits 1 with a clear message", async () => {
86+
const { client } = fakeClient({ id: "a", status: "done", url: MAP_URL });
87+
const fetchMock = spyOn(globalThis, "fetch").mockResolvedValue(new Response("nope", { status: 403 }));
9488
try {
95-
await analyzeCommand.parseAsync(["node", "analyze", "https://example.com/a.mp3", "--output", "json"]);
96-
const [generate, map] = fetchMock.mock.calls;
97-
expect((generate![1]!.headers as Record<string, string>)["x-api-key"]).toBe("test-key");
98-
expect(map).toEqual([MAP_URL]);
89+
const { result, lines, errors } = await capture(() => runAnalyze(client, "https://example.com/a.mp3", "json", 0));
90+
expect(result).toMatchObject({ exitCode: 1 });
91+
expect(lines).toEqual([]);
92+
expect(errors).toEqual([`could not fetch the analysis map (403) from ${MAP_URL}`]);
9993
} finally {
10094
fetchMock.mockRestore();
101-
log.mockRestore();
102-
if (saved === undefined) delete process.env.SHOTSTACK_API_KEY;
103-
else process.env.SHOTSTACK_API_KEY = saved;
10495
}
10596
});
97+
98+
test("a done job with no url exits 1 with a clear message", async () => {
99+
const { client } = fakeClient({ id: "a", status: "done" });
100+
const { result, errors } = await capture(() => runAnalyze(client, "https://example.com/a.mp3", "json", 0));
101+
expect(result).toMatchObject({ exitCode: 1 });
102+
expect(errors).toEqual(["analysis finished without a map URL"]);
103+
});
106104
});
107105

108106
describe("formatSummary", () => {
@@ -115,15 +113,3 @@ describe("formatSummary", () => {
115113
expect(formatSummary(varies)).toBe("tempo varies (about 120 BPM): 822 beats, 227 downbeats, 2 drops, 9 sections");
116114
});
117115
});
118-
119-
describe("createClient", () => {
120-
test("sends no API key when it has none", async () => {
121-
const fetchMock = spyOn(globalThis, "fetch").mockResolvedValue(new Response("{}"));
122-
try {
123-
await createClient({ env: { name: "v1", baseUrl: "https://api.example.com" } }).get("/x");
124-
expect(fetchMock.mock.calls[0]![1]!.headers).not.toHaveProperty("x-api-key");
125-
} finally {
126-
fetchMock.mockRestore();
127-
}
128-
});
129-
});

0 commit comments

Comments
 (0)