-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
e2e.ts
710 lines (657 loc) · 20.6 KB
/
e2e.ts
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
import execa from "execa";
import * as uvu from "uvu";
import * as assert from "uvu/assert";
import { Monorepo } from "../monorepo";
import path from "path";
import * as fs from "fs";
const basicPipeline = {
pipeline: {
test: {
dependsOn: ["^build"],
outputs: [],
},
lint: {
inputs: ["build.js", "lint.js"],
outputs: [],
},
build: {
dependsOn: ["^build"],
outputs: ["dist/**"],
},
"//#build": {
dependsOn: [],
outputs: ["dist/**"],
inputs: ["rootbuild.js"],
},
"//#special": {
dependsOn: ["^build"],
outputs: ["dist/**"],
inputs: [],
},
"//#args": {
dependsOn: [],
outputs: [],
},
},
globalDependencies: ["$GLOBAL_ENV_DEPENDENCY"],
};
// This is injected by github actions
process.env.TURBO_TOKEN = "";
let suites = [];
for (let npmClient of ["yarn", "berry", "pnpm6", "pnpm", "npm"] as const) {
const Suite = uvu.suite(`${npmClient}`);
const repo = new Monorepo("basics");
repo.init(npmClient, basicPipeline);
repo.install();
repo.addPackage("a", ["b"]);
repo.addPackage("b");
repo.addPackage("c");
repo.linkPackages();
repo.expectCleanGitStatus();
runSmokeTests(Suite, repo, npmClient);
const sub = new Monorepo("in-subdirectory");
sub.init(npmClient, basicPipeline, "js");
sub.install();
sub.addPackage("a", ["b"]);
sub.addPackage("b");
sub.addPackage("c");
sub.linkPackages();
runSmokeTests(Suite, sub, npmClient, {
cwd: path.join(sub.root, sub.subdir),
});
suites.push(Suite);
// test that turbo can run from a subdirectory
}
for (let s of suites) {
s.run();
}
type Task = {
taskId: string;
task: string;
package: string;
hash: string;
command: string;
outputs: string[];
logFile: string;
directory: string;
dependencies: string[];
dependents: string[];
};
type DryRun = {
packages: string[];
tasks: Task[];
};
const matchTask =
<T, V>(predicate: (dryRun: DryRun, val: T) => V) =>
(dryRun: DryRun) =>
(val: T): V => {
return predicate(dryRun, val);
};
const includesTaskIdPredicate = (dryRun: DryRun, task: string): boolean => {
for (const entry of dryRun.tasks) {
if (entry.taskId === task) {
return true;
}
}
return false;
};
const includesTaskId = matchTask(includesTaskIdPredicate);
const taskHashPredicate = (dryRun: DryRun, taskId: string): string => {
for (const entry of dryRun.tasks) {
if (entry.taskId === taskId) {
return entry.hash;
}
}
throw new Error(`missing task with id ${taskId}`);
};
function runSmokeTests<T>(
suite: uvu.Test<T>,
repo: Monorepo,
npmClient: "yarn" | "berry" | "pnpm6" | "pnpm" | "npm",
options: execa.SyncOptions<string> = {}
) {
suite.after(() => {
repo.cleanup();
});
suite(
`${npmClient} builds${options.cwd ? " from " + options.cwd : ""}`,
async () => {
const results = repo.turbo("run", ["build", "--dry=json"], options);
const dryRun: DryRun = JSON.parse(results.stdout);
// expect to run all packages
const expectTaskId = includesTaskId(dryRun);
for (const pkg of ["a", "b", "c", "//"]) {
assert.ok(
dryRun.packages.includes(pkg),
`Expected to include package ${pkg}`
);
assert.ok(
expectTaskId(pkg + "#build"),
`Expected to include task ${pkg}#build`
);
}
// actually run the build
const buildOutput = getCommandOutputAsArray(
repo.turbo("run", ["build"], options)
);
assert.ok(
buildOutput.includes("//:build: building"),
"Missing root build"
);
// assert that hashes are stable across multiple runs
const secondRun = repo.turbo("run", ["build", "--dry=json"], options);
const secondDryRun: DryRun = JSON.parse(secondRun.stdout);
repo.turbo("run", ["build"], options);
const thirdRun = repo.turbo("run", ["build", "--dry=json"], options);
const thirdDryRun: DryRun = JSON.parse(thirdRun.stdout);
const getThirdRunHash = matchTask(taskHashPredicate)(thirdDryRun);
for (const entry of secondDryRun.tasks) {
assert.equal(
getThirdRunHash(entry.taskId),
entry.hash,
`Hashes for ${entry.taskId} did not match`
);
}
}
);
suite(
`${npmClient} runs tests and logs${
options.cwd ? " from " + options.cwd : ""
}`,
async () => {
const results = repo.turbo(
"run",
["test", "--stream", "--profile=chrometracing"],
options
);
assert.equal(0, results.exitCode, "exit code should be 0");
const commandOutput = getCommandOutputAsArray(results);
const hash = getHashFromOutput(commandOutput, "c#test");
assert.ok(!!hash, "No hash for c#test");
const cachedLogFilePath = getCachedLogFilePathForTask(
getCachedDirForHash(repo, hash),
path.join("packages", "c"),
"test"
);
let text = "";
assert.not.throws(() => {
text = repo.readFileSync(cachedLogFilePath);
}, `Could not read cached log file from cache ${cachedLogFilePath}`);
assert.ok(text.includes("testing c"), "Contains correct output");
const root = options.cwd ? options.cwd : repo.root;
const tracingFile = path.join(root, "chrometracing");
const tracingBuf = fs.readFileSync(tracingFile);
// ensure it doesn't throw
JSON.parse(tracingBuf.toString("utf-8"));
// don't throw off hashes for later tests
fs.unlinkSync(tracingFile);
}
);
suite(
`${npmClient} runs lint and logs${
options.cwd ? " from " + options.cwd : ""
}`,
async () => {
const results = repo.turbo("run", ["lint", "--stream"], options);
assert.equal(0, results.exitCode, "exit code should be 0");
const commandOutput = getCommandOutputAsArray(results);
const hash = getHashFromOutput(commandOutput, "c#lint");
assert.ok(!!hash, "No hash for c#lint");
const cachedLogFilePath = getCachedLogFilePathForTask(
getCachedDirForHash(repo, hash),
path.join("packages", "c"),
"lint"
);
let text = "";
assert.not.throws(() => {
text = repo.readFileSync(cachedLogFilePath);
}, `Could not read cached log file from cache ${cachedLogFilePath}`);
assert.ok(text.includes("linting c"), "Contains correct output");
}
);
suite(
`${npmClient} handles filesystem changes${
options.cwd ? " from " + options.cwd : ""
}`,
async () => {
repo.newBranch("my-feature-branch");
repo.commitFiles({
[path.join("packages", "a", "test.js")]: `console.log('testingz a');`,
});
const sinceCommandOutputNoCache = getCommandOutputAsArray(
repo.turbo(
"run",
["test", "--since=main", "--stream", "--no-cache"],
options
)
);
assert.fixture(
sinceCommandOutputNoCache[0],
`• Packages in scope: a`,
"Packages in scope"
);
assert.fixture(
sinceCommandOutputNoCache[1],
`• Running test in 1 packages`,
"Runs only in changed packages"
);
assert.ok(
sinceCommandOutputNoCache.includes(
`a:test: cache miss, executing ${getHashFromOutput(
sinceCommandOutputNoCache,
"a#test"
)}`
),
"Cache miss in changed package"
);
const sinceCommandOutput = getCommandOutputAsArray(
repo.turbo(
"run",
["test", "--since=main", "--stream", "--output-logs=hash-only"],
options
)
);
assert.fixture(
sinceCommandOutput[0],
`• Packages in scope: a`,
"Packages in scope"
);
assert.fixture(
sinceCommandOutput[1],
`• Running test in 1 packages`,
"Runs only in changed packages"
);
assert.ok(
sinceCommandOutput.includes(
`a:test: cache miss, executing ${getHashFromOutput(
sinceCommandOutput,
"a#test"
)}`
),
"Cache miss in changed package"
);
// Check cache hit after another run
const sinceCommandSecondRunOutput = getCommandOutputAsArray(
repo.turbo(
"run",
["test", "--since=main", "--stream", "--output-logs=hash-only"],
options
)
);
assert.equal(
sinceCommandSecondRunOutput[0],
`• Packages in scope: a`,
"Packages in scope after a second run"
);
assert.equal(
sinceCommandSecondRunOutput[1],
`• Running test in 1 packages`,
"Runs only in changed packages after a second run"
);
assert.ok(
sinceCommandSecondRunOutput.includes(
`b:build: cache hit, suppressing output ${getHashFromOutput(
sinceCommandSecondRunOutput,
"b#build"
)}`
),
"Cache hit building dependency after a second run"
);
assert.ok(
sinceCommandSecondRunOutput.includes(
`a:test: cache hit, suppressing output ${getHashFromOutput(
sinceCommandSecondRunOutput,
"a#test"
)}`
),
"Cache hit in changed package after a second run"
);
// run a task without dependencies
// ensure that uncommitted irrelevant changes are also ignored
repo.modifyFiles({
[path.join("packages", "a", "README.md")]: "important text",
});
const lintOutput = getCommandOutputAsArray(
repo.turbo(
"run",
["lint", "--filter=a", "--stream", "--output-logs=hash-only"],
options
)
);
assert.equal(
lintOutput[0],
`• Packages in scope: a`,
"Packages in scope for lint"
);
assert.ok(
lintOutput.includes(
`a:lint: cache hit, suppressing output ${getHashFromOutput(
lintOutput,
"a#lint"
)}`
),
"Cache hit, a has changed but not a file lint depends on"
);
// Check that hashes are different and trigger a cascade
repo.commitFiles({
[path.join("packages", "b", "test.js")]: `console.log('testingz b');`,
});
const secondLintRun = getCommandOutputAsArray(
repo.turbo(
"run",
["lint", "--filter=a", "--stream", "--output-logs=hash-only"],
options
)
);
assert.equal(
secondLintRun[0],
`• Packages in scope: a`,
"Packages in scope for lint"
);
assert.ok(
secondLintRun.includes(
`a:lint: cache hit, suppressing output ${getHashFromOutput(
secondLintRun,
"a#lint"
)}`
),
"Cache hit, dependency changes are irrelevant for lint task"
);
repo.commitFiles({
[path.join("packages", "a", "lint.js")]: "console.log('lintingz a')",
});
const thirdLintRun = getCommandOutputAsArray(
repo.turbo(
"run",
["lint", "--filter=a", "--stream", "--output-logs=hash-only"],
options
)
);
assert.equal(
thirdLintRun[0],
`• Packages in scope: a`,
"Packages in scope for lint"
);
assert.ok(
thirdLintRun.includes(
`a:lint: cache miss, executing ${getHashFromOutput(
thirdLintRun,
"a#lint"
)}`
),
"Cache miss, we changed a file that lint uses as an input"
);
const commandOnceBHasChangedOutput = getCommandOutputAsArray(
repo.turbo("run", ["test", "--stream"], options)
);
assert.fixture(
`• Packages in scope: a, b, c`,
commandOnceBHasChangedOutput[0],
"After running, changing source of b, and running `turbo run test` again, should print `Packages in scope: a, b, c`"
);
assert.fixture(
`• Running test in 3 packages`,
commandOnceBHasChangedOutput[1],
"After running, changing source of b, and running `turbo run test` again, should print `Running in 3 packages`"
);
assert.ok(
commandOnceBHasChangedOutput.findIndex((l) =>
l.startsWith("a:test: cache miss, executing")
) >= 0,
"After running, changing source of b, and running `turbo run test` again, should print `a:test: cache miss, executing` since a depends on b and b has changed"
);
assert.ok(
commandOnceBHasChangedOutput.findIndex((l) =>
l.startsWith("b:test: cache miss, executing")
) >= 0,
"After running, changing source of b, and running `turbo run test` again, should print `b:test: cache miss, executing` since b has changed"
);
assert.ok(
commandOnceBHasChangedOutput.findIndex((l) =>
l.startsWith("c:test: cache hit, replaying output")
) >= 0,
"After running, changing source of b, and running `turbo run test` again, should print `c:test: cache hit, replaying output` since c should not be impacted by changes to b"
);
const scopeCommandOutput = getCommandOutputAsArray(
repo.turbo("run", ["test", '--scope="!b"', "--stream"], options)
);
assert.fixture(
`• Packages in scope: a, c`,
scopeCommandOutput[0],
"Packages in scope"
);
assert.fixture(
`• Running test in 2 packages`,
scopeCommandOutput[1],
"Runs only in changed packages"
);
}
);
suite(
`${npmClient} runs root tasks${options.cwd ? " from " + options.cwd : ""}`,
async () => {
const result = getCommandOutputAsArray(
repo.turbo("run", ["special"], options)
);
assert.ok(result.includes("//:special: root task"));
const secondPass = getCommandOutputAsArray(
repo.turbo(
"run",
["special", "--filter=//", "--output-logs=hash-only"],
options
)
);
assert.ok(
secondPass.includes(
`//:special: cache hit, suppressing output ${getHashFromOutput(
secondPass,
"//#special"
)}`
),
"Rerun of //:special should be cached"
);
}
);
suite(
`${npmClient} passes through correct args ${
options.cwd ? " from " + options.cwd : ""
}`,
async () => {
const expectArgsPassed = (inputArgs: string[], passedArgs: string[]) => {
const result = getCommandOutputAsArray(
repo.turbo("run", inputArgs, options)
);
// Find the output logs of the test script
const needle = "//:args: Output:";
const script_output = result.find((line) => line.startsWith(needle));
assert.ok(
script_output != undefined && script_output.startsWith(needle),
`Unable to find '//:arg' output in '${result}'`
);
const [node, ...args] = JSON.parse(
script_output.substring(needle.length)
);
assert.match(
node,
"node",
`Expected node binary path (${node}) to contain 'node'`
);
assert.equal(args, passedArgs);
};
const tests = [
[["args", "--filter=//", "--", "--script-arg=42"], ["--script-arg=42"]],
[["args", "--filter=//", "--", "--filter=//"], ["--filter=//"]],
[["--filter=//", "args", "--", "--filter=//"], ["--filter=//"]],
[
["args", "--", "--script-arg", "42"],
["--script-arg", "42"],
],
[["args"], []],
[["args", "--"], []],
[
["args", "--", "--", "--"],
["--", "--"],
],
[
["args", "--", "first", "--", "second"],
["first", "--", "second"],
],
[
["args", "--", "-f", "--f", "---f", "----f"],
["-f", "--f", "---f", "----f"],
],
];
for (const [input, expected] of tests) {
expectArgsPassed(input, expected);
}
}
);
if (["yarn", "pnpm6", "pnpm"].includes(npmClient)) {
// Test `turbo prune --scope=a`
// @todo refactor with other package managers
const installArgs = ["--frozen-lockfile"];
suite(
`${npmClient} + turbo prune${options.cwd ? " from " + options.cwd : ""}`,
async () => {
const pruneCommandOutput = getCommandOutputAsArray(
repo.turbo("prune", ["--scope=a"], options)
);
assert.fixture(pruneCommandOutput[1], " - Added a");
assert.fixture(pruneCommandOutput[2], " - Added b");
let files = [];
assert.not.throws(() => {
files = repo.globbySync("out/**/*", {
cwd: options.cwd ?? repo.root,
});
}, `Could not read generated \`out\` directory after \`turbo prune\``);
const expected = [
"out/package.json",
"out/turbo.json",
`out/${getLockfileForPackageManager(npmClient)}`,
"out/packages/a/build.js",
"out/packages/a/lint.js",
"out/packages/a/package.json",
"out/packages/a/test.js",
"out/packages/b/build.js",
"out/packages/b/lint.js",
"out/packages/b/package.json",
"out/packages/b/test.js",
];
for (const file of expected) {
assert.ok(
files.includes(file),
`Expected file ${file} to be generated`
);
}
const install = repo.run("install", installArgs, {
cwd: options.cwd
? path.join(options.cwd, "out")
: path.join(repo.root, "out"),
});
assert.is(
install.exitCode,
0,
`Expected ${npmClient} install --frozen-lockfile to succeed`
);
}
);
suite(
`${npmClient} + turbo prune --docker${
options.cwd ? " from " + options.cwd : ""
}`,
async () => {
const pruneCommandOutput = getCommandOutputAsArray(
repo.turbo("prune", ["--scope=a", "--docker"], options)
);
assert.fixture(pruneCommandOutput[1], " - Added a");
assert.fixture(pruneCommandOutput[2], " - Added b");
let files = [];
assert.not.throws(() => {
files = repo.globbySync("out/**/*", {
cwd: options.cwd ?? repo.root,
});
}, `Could not read generated \`out\` directory after \`turbo prune\``);
const expected = [
"out/full/package.json",
"out/json/package.json",
"out/full/turbo.json",
`out/${getLockfileForPackageManager(npmClient)}`,
"out/full/packages/a/build.js",
"out/full/packages/a/lint.js",
"out/full/packages/a/package.json",
"out/json/packages/a/package.json",
"out/full/packages/a/test.js",
"out/full/packages/b/build.js",
"out/full/packages/b/lint.js",
"out/full/packages/b/package.json",
"out/json/packages/b/package.json",
"out/full/packages/b/test.js",
];
for (const file of expected) {
assert.ok(
files.includes(file),
`Expected file ${file} to be generated`
);
}
const install = repo.run("install", installArgs, {
cwd: options.cwd
? path.join(options.cwd, "out")
: path.join(repo.root, "out"),
});
assert.is(
install.exitCode,
0,
`Expected ${npmClient} install --frozen-lockfile to succeed`
);
}
);
}
}
type PackageManager = "yarn" | "pnpm6" | "pnpm" | "npm" | "berry";
// getLockfileForPackageManager returns the name of the lockfile for the given package manager
function getLockfileForPackageManager(ws: PackageManager) {
switch (ws) {
case "yarn":
return "yarn.lock";
case "pnpm":
return "pnpm-lock.yaml";
case "pnpm6":
return "pnpm-lock.yaml";
case "npm":
return "package-lock.json";
case "berry":
return "yarn.lock";
default:
throw new Error(`Unknown package manager: ${ws}`);
}
}
function getCommandOutputAsArray(
results: execa.ExecaSyncReturnValue<string>
): string[] {
return (results.stdout + results.stderr)
.split("\n")
.map((line) => line.replace("\r", ""));
}
function getHashFromOutput(lines: string[], taskId: string): string {
const normalizedTaskId = taskId.replace("#", ":");
const line = lines.find((l) => l.startsWith(normalizedTaskId));
const splitMessage = line.split(" ");
const hash = splitMessage[splitMessage.length - 1];
return hash;
}
function getCachedDirForHash(repo: Monorepo, hash: string): string {
return path.join(
repo.subdir ? repo.subdir : ".",
"node_modules",
".cache",
"turbo",
hash
);
}
function getCachedLogFilePathForTask(
cacheDir: string,
pathToPackage: string,
taskName: string
): string {
return path.join(cacheDir, pathToPackage, ".turbo", `turbo-${taskName}.log`);
}