Skip to content

Commit

Permalink
Finish writting controller tests
Browse files Browse the repository at this point in the history
  • Loading branch information
davidbarratt committed Aug 31, 2024
1 parent ad02462 commit fa2bae9
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 2 deletions.
12 changes: 11 additions & 1 deletion workers/controller/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,17 @@ async function handlePurgeRequest(
);
}

const { data } = Purge.safeParse(await request.json());
if (!data) {
return Response.json(
{
error: "Malformed request",
},
{ status: 400 },
);
}
const { tags } = data;

const client = new Cloudflare({
apiToken: token,
});
Expand All @@ -76,7 +87,6 @@ async function handlePurgeRequest(
);
}

const { tags } = Purge.parse(await request.json());
console.debug("[Cache Purge Request] Purge Tags", tags);

// If no zone is present, then all zones will be purged.
Expand Down
67 changes: 66 additions & 1 deletion workers/controller/test/purge.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { SELF, env } from "cloudflare:test";
import { it, expect, vi } from "vitest";
import { it, expect, vi, afterEach } from "vitest";
import type Cloudflare from "cloudflare";

const verify = vi.fn<
Expand All @@ -17,6 +17,10 @@ vi.mock("cloudflare", () => ({
})),
}));

afterEach(() => {
vi.clearAllMocks();
});

it("adds cache tags to the purge queue", async () => {
verify.mockResolvedValueOnce({ status: "active", id: "foo" });

Expand Down Expand Up @@ -85,3 +89,64 @@ it("adds cache tags to the purge queue with no zone", async () => {
},
]);
});

it("returns a 401 when the wrong API Token is provided", async () => {
const response = await SELF.fetch(
"https://cache-tag.example.workers.dev/purge",
{
method: "POST",
body: JSON.stringify({
tags: ["test"],
}),
headers: {
Authorization: `Bearer wrong`,
"CF-Worker": "example.com",
},
},
);

expect(response.status).toBe(401);

expect(verify).not.toBeCalled();
});

it("returns a 401 when the wrong API Token is expired", async () => {
verify.mockResolvedValueOnce({ status: "expired", id: "foo" });

const response = await SELF.fetch(
"https://cache-tag.example.workers.dev/purge",
{
method: "POST",
body: JSON.stringify({
tags: ["test"],
}),
headers: {
Authorization: `Bearer ${env.API_TOKEN}`,
},
},
);

expect(response.status).toBe(401);

expect(verify).toBeCalled();
});

it("returns a 400 when request is malformed", async () => {
const response = await SELF.fetch(
"https://cache-tag.example.workers.dev/purge",
{
method: "POST",
body: JSON.stringify({
url: "https://example.com",
}),
headers: {
Authorization: `Bearer ${env.API_TOKEN}`,
"CF-Worker": "example.com",
},
},
);

expect(response.status).toBe(400);

expect(verify).not.toBeCalled();
});

0 comments on commit fa2bae9

Please sign in to comment.