Skip to content

Commit 49aca43

Browse files
authored
Refactor test coverage (#21)
* Remove `central-alerts` CRUD endpoints and update support labels Removed all CRUD endpoints and related logic from the central-alerts service, including database methods, API routes, and tests. Updated the releases API to use new support labels: 'latest', 'outdated', and 'insecure' instead of 'supported' and 'unsupported'. Adjusted related documentation, interfaces, and tests to reflect these changes. Improved `CloudflareKVAdapter` error handling and binding name tracking. Also fixed update token key casing in versions service and tests. * Add Vary header when no releases are found Sets the 'Vary' header to '*' in the API response when the releases object is empty. This helps ensure proper caching behavior when no release data is available. * Add Vary header when no releases are found Sets the 'Vary' header to '*' in the API response when the releases object is empty. This helps ensure proper caching behavior when no release data is available. * Add unit and integration tests for v1 versions API error handling and middleware.
1 parent fb0bca5 commit 49aca43

4 files changed

Lines changed: 1148 additions & 6 deletions

File tree

‎src/versions/v1/index.ts‎

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -47,17 +47,26 @@ async function getUpdateToken(cache: ICache): Promise<string> {
4747

4848
versionsV1.get(
4949
"/",
50-
cache({ cacheName: "versions-api-v1", cacheControl: "max-age: 86400" }),
50+
cache({
51+
cacheName: "versions-api-v1",
52+
cacheControl: "max-age: 86400"
53+
}),
5154
etag(),
5255
prettyJSON(),
5356
async (c) => {
5457
const platform = getPlatform(c);
58+
const releases = await getReleases(
59+
platform.getCache("CACHE_KV"),
60+
platform.getEnv("GITHUB_TOKEN") || "",
61+
false
62+
);
63+
64+
if (Object.keys(releases).length === 0) {
65+
c.header("Vary", "*");
66+
}
67+
5568
return c.json({
56-
result: await getReleases(
57-
platform.getCache("CACHE_KV"),
58-
platform.getEnv("GITHUB_TOKEN") || "",
59-
false
60-
),
69+
result: releases,
6170
error_code: 0,
6271
message: null
6372
});

‎test/integration/versions.test.ts‎

Lines changed: 324 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,324 @@
1+
import { describe, it, expect, beforeEach, vi } from "vitest";
2+
import {
3+
env,
4+
createExecutionContext,
5+
waitOnExecutionContext
6+
} from "cloudflare:test";
7+
import app from "../../src";
8+
import {
9+
mockGitHubReleases,
10+
mockComposerJson
11+
} from "../fixtures/github-releases";
12+
import { setupGitHubApiMock } from "../utils/mock-helpers";
13+
import {
14+
MockGitHubRequest,
15+
VersionsResponse,
16+
ApiResponse
17+
} from "../utils/test-types";
18+
19+
vi.mock("@octokit/request", () => ({
20+
request: vi.fn()
21+
}));
22+
23+
import { request as ghRequest } from "@octokit/request";
24+
25+
describe("Versions API v1 - Integration Tests", () => {
26+
beforeEach(async () => {
27+
await env.CACHE_KV.delete("gh-fossbilling-releases");
28+
await env.AUTH_KV.put("UPDATE_TOKEN", "test-update-token-12345");
29+
30+
vi.clearAllMocks();
31+
setupGitHubApiMock(
32+
vi.mocked(ghRequest) as MockGitHubRequest,
33+
mockGitHubReleases,
34+
mockComposerJson
35+
);
36+
});
37+
38+
describe("Full Request/Response Cycle", () => {
39+
it("should handle complete flow from request to cached response", async () => {
40+
// First request - fetch from GitHub
41+
const ctx1 = createExecutionContext();
42+
const response1 = await app.request("/versions/v1", {}, env, ctx1);
43+
await waitOnExecutionContext(ctx1);
44+
45+
expect(response1.status).toBe(200);
46+
const data1: VersionsResponse = await response1.json();
47+
expect(Object.keys(data1.result).length).toBeGreaterThan(0);
48+
49+
// Verify data was cached
50+
const cached = await env.CACHE_KV.get("gh-fossbilling-releases");
51+
expect(cached).toBeTruthy();
52+
53+
// Second request - should use cache
54+
const ctx2 = createExecutionContext();
55+
const response2 = await app.request("/versions/v1", {}, env, ctx2);
56+
await waitOnExecutionContext(ctx2);
57+
58+
expect(response2.status).toBe(200);
59+
const data2: VersionsResponse = await response2.json();
60+
expect(data1).toEqual(data2);
61+
});
62+
63+
it("should handle update flow with authentication", async () => {
64+
// Initial state - no cache
65+
let cached = await env.CACHE_KV.get("gh-fossbilling-releases");
66+
expect(cached).toBeFalsy();
67+
68+
// Call update endpoint
69+
const ctx1 = createExecutionContext();
70+
const response1 = await app.request(
71+
"/versions/v1/update",
72+
{
73+
headers: {
74+
Authorization: "Bearer test-update-token-12345"
75+
}
76+
},
77+
env,
78+
ctx1
79+
);
80+
await waitOnExecutionContext(ctx1);
81+
82+
expect(response1.status).toBe(200);
83+
const data1 = (await response1.json()) as ApiResponse<string>;
84+
expect(data1.result).toContain("updated successfully");
85+
86+
// Verify cache was populated
87+
cached = await env.CACHE_KV.get("gh-fossbilling-releases");
88+
expect(cached).toBeTruthy();
89+
90+
// Subsequent request should use cache
91+
const ctx2 = createExecutionContext();
92+
const response2 = await app.request("/versions/v1", {}, env, ctx2);
93+
await waitOnExecutionContext(ctx2);
94+
95+
expect(response2.status).toBe(200);
96+
});
97+
98+
it("should return correct data across all endpoints", async () => {
99+
// Get all versions
100+
const ctx1 = createExecutionContext();
101+
const response1 = await app.request("/versions/v1", {}, env, ctx1);
102+
await waitOnExecutionContext(ctx1);
103+
const allVersions: VersionsResponse = await response1.json();
104+
105+
// Get latest version
106+
const ctx2 = createExecutionContext();
107+
const response2 = await app.request("/versions/v1/latest", {}, env, ctx2);
108+
await waitOnExecutionContext(ctx2);
109+
const latest = (await response2.json()) as VersionsResponse;
110+
111+
// Get specific version
112+
const ctx3 = createExecutionContext();
113+
const response3 = await app.request("/versions/v1/0.6.0", {}, env, ctx3);
114+
await waitOnExecutionContext(ctx3);
115+
const specific = (await response3.json()) as VersionsResponse;
116+
117+
// Verify consistency
118+
expect(latest.result).toEqual(allVersions.result["0.6.0"]);
119+
expect(specific.result).toEqual(allVersions.result["0.6.0"]);
120+
});
121+
});
122+
123+
describe("Cache Behavior", () => {
124+
it("should use cache across multiple requests", async () => {
125+
const requests = 5;
126+
const responses = [];
127+
128+
for (let i = 0; i < requests; i++) {
129+
const ctx = createExecutionContext();
130+
const response = await app.request("/versions/v1", {}, env, ctx);
131+
await waitOnExecutionContext(ctx);
132+
responses.push(await response.json());
133+
}
134+
135+
// All responses should be identical
136+
for (let i = 1; i < requests; i++) {
137+
expect(responses[i]).toEqual(responses[0]);
138+
}
139+
140+
// GitHub API should only be called once (first request)
141+
expect(vi.mocked(ghRequest)).toHaveBeenCalled();
142+
});
143+
144+
it("should refresh cache when update endpoint is called", async () => {
145+
// First request
146+
const ctx1 = createExecutionContext();
147+
await app.request("/versions/v1", {}, env, ctx1);
148+
await waitOnExecutionContext(ctx1);
149+
150+
const cachedBefore = await env.CACHE_KV.get("gh-fossbilling-releases");
151+
152+
// Modify mock to return different data
153+
(vi.mocked(ghRequest) as MockGitHubRequest).mockImplementation(
154+
async (route: string) => {
155+
if (route === "GET /repos/{owner}/{repo}/releases") {
156+
return {
157+
data: [
158+
{
159+
id: 9999,
160+
tag_name: "9.9.9",
161+
name: "9.9.9",
162+
published_at: "2024-01-01T00:00:00Z",
163+
prerelease: false,
164+
body: "New release",
165+
assets: [
166+
{
167+
name: "FOSSBilling.zip",
168+
browser_download_url: "https://example.com/new.zip",
169+
size: 2000000
170+
}
171+
]
172+
}
173+
]
174+
};
175+
}
176+
if (route === "GET /repos/{owner}/{repo}/contents/{path}{?ref}") {
177+
const content = btoa(JSON.stringify(mockComposerJson));
178+
return { data: { content } };
179+
}
180+
throw new Error("Unexpected route");
181+
}
182+
);
183+
184+
// Call update endpoint
185+
const ctx2 = createExecutionContext();
186+
await app.request(
187+
"/versions/v1/update",
188+
{
189+
headers: {
190+
Authorization: "Bearer test-update-token-12345"
191+
}
192+
},
193+
env,
194+
ctx2
195+
);
196+
await waitOnExecutionContext(ctx2);
197+
198+
const cachedAfter = await env.CACHE_KV.get("gh-fossbilling-releases");
199+
200+
// Cache should be different
201+
expect(cachedAfter).not.toBe(cachedBefore);
202+
expect(cachedAfter).toContain("9.9.9");
203+
});
204+
205+
it("should handle concurrent requests gracefully", async () => {
206+
await env.CACHE_KV.delete("gh-fossbilling-releases");
207+
208+
// Make 10 concurrent requests
209+
const promises = [];
210+
for (let i = 0; i < 10; i++) {
211+
const ctx = createExecutionContext();
212+
const promise = (async () => {
213+
const response = await app.request("/versions/v1", {}, env, ctx);
214+
await waitOnExecutionContext(ctx);
215+
return response.json();
216+
})();
217+
promises.push(promise);
218+
}
219+
220+
const results = await Promise.all(promises);
221+
222+
// All should succeed
223+
results.forEach((result) => {
224+
const r = result as ApiResponse;
225+
expect(r.error_code).toBe(0);
226+
expect(
227+
Object.keys(r.result as Record<string, unknown>).length
228+
).toBeGreaterThan(0);
229+
});
230+
});
231+
});
232+
233+
describe("Error Recovery", () => {
234+
it("should recover from GitHub API failure using cache", async () => {
235+
// First request to populate cache
236+
const ctx1 = createExecutionContext();
237+
await app.request("/versions/v1", {}, env, ctx1);
238+
await waitOnExecutionContext(ctx1);
239+
240+
// Mock GitHub API to fail
241+
(vi.mocked(ghRequest) as MockGitHubRequest).mockRejectedValueOnce(
242+
new Error("GitHub API Error")
243+
);
244+
245+
// Second request should use cache
246+
const ctx2 = createExecutionContext();
247+
const response2 = await app.request("/versions/v1", {}, env, ctx2);
248+
await waitOnExecutionContext(ctx2);
249+
250+
expect(response2.status).toBe(200);
251+
const data: VersionsResponse = await response2.json();
252+
expect(Object.keys(data.result).length).toBeGreaterThan(0);
253+
});
254+
255+
it("should work after authentication failure then success", async () => {
256+
// First attempt - wrong token
257+
const ctx1 = createExecutionContext();
258+
const response1 = await app.request(
259+
"/versions/v1/update",
260+
{
261+
headers: {
262+
Authorization: "Bearer wrong-token"
263+
}
264+
},
265+
env,
266+
ctx1
267+
);
268+
await waitOnExecutionContext(ctx1);
269+
270+
expect(response1.status).toBe(401);
271+
272+
// Second attempt - correct token
273+
const ctx2 = createExecutionContext();
274+
const response2 = await app.request(
275+
"/versions/v1/update",
276+
{
277+
headers: {
278+
Authorization: "Bearer test-update-token-12345"
279+
}
280+
},
281+
env,
282+
ctx2
283+
);
284+
await waitOnExecutionContext(ctx2);
285+
286+
expect(response2.status).toBe(200);
287+
});
288+
});
289+
290+
describe("Service Integration", () => {
291+
it("should work when called through main app router", async () => {
292+
const ctx = createExecutionContext();
293+
const response = await app.request("/versions/v1", {}, env, ctx);
294+
await waitOnExecutionContext(ctx);
295+
296+
expect(response.status).toBe(200);
297+
expect(response.headers.get("Access-Control-Allow-Origin")).toBe("*");
298+
299+
const data: VersionsResponse = await response.json();
300+
expect(data).toHaveProperty("result");
301+
expect(data).toHaveProperty("error_code", 0);
302+
expect(data).toHaveProperty("message", null);
303+
});
304+
305+
it("should maintain consistent API response format", async () => {
306+
const endpoints = [
307+
"/versions/v1",
308+
"/versions/v1/latest",
309+
"/versions/v1/0.6.0"
310+
];
311+
312+
for (const endpoint of endpoints) {
313+
const ctx = createExecutionContext();
314+
const response = await app.request(endpoint, {}, env, ctx);
315+
await waitOnExecutionContext(ctx);
316+
317+
const data = await response.json();
318+
expect(data).toHaveProperty("result");
319+
expect(data).toHaveProperty("error_code");
320+
expect(data).toHaveProperty("message");
321+
}
322+
});
323+
});
324+
});

0 commit comments

Comments
 (0)