-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathsigned-commit-artefacts.test.ts
More file actions
301 lines (266 loc) · 8.36 KB
/
Copy pathsigned-commit-artefacts.test.ts
File metadata and controls
301 lines (266 loc) · 8.36 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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import {
afterAll,
afterEach,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from "vitest";
import {
reportCommitArtefacts,
reportTaskRunBranch,
resolveSandboxPosthogApi,
} from "./signed-commit-artefacts";
const ENV = {
POSTHOG_API_URL: "https://us.posthog.com",
POSTHOG_PERSONAL_API_KEY: "pha_test",
POSTHOG_PROJECT_ID: "7",
};
// Point the env-file read at a path that never exists so only `env` is used.
const NO_ENV_FILE = "/nonexistent/agent-env";
const TEST_OAUTH_ENV_FILE = path.join(
tmpdir(),
`posthog-agent-oauth-env-${process.pid}`,
);
beforeAll(async () => {
await writeFile(TEST_OAUTH_ENV_FILE, "POSTHOG_PERSONAL_API_KEY=pha_test\0");
});
afterAll(async () => {
await rm(TEST_OAUTH_ENV_FILE, { force: true });
});
describe("resolveSandboxPosthogApi", () => {
it("reads the rotating API key from the dedicated OAuth file", async () => {
const directory = await mkdtemp(
path.join(tmpdir(), "sandbox-posthog-api-"),
);
const envFilePath = path.join(directory, "agent-env");
const oauthEnvFilePath = path.join(directory, "agent-oauth-env");
try {
await writeFile(
envFilePath,
"POSTHOG_API_URL=https://us.posthog.com\0POSTHOG_PROJECT_ID=7\0",
);
await writeFile(
oauthEnvFilePath,
"POSTHOG_PERSONAL_API_KEY=pha_refreshed\0",
);
expect(
resolveSandboxPosthogApi({}, envFilePath, oauthEnvFilePath),
).toEqual({
apiUrl: "https://us.posthog.com",
apiKey: "pha_refreshed",
projectId: 7,
});
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("fails closed without the dedicated OAuth file", () => {
expect(
resolveSandboxPosthogApi(ENV, NO_ENV_FILE, NO_ENV_FILE),
).toBeUndefined();
});
it("does not resurrect a stale token when the OAuth file is empty", async () => {
const directory = await mkdtemp(
path.join(tmpdir(), "sandbox-posthog-api-"),
);
const envFilePath = path.join(directory, "agent-env");
const oauthEnvFilePath = path.join(directory, "agent-oauth-env");
try {
await writeFile(
envFilePath,
"POSTHOG_API_URL=https://us.posthog.com\0POSTHOG_PERSONAL_API_KEY=pha_stale\0POSTHOG_PROJECT_ID=7\0",
);
await writeFile(oauthEnvFilePath, "");
expect(
resolveSandboxPosthogApi(ENV, envFilePath, oauthEnvFilePath),
).toBeUndefined();
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("fails closed when the managed OAuth file is unreadable", async () => {
const directory = await mkdtemp(
path.join(tmpdir(), "sandbox-posthog-api-"),
);
const envFilePath = path.join(directory, "agent-env");
try {
await writeFile(
envFilePath,
"POSTHOG_API_URL=https://us.posthog.com\0POSTHOG_PROJECT_ID=7\0",
);
expect(
resolveSandboxPosthogApi(ENV, envFilePath, directory),
).toBeUndefined();
} finally {
await rm(directory, { recursive: true, force: true });
}
});
});
const RESULT = {
branch: "posthog-code/fix-foo",
repository: "posthog/posthog",
commits: [
{ sha: "aaa111", url: "https://github.com/posthog/posthog/commit/aaa111" },
{ sha: "bbb222", url: "https://github.com/posthog/posthog/commit/bbb222" },
],
};
describe("reportCommitArtefacts", () => {
const fetchMock = vi.fn();
beforeEach(() => {
fetchMock.mockReset();
vi.stubGlobal("fetch", fetchMock);
vi.spyOn(process.stderr, "write").mockImplementation(() => true);
});
afterEach(() => {
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
function jsonResponse(body: unknown): Response {
return new Response(JSON.stringify(body), {
status: 200,
headers: { "Content-Type": "application/json" },
});
}
it("posts one commit artefact per commit per associated report, attributed via header", async () => {
fetchMock.mockImplementation(async (url: string | URL) => {
if (String(url).includes("/signals/reports/?")) {
return jsonResponse({
results: [{ id: "report-1" }, { id: "report-2" }],
});
}
return jsonResponse({ id: "artefact" });
});
await reportCommitArtefacts({
taskId: "task-1",
result: RESULT,
message: "fix: foo",
env: ENV,
envFilePath: NO_ENV_FILE,
oauthEnvFilePath: TEST_OAUTH_ENV_FILE,
});
const lookupCalls = fetchMock.mock.calls.filter(([url]) =>
String(url).includes("/signals/reports/?task_id=task-1"),
);
expect(lookupCalls).toHaveLength(1);
const postCalls = fetchMock.mock.calls.filter(([url]) =>
String(url).includes("/artefacts/"),
);
// 2 commits × 2 reports.
expect(postCalls).toHaveLength(4);
for (const [url, init] of postCalls) {
expect(String(url)).toMatch(
/\/api\/projects\/7\/signals\/reports\/report-[12]\/artefacts\/$/,
);
const headers = new Headers((init as RequestInit).headers);
expect(headers.get("X-PostHog-Task-Id")).toBe("task-1");
const body = JSON.parse(String((init as RequestInit).body));
expect(body.artefact_type).toBe("commit");
expect(body.content.repository).toBe("posthog/posthog");
expect(body.content.branch).toBe("posthog-code/fix-foo");
expect(["aaa111", "bbb222"]).toContain(body.content.commit_sha);
expect(body.content.message).toBe("fix: foo");
}
});
it("is a no-op without a task id", async () => {
await reportCommitArtefacts({
taskId: undefined,
result: RESULT,
message: "fix: foo",
env: ENV,
envFilePath: NO_ENV_FILE,
});
expect(fetchMock).not.toHaveBeenCalled();
});
it("is a no-op without sandbox PostHog credentials", async () => {
await reportCommitArtefacts({
taskId: "task-1",
result: RESULT,
message: "fix: foo",
env: {},
envFilePath: NO_ENV_FILE,
});
expect(fetchMock).not.toHaveBeenCalled();
});
it("never throws when the report lookup fails", async () => {
fetchMock.mockRejectedValue(new Error("network down"));
await expect(
reportCommitArtefacts({
taskId: "task-1",
result: RESULT,
message: "fix: foo",
env: ENV,
envFilePath: NO_ENV_FILE,
oauthEnvFilePath: TEST_OAUTH_ENV_FILE,
}),
).resolves.toBeUndefined();
});
it("keeps posting remaining artefacts when one post fails", async () => {
let postCount = 0;
fetchMock.mockImplementation(async (url: string | URL) => {
if (String(url).includes("/signals/reports/?")) {
return jsonResponse({ results: [{ id: "report-1" }] });
}
postCount += 1;
if (postCount === 1) {
return new Response("{}", { status: 500 });
}
return jsonResponse({ id: "artefact" });
});
await reportCommitArtefacts({
taskId: "task-1",
result: RESULT,
message: "fix: foo",
env: ENV,
envFilePath: NO_ENV_FILE,
oauthEnvFilePath: TEST_OAUTH_ENV_FILE,
});
// Both commits attempted despite the first failing.
expect(postCount).toBe(2);
});
});
describe("reportTaskRunBranch", () => {
const fetchMock = vi.fn();
beforeEach(() => {
fetchMock.mockReset();
vi.stubGlobal("fetch", fetchMock);
vi.spyOn(process.stderr, "write").mockImplementation(() => true);
});
afterEach(() => {
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
it("persists the signed commit branch on the task run", async () => {
fetchMock.mockResolvedValue(
new Response(JSON.stringify({}), {
status: 200,
headers: { "Content-Type": "application/json" },
}),
);
await reportTaskRunBranch({
taskId: "task-1",
taskRunId: "run-1",
branch: "posthog-code/fix-foo",
env: ENV,
envFilePath: NO_ENV_FILE,
oauthEnvFilePath: TEST_OAUTH_ENV_FILE,
});
expect(fetchMock).toHaveBeenCalledOnce();
const [url, init] = fetchMock.mock.calls[0];
expect(String(url)).toBe(
"https://us.posthog.com/api/projects/7/tasks/task-1/runs/run-1/",
);
expect(init).toMatchObject({
method: "PATCH",
body: JSON.stringify({
branch: "posthog-code/fix-foo",
output: { head_branch: "posthog-code/fix-foo" },
}),
});
});
});