|
| 1 | +import { expect, test } from "bun:test"; |
| 2 | + |
| 3 | +import { clearYurucommuApiTransport } from "../transport.ts"; |
| 4 | +import { fetchActor } from "./actors.ts"; |
| 5 | +import { InvalidApiResponseError } from "./response.ts"; |
| 6 | + |
| 7 | +function actor(outgoing_follow_status?: unknown) { |
| 8 | + return { |
| 9 | + ap_id: "https://example.com/ap/users/alice", |
| 10 | + preferred_username: "alice", |
| 11 | + ...(outgoing_follow_status === undefined ? {} : { outgoing_follow_status }), |
| 12 | + }; |
| 13 | +} |
| 14 | + |
| 15 | +function outgoingStatus(value: object): unknown { |
| 16 | + return (value as Record<string, unknown>).outgoing_follow_status; |
| 17 | +} |
| 18 | + |
| 19 | +async function withMockFetch<T>( |
| 20 | + body: unknown, |
| 21 | + fn: () => Promise<T>, |
| 22 | +): Promise<T> { |
| 23 | + const originalFetch = globalThis.fetch; |
| 24 | + clearYurucommuApiTransport(); |
| 25 | + globalThis.fetch = Object.assign( |
| 26 | + async () => |
| 27 | + new Response(JSON.stringify({ actor: body }), { |
| 28 | + status: 200, |
| 29 | + headers: { "Content-Type": "application/json" }, |
| 30 | + }), |
| 31 | + { preconnect: originalFetch.preconnect }, |
| 32 | + ); |
| 33 | + |
| 34 | + try { |
| 35 | + return await fn(); |
| 36 | + } finally { |
| 37 | + globalThis.fetch = originalFetch; |
| 38 | + clearYurucommuApiTransport(); |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +test("fetchActor accepts legacy omission and preserves valid outgoing status", async () => { |
| 43 | + const legacy = await withMockFetch(actor(), () => fetchActor("alice")); |
| 44 | + expect(legacy).not.toHaveProperty("outgoing_follow_status"); |
| 45 | + |
| 46 | + for (const status of ["none", "pending", "accepted"] as const) { |
| 47 | + const result = await withMockFetch(actor(status), () => |
| 48 | + fetchActor("alice"), |
| 49 | + ); |
| 50 | + expect(outgoingStatus(result)).toBe(status); |
| 51 | + expect(result.username).toBe("alice@example.com"); |
| 52 | + } |
| 53 | +}); |
| 54 | + |
| 55 | +test("fetchActor rejects malformed outgoing status values as invalid API responses", async () => { |
| 56 | + for (const status of [null, 1, false, "rejected", "unknown"]) { |
| 57 | + await expect( |
| 58 | + withMockFetch(actor(status), () => fetchActor("alice")), |
| 59 | + ).rejects.toBeInstanceOf(InvalidApiResponseError); |
| 60 | + } |
| 61 | +}); |
0 commit comments