-
Notifications
You must be signed in to change notification settings - Fork 332
Expand file tree
/
Copy pathreplay-pure.test.ts
More file actions
495 lines (445 loc) · 18.4 KB
/
Copy pathreplay-pure.test.ts
File metadata and controls
495 lines (445 loc) · 18.4 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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
import { readFileSync } from "fs";
import { join } from "path";
import tmp from "tmp-promise";
import { vi } from "vitest";
import { parseCommitMessageForPR } from "../pipeline/github/parseCommitMessage";
import {
formatConflictReason,
formatReplayPrBody,
logReplaySummary,
patchDescription
} from "../pipeline/replay-summary";
import { ensureReplayFernignoreEntries, GITATTRIBUTES_ENTRIES, REPLAY_FERNIGNORE_ENTRIES } from "../replay/fernignore";
// ---------------------------------------------------------------------------
// formatConflictReason
// ---------------------------------------------------------------------------
describe("formatConflictReason", () => {
it("maps same-line-edit", () => {
expect(formatConflictReason("same-line-edit")).toBe("The new generation changed the same lines you edited");
});
it("maps new-file-both", () => {
expect(formatConflictReason("new-file-both")).toBe(
"Both the generator and your customization created this file"
);
});
it("maps base-generation-mismatch", () => {
expect(formatConflictReason("base-generation-mismatch")).toBe(
"This customization was from a previous generation"
);
});
it("maps patch-apply-failed", () => {
expect(formatConflictReason("patch-apply-failed")).toBe(
"The customization could not be applied to the new code"
);
});
it("returns fallback for undefined", () => {
expect(formatConflictReason(undefined)).toBe("Your edit overlaps with changes in the new generation");
});
it("returns fallback for unknown strings", () => {
expect(formatConflictReason("some-unknown-reason")).toBe(
"Your edit overlaps with changes in the new generation"
);
});
});
// ---------------------------------------------------------------------------
// patchDescription
// ---------------------------------------------------------------------------
describe("patchDescription", () => {
it("returns patchMessage when truthy and not 'update'", () => {
expect(patchDescription({ patchMessage: "add custom auth header", files: ["src/auth.ts"] })).toBe(
"add custom auth header"
);
});
it("returns 'changes in <file>' when patchMessage is falsy (empty string)", () => {
expect(patchDescription({ patchMessage: "", files: ["src/client.ts"] })).toBe("changes in src/client.ts");
});
it("returns 'changes in <file>' when patchMessage is 'update'", () => {
expect(patchDescription({ patchMessage: "update", files: ["src/index.ts"] })).toBe("changes in src/index.ts");
});
it("returns 'customization' when no files and no useful patchMessage", () => {
expect(patchDescription({ patchMessage: "", files: [] })).toBe("customization");
});
it("returns 'customization' when patchMessage is 'update' and no files", () => {
expect(patchDescription({ patchMessage: "update", files: [] })).toBe("customization");
});
});
// ---------------------------------------------------------------------------
// logReplaySummary
// ---------------------------------------------------------------------------
describe("logReplaySummary", () => {
function makeLogger() {
return {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn()
};
}
it("does nothing when not executed", () => {
const logger = makeLogger();
logReplaySummary({ executed: false, success: true }, logger);
expect(logger.debug).not.toHaveBeenCalled();
expect(logger.info).not.toHaveBeenCalled();
expect(logger.warn).not.toHaveBeenCalled();
expect(logger.error).not.toHaveBeenCalled();
});
it("logs debug line for first-generation flow", () => {
const logger = makeLogger();
logReplaySummary(
{ executed: true, success: true, flow: "first-generation", patchesDetected: 0, patchesApplied: 0 },
logger
);
expect(logger.debug).toHaveBeenCalledTimes(1);
expect(logger.debug.mock.calls[0]?.[0]).toContain("flow=first-generation");
});
it("logs info when preserved patches > 0", () => {
const logger = makeLogger();
logReplaySummary(
{
executed: true,
success: true,
flow: "normal-regeneration",
patchesApplied: 3,
patchesAbsorbed: 0
},
logger
);
expect(logger.info).toHaveBeenCalledTimes(1);
expect(logger.info.mock.calls[0]?.[0]).toContain("customizations preserved");
});
it("logs info when only absorbed patches (all applied became part of generated code)", () => {
const logger = makeLogger();
logReplaySummary(
{
executed: true,
success: true,
flow: "normal-regeneration",
patchesApplied: 2,
patchesAbsorbed: 2
},
logger
);
// preserved = applied - absorbed = 0, absorbed > 0 => "now part of generated code"
expect(logger.info).toHaveBeenCalledTimes(1);
expect(logger.info.mock.calls[0]?.[0]).toContain("now part of generated code");
});
it("logs warn for unresolved patches with file details", () => {
const logger = makeLogger();
logReplaySummary(
{
executed: true,
success: false,
flow: "normal-regeneration",
patchesApplied: 0,
patchesAbsorbed: 0,
unresolvedPatches: [
{
patchId: "patch-1",
patchMessage: "add retry logic",
files: ["src/client.ts"],
conflictDetails: [{ file: "src/client.ts", conflictReason: "same-line-edit" }]
}
]
},
logger
);
// Should have at least 2 warn calls: summary line + patch description + file detail
expect(logger.warn).toHaveBeenCalled();
const warnMessages = logger.warn.mock.calls.map((c: unknown[]) => c[0] as string);
expect(warnMessages.some((m) => m.includes("unresolved"))).toBe(true);
expect(warnMessages.some((m) => m.includes("src/client.ts"))).toBe(true);
});
it("logs warnings from result.warnings", () => {
const logger = makeLogger();
logReplaySummary(
{
executed: true,
success: true,
flow: "normal-regeneration",
patchesApplied: 0,
patchesAbsorbed: 0,
warnings: ["lockfile version mismatch"]
},
logger
);
expect(logger.warn).toHaveBeenCalled();
const warnMessages = logger.warn.mock.calls.map((c: unknown[]) => c[0] as string);
expect(warnMessages.some((m) => m.includes("lockfile version mismatch"))).toBe(true);
});
});
// ---------------------------------------------------------------------------
// formatReplayPrBody
// ---------------------------------------------------------------------------
describe("formatReplayPrBody", () => {
it("returns undefined for undefined result", () => {
expect(formatReplayPrBody(undefined)).toBeUndefined();
});
it("returns undefined when result is not executed", () => {
expect(formatReplayPrBody({ executed: false, success: true })).toBeUndefined();
});
it("returns undefined when zero preserved and no unresolved patches", () => {
expect(
formatReplayPrBody({
executed: true,
success: true,
patchesApplied: 0,
patchesAbsorbed: 0,
unresolvedPatches: []
})
).toBeUndefined();
});
it("returns happy-path body with checkbox when preserved > 0 and no conflicts", () => {
const body = formatReplayPrBody({
executed: true,
success: true,
patchesApplied: 3,
patchesAbsorbed: 0,
unresolvedPatches: []
});
expect(body).toBeDefined();
// Checkbox emoji ✅ is U+2705
expect(body).toContain("\u2705");
expect(body).toContain("preserved");
expect(body).not.toContain("Action required");
});
it("returns conflict body with markdown table when unresolved patches exist", () => {
const body = formatReplayPrBody({
executed: true,
success: false,
patchesApplied: 0,
patchesAbsorbed: 0,
unresolvedPatches: [
{
patchId: "p1",
patchMessage: "add retry logic",
files: ["src/client.ts"],
conflictDetails: [{ file: "src/client.ts", conflictReason: "same-line-edit" }]
}
]
});
expect(body).toBeDefined();
expect(body).toContain("Action required");
// Table header
expect(body).toContain("| File |");
expect(body).toContain("Your customization");
expect(body).toContain("Why it conflicted");
// Table row
expect(body).toContain("src/client.ts");
expect(body).toContain("add retry logic");
expect(body).toContain("The new generation changed the same lines you edited");
});
it("includes branch name in resolution instructions when branchName option is provided", () => {
const body = formatReplayPrBody(
{
executed: true,
success: false,
patchesApplied: 0,
patchesAbsorbed: 0,
unresolvedPatches: [
{
patchId: "p1",
patchMessage: "tweak",
files: ["src/api.ts"],
conflictDetails: [{ file: "src/api.ts", conflictReason: "patch-apply-failed" }]
}
]
},
{ branchName: "fern-bot/my-sdk-branch" }
);
expect(body).toContain("fern-bot/my-sdk-branch");
});
it("includes clone URL when repoUri option is provided", () => {
const body = formatReplayPrBody(
{
executed: true,
success: false,
patchesApplied: 0,
patchesAbsorbed: 0,
unresolvedPatches: [
{
patchId: "p1",
patchMessage: "tweak",
files: ["src/api.ts"],
conflictDetails: [{ file: "src/api.ts", conflictReason: "patch-apply-failed" }]
}
]
},
{ branchName: "fern-bot/branch", repoUri: "my-org/my-sdk" }
);
expect(body).toContain("my-org/my-sdk");
expect(body).toContain("git clone");
});
it("table rows match number of conflict detail entries across patches", () => {
const body = formatReplayPrBody({
executed: true,
success: false,
patchesApplied: 1,
patchesAbsorbed: 0,
unresolvedPatches: [
{
patchId: "p1",
patchMessage: "my patch",
files: ["a.ts", "b.ts"],
conflictDetails: [
{ file: "a.ts", conflictReason: "same-line-edit" },
{ file: "b.ts", conflictReason: "new-file-both" }
]
}
]
});
expect(body).toBeDefined();
// Count table data rows (lines starting with "| `")
const lines = body?.split("\n") ?? [];
const dataRows = lines.filter((l) => l.startsWith("| `"));
expect(dataRows).toHaveLength(2);
expect(dataRows[0]).toContain("a.ts");
expect(dataRows[1]).toContain("b.ts");
});
});
// ---------------------------------------------------------------------------
// parseCommitMessageForPR
// ---------------------------------------------------------------------------
describe("parseCommitMessageForPR", () => {
it("single-line message -> title is that line, body is default", () => {
const { prTitle, prBody } = parseCommitMessageForPR("Update SDK");
expect(prTitle).toBe("Update SDK");
expect(prBody).toBe("Automated SDK generation by Fern");
});
it("multi-line message -> title is first line, body is rest of message", () => {
const { prTitle, prBody } = parseCommitMessageForPR("Update SDK\n\nAdded new endpoints");
expect(prTitle).toBe("Update SDK");
expect(prBody).toBe("Added new endpoints");
});
it("with changelogEntry -> body uses changelog when no prDescription", () => {
const { prTitle, prBody } = parseCommitMessageForPR("Update SDK", "## Changelog\n- feature A");
expect(prTitle).toBe("Update SDK");
expect(prBody).toBe("## Changelog\n- feature A");
});
it("with prDescription -> prefers prDescription over changelogEntry", () => {
const { prTitle, prBody } = parseCommitMessageForPR(
"Update SDK",
"## Changelog\n- feature A",
"## Before/After\n```before```\n```after```"
);
expect(prTitle).toBe("Update SDK");
expect(prBody).toBe("## Before/After\n```before```\n```after```");
});
it("with versionBumpReason but non-MAJOR bump -> reason is not shown", () => {
const { prTitle, prBody } = parseCommitMessageForPR(
"Update SDK",
undefined,
undefined,
"Minor dependency bump"
);
expect(prTitle).toBe("Update SDK");
expect(prBody).not.toContain("Minor dependency bump");
expect(prBody).toContain("Automated SDK generation by Fern");
});
it("with versionBumpReason and MAJOR bump -> reason is shown as Breaking", () => {
const { prBody } = parseCommitMessageForPR(
"Update SDK",
undefined,
"Custom PR description",
"Removed getUser endpoint",
"1.0.0",
"2.0.0",
"MAJOR"
);
expect(prBody).toContain("**Breaking:** Removed getUser endpoint");
expect(prBody).toContain("Custom PR description");
expect(prBody).toContain("1.0.0 \u2192 2.0.0");
});
it("empty message -> default title 'SDK Generation'", () => {
const { prTitle } = parseCommitMessageForPR("");
expect(prTitle).toBe("SDK Generation");
});
it("blank/whitespace-only message -> default title 'SDK Generation'", () => {
const { prTitle } = parseCommitMessageForPR(" ");
expect(prTitle).toBe("SDK Generation");
});
it("with changelogUrl -> appends full changelog link", () => {
const { prBody } = parseCommitMessageForPR(
"Update SDK",
undefined,
"Some changes",
undefined,
"1.0.0",
"1.1.0",
"MINOR",
"https://github.com/owner/repo/blob/fern-bot/branch/changelog.md"
);
expect(prBody).toContain("[See full changelog]");
expect(prBody).toContain("https://github.com/owner/repo/blob/fern-bot/branch/changelog.md");
});
it("without changelogUrl -> no changelog link appended", () => {
const { prBody } = parseCommitMessageForPR(
"Update SDK",
undefined,
"Some changes",
undefined,
"1.0.0",
"1.1.0",
"MINOR"
);
expect(prBody).not.toContain("[See full changelog]");
});
});
// ---------------------------------------------------------------------------
// fernignore
// ---------------------------------------------------------------------------
describe("fernignore", () => {
it("REPLAY_FERNIGNORE_ENTRIES contains expected values", () => {
expect(REPLAY_FERNIGNORE_ENTRIES).toContain(".fern/replay.lock");
expect(REPLAY_FERNIGNORE_ENTRIES).toContain(".fern/replay.yml");
expect(REPLAY_FERNIGNORE_ENTRIES).toContain(".gitattributes");
expect(REPLAY_FERNIGNORE_ENTRIES.length).toBeGreaterThanOrEqual(3);
});
it("GITATTRIBUTES_ENTRIES marks the replay lockfile as linguist-generated", () => {
expect(GITATTRIBUTES_ENTRIES).toContain(".fern/replay.lock linguist-generated=true");
});
it("creates .fernignore with entries when no file exists, returns true", async () => {
const dir = await tmp.dir({ unsafeCleanup: true });
try {
const modified = await ensureReplayFernignoreEntries(dir.path);
expect(modified).toBe(true);
const content = readFileSync(join(dir.path, ".fernignore"), "utf-8");
for (const entry of REPLAY_FERNIGNORE_ENTRIES) {
expect(content).toContain(entry);
}
} finally {
await dir.cleanup();
}
});
it("appends missing entries to existing .fernignore, returns true", async () => {
const dir = await tmp.dir({ unsafeCleanup: true });
try {
const fernignorePath = join(dir.path, ".fernignore");
// Write a .fernignore that has unrelated entries but NOT the replay entries
const { writeFileSync } = await import("fs");
writeFileSync(fernignorePath, "node_modules\ndist\n", "utf-8");
const modified = await ensureReplayFernignoreEntries(dir.path);
expect(modified).toBe(true);
const content = readFileSync(fernignorePath, "utf-8");
// Original entries preserved
expect(content).toContain("node_modules");
// Replay entries appended
for (const entry of REPLAY_FERNIGNORE_ENTRIES) {
expect(content).toContain(entry);
}
} finally {
await dir.cleanup();
}
});
it("returns false when .fernignore already has all entries", async () => {
const dir = await tmp.dir({ unsafeCleanup: true });
try {
const fernignorePath = join(dir.path, ".fernignore");
const { writeFileSync } = await import("fs");
writeFileSync(fernignorePath, REPLAY_FERNIGNORE_ENTRIES.join("\n") + "\n", "utf-8");
const modified = await ensureReplayFernignoreEntries(dir.path);
expect(modified).toBe(false);
} finally {
await dir.cleanup();
}
});
});