/ opencodehub / tests / integration / workflow-states-route.test.ts
swadhinbiswas Harden workflow state endpoints with auth and safety checks · 2/19/2026
7a069c9
125 lines · 3.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
import { beforeEach, describe, expect, it, vi } from "vitest";

const { canReadRepoMock, canAdminRepoMock, fakeSchema } = vi.hoisted(() => ({
  canReadRepoMock: vi.fn(async () => true),
  canAdminRepoMock: vi.fn(async () => true),
  fakeSchema: {
    users: { username: {} },
    repositories: { name: {}, ownerId: {}, id: {} },
    prStateDefinitions: { repositoryId: {}, name: {}, id: {} },
    pullRequests: { stateId: {}, id: {} },
  } as any,
}));

let mockDb: any;

vi.mock("@/db", () => ({
  getDatabase: () => mockDb,
  schema: fakeSchema,
}));

vi.mock("@/lib/permissions", () => ({
  canReadRepo: canReadRepoMock,
  canAdminRepo: canAdminRepoMock,
}));

import { GET as getStates, POST as createState } from "@/pages/api/repos/[owner]/[repo]/workflow/states";
import { DELETE as deleteState } from "@/pages/api/repos/[owner]/[repo]/workflow/states/[id]";

function makeDb() {
  const owner = { id: "owner-1" };
  const repository = { id: "repo-1", ownerId: "owner-1", name: "demo" };
  const existingState = { id: "state-1", repositoryId: "repo-1", name: "in_review" };

  const insertCalls: unknown[] = [];
  const deleteCalls: unknown[] = [];

  return {
    query: {
      users: {
        findFirst: vi.fn(async () => owner),
      },
      repositories: {
        findFirst: vi.fn(async () => repository),
      },
      prStateDefinitions: {
        findMany: vi.fn(async () => [existingState]),
        findFirst: vi.fn(async (args?: any) => {
          if (args?.where) {
            // Existence checks in route; default to found.
            return existingState;
          }
          return existingState;
        }),
      },
      pullRequests: {
        findFirst: vi.fn(async () => null),
      },
    },
    $count: vi.fn(async () => 1),
    insert: vi.fn(() => ({
      values: vi.fn(async (value: unknown) => {
        insertCalls.push(value);
        return [{ id: "new-state", name: "qa", repositoryId: "repo-1" }];
      }),
    })),
    delete: vi.fn(() => ({
      where: vi.fn(async (value: unknown) => {
        deleteCalls.push(value);
      }),
    })),
    __state: { insertCalls, deleteCalls },
  };
}

async function readJson(response: Response): Promise<any> {
  return response.json();
}

describe("workflow states route", () => {
  beforeEach(() => {
    mockDb = makeDb();
    canReadRepoMock.mockResolvedValue(true);
    canAdminRepoMock.mockResolvedValue(true);
  });

  it("rejects GET when unauthenticated", async () => {
    const response = await getStates({
      params: { owner: "owner-1", repo: "demo" },
      locals: {},
    } as any);

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

  it("rejects duplicate state names on POST", async () => {
    const response = await createState({
      params: { owner: "owner-1", repo: "demo" },
      locals: { user: { id: "admin-1", isAdmin: false } },
      request: new Request("http://localhost/api/repos/owner-1/demo/workflow/states", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ name: "In Review" }),
      }),
    } as any);

    const body = await readJson(response);
    expect(response.status).toBe(400);
    expect(body?.error?.code).toBe("BAD_REQUEST");
  });

  it("blocks DELETE when state is assigned to pull requests", async () => {
    mockDb.query.pullRequests.findFirst.mockResolvedValueOnce({ id: "pr-1" });

    const response = await deleteState({
      params: { owner: "owner-1", repo: "demo", id: "state-1" },
      locals: { user: { id: "admin-1", isAdmin: false } },
    } as any);

    const body = await readJson(response);
    expect(response.status).toBe(400);
    expect(body?.error?.code).toBe("BAD_REQUEST");
    expect(mockDb.__state.deleteCalls).toHaveLength(0);
  });
});