forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathharness.ts
More file actions
1964 lines (1755 loc) · 67.2 KB
/
harness.ts
File metadata and controls
1964 lines (1755 loc) · 67.2 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
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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* This file is loaded in every test file in the repository.
*
* Avoid adding external dependencies here so that we can still run some tests
* without always needing to run `bun install` in development.
*/
import { gc as bunGC, sleepSync, spawnSync, unsafe, which, write } from "bun";
import { heapStats } from "bun:jsc";
import { beforeAll, describe, expect } from "bun:test";
import { ChildProcess, execSync, fork } from "child_process";
import { readdir, readFile, readlink, rm, writeFile } from "fs/promises";
import fs, { closeSync, openSync, rmSync } from "node:fs";
import os from "node:os";
import { dirname, isAbsolute, join } from "path";
import * as numeric from "_util/numeric.ts";
export const BREAKING_CHANGES_BUN_1_2 = false;
export const isMacOS = process.platform === "darwin";
export const isLinux = process.platform === "linux";
export const isPosix = isMacOS || isLinux;
export const isWindows = process.platform === "win32";
export const isIntelMacOS = isMacOS && process.arch === "x64";
export const isArm64 = process.arch === "arm64";
export const isDebug = Bun.version.includes("debug");
export const isCI = process.env.CI !== undefined;
export const libcFamily: "glibc" | "musl" =
process.platform !== "linux"
? "glibc"
: // process.report.getReport() has incorrect type definitions.
(process.report.getReport() as { header: { glibcVersionRuntime: boolean } }).header.glibcVersionRuntime
? "glibc"
: "musl";
export const isMusl = isLinux && libcFamily === "musl";
export const isGlibc = isLinux && libcFamily === "glibc";
export const isBuildKite = process.env.BUILDKITE === "true";
export const isVerbose = process.env.DEBUG === "1";
// Use these to mark a test as flaky or broken.
// This will help us keep track of these tests.
//
// test.todoIf(isFlaky && isMacOS)("this test is flaky");
export const isFlaky = isCI;
export const isBroken = isCI;
export const isASAN = basename(process.execPath).includes("bun-asan");
export const bunEnv: NodeJS.Dict<string> = {
...process.env,
GITHUB_ACTIONS: "false",
BUN_DEBUG_QUIET_LOGS: "1",
NO_COLOR: "1",
FORCE_COLOR: undefined,
TZ: "Etc/UTC",
CI: "1",
BUN_RUNTIME_TRANSPILER_CACHE_PATH: "0",
BUN_FEATURE_FLAG_INTERNAL_FOR_TESTING: "1",
BUN_GARBAGE_COLLECTOR_LEVEL: process.env.BUN_GARBAGE_COLLECTOR_LEVEL || "0",
BUN_FEATURE_FLAG_EXPERIMENTAL_BAKE: "1",
BUN_DEBUG_linkerctx: "0",
WANTS_LOUD: "0",
AGENT: "false",
};
const ciEnv = { ...bunEnv };
if (isASAN) {
bunEnv.ASAN_OPTIONS ??= "allow_user_segv_handler=1:disable_coredump=0";
}
if (isWindows) {
bunEnv.SHELLOPTS = "igncr"; // Ignore carriage return
}
for (let key in bunEnv) {
if (bunEnv[key] === undefined) {
delete ciEnv[key];
delete bunEnv[key];
}
if (key.startsWith("BUN_DEBUG_") && key !== "BUN_DEBUG_QUIET_LOGS") {
delete ciEnv[key];
delete bunEnv[key];
}
if (key.startsWith("BUILDKITE")) {
delete bunEnv[key];
delete process.env[key];
}
}
delete bunEnv.BUN_INSPECT_CONNECT_TO;
delete bunEnv.NODE_ENV;
if (isDebug) {
// This makes debug build memory leak tests more reliable.
// The code for dumping out the debug build transpiled source code has leaks.
bunEnv.BUN_DEBUG_NO_DUMP = "1";
}
export function bunExe() {
if (isWindows) return process.execPath.replaceAll("\\", "/");
return process.execPath;
}
export function nodeExe(): string | null {
return which("node") || null;
}
export function shellExe(): string {
return isWindows ? "pwsh" : "bash";
}
export function gc(force = true) {
bunGC(force);
}
/**
* The garbage collector is not 100% deterministic
*
* We want to assert that SOME of the objects are collected
* But we cannot reliably assert that ALL of them are collected
*
* Therefore, we check that the count is less than or equal to the expected count
*
* @param type
* @param count
* @param maxWait
* @returns
*/
export async function expectMaxObjectTypeCount(
expect: typeof import("bun:test").expect,
type: string,
count: number,
maxWait = 1000,
) {
var { heapStats } = require("bun:jsc");
gc();
if (heapStats().objectTypeCounts[type] <= count) return;
gc(true);
for (const wait = 20; maxWait > 0; maxWait -= wait) {
if (heapStats().objectTypeCounts[type] <= count) break;
await Bun.sleep(wait);
gc();
}
expect(heapStats().objectTypeCounts[type] || 0).toBeLessThanOrEqual(count);
}
// we must ensure that finalizers are run
// so that the reference-counting logic is exercised
export function gcTick(trace = false) {
trace && console.trace("");
// console.trace("hello");
gc();
return Bun.sleep(0);
}
export function withoutAggressiveGC(block: () => unknown) {
if (!unsafe.gcAggressionLevel) return block();
const origGC = unsafe.gcAggressionLevel();
unsafe.gcAggressionLevel(0);
try {
return block();
} finally {
unsafe.gcAggressionLevel(origGC);
}
}
export function hideFromStackTrace(block: CallableFunction) {
Object.defineProperty(block, "name", {
value: "::bunternal::",
configurable: true,
enumerable: true,
writable: true,
});
}
export type DirectoryTree = {
[name: string]:
| string
| Buffer
| DirectoryTree
| ((opts: { root: string }) => Bun.MaybePromise<string | Buffer | DirectoryTree>);
};
export async function makeTree(base: string, tree: DirectoryTree) {
const isDirectoryTree = (value: string | DirectoryTree | Buffer): value is DirectoryTree =>
typeof value === "object" && value && typeof value?.byteLength === "undefined";
for (const [name, raw_contents] of Object.entries(tree)) {
const contents = typeof raw_contents === "function" ? await raw_contents({ root: base }) : raw_contents;
const joined = join(base, name);
if (name.includes("/")) {
const dir = dirname(name);
if (dir !== name && dir !== ".") {
fs.mkdirSync(join(base, dir), { recursive: true });
}
}
if (isDirectoryTree(contents)) {
fs.mkdirSync(joined);
makeTree(joined, contents);
continue;
}
fs.writeFileSync(joined, contents);
}
}
export function makeTreeSyncFromDirectoryTree(base: string, tree: DirectoryTree) {
const isDirectoryTree = (value: string | DirectoryTree | Buffer): value is DirectoryTree =>
typeof value === "object" && value && typeof value?.byteLength === "undefined";
for (const [name, raw_contents] of Object.entries(tree)) {
const contents = (typeof raw_contents === "function" ? raw_contents({ root: base }) : raw_contents) as string;
const joined = join(base, name);
if (name.includes("/")) {
const dir = dirname(name);
if (dir !== name && dir !== ".") {
fs.mkdirSync(join(base, dir), { recursive: true });
}
}
if (isDirectoryTree(contents)) {
fs.mkdirSync(joined);
makeTreeSync(joined, contents);
continue;
}
fs.writeFileSync(joined, contents);
}
}
export function makeTreeSync(base: string, filesOrAbsolutePathToCopyFolderFrom: DirectoryTree | string) {
if (typeof filesOrAbsolutePathToCopyFolderFrom === "string") {
fs.cpSync(filesOrAbsolutePathToCopyFolderFrom, base, { recursive: true });
return;
}
return makeTreeSyncFromDirectoryTree(base, filesOrAbsolutePathToCopyFolderFrom);
}
/**
* Recursively create files within a new temporary directory.
*
* @param basename prefix of the new temporary directory
* @param filesOrAbsolutePathToCopyFolderFrom Directory tree or absolute path to a folder to copy. If passing an object each key is a folder or file, and each value is the contents of the file. Use objects for directories.
* @returns an absolute path to the new temporary directory
*
* @example
* ```ts
* const dir = tempDirWithFiles("my-test", {
* "index.js": `import foo from "./src/foo";`,
* "src": {
* "foo.js": `export default "foo";`,
* },
* });
* ```
*/
export function tempDirWithFiles(
basename: string,
filesOrAbsolutePathToCopyFolderFrom: DirectoryTree | string,
): string {
const base = fs.mkdtempSync(join(fs.realpathSync.native(os.tmpdir()), basename + "_"));
makeTreeSync(base, filesOrAbsolutePathToCopyFolderFrom);
return base;
}
class DisposableString extends String {
[Symbol.dispose]() {
fs.rmSync(this + "", { recursive: true, force: true });
}
[Symbol.asyncDispose]() {
return fs.promises.rm(this + "", { recursive: true, force: true });
}
}
export function tempDir(
basename: string,
filesOrAbsolutePathToCopyFolderFrom: DirectoryTree | string,
): string & DisposableString & AsyncDisposable {
const base = tempDirWithFiles(basename, filesOrAbsolutePathToCopyFolderFrom);
return new DisposableString(base) as string & DisposableString & AsyncDisposable;
}
export function tempDirWithFilesAnon(filesOrAbsolutePathToCopyFolderFrom: DirectoryTree | string): string {
const base = tmpdirSync();
makeTreeSync(base, filesOrAbsolutePathToCopyFolderFrom);
return base;
}
export function bunRun(file: string, env?: Record<string, string> | NodeJS.ProcessEnv, dump = false) {
var path = require("path");
const result = Bun.spawnSync([bunExe(), file], {
cwd: path.dirname(file),
env: {
...bunEnv,
NODE_ENV: undefined,
...env,
},
stdin: "ignore",
stdout: !dump ? "pipe" : "inherit",
stderr: !dump ? "pipe" : "inherit",
});
if (!result.success) {
if (dump) {
throw new Error(
"exited with code " + result.exitCode + (result.signalCode ? `signal: ${result.signalCode}` : ""),
);
}
throw new Error(String(result.stderr) + "\n" + String(result.stdout));
}
return {
stdout: String(result.stdout ?? "").trim(),
stderr: String(result.stderr ?? "").trim(),
};
}
export function bunTest(file: string, env?: Record<string, string>) {
var path = require("path");
const result = Bun.spawnSync([bunExe(), "test", path.basename(file)], {
cwd: path.dirname(file),
env: {
...bunEnv,
NODE_ENV: undefined,
...env,
},
});
if (!result.success) throw new Error(result.stderr.toString("utf8"));
return {
stdout: result.stdout.toString("utf8").trim(),
stderr: result.stderr.toString("utf8").trim(),
};
}
export function bunRunAsScript(
dir: string,
script: string,
env?: Record<string, string | undefined>,
execArgv?: string[],
) {
const result = Bun.spawnSync([bunExe(), ...(execArgv ?? []), `run`, `${script}`], {
cwd: dir,
env: {
...bunEnv,
NODE_ENV: undefined,
...env,
},
});
if (!result.success) throw new Error(result.stderr.toString("utf8"));
return {
stdout: result.stdout.toString("utf8").trim(),
stderr: result.stderr.toString("utf8").trim(),
};
}
export function randomLoneSurrogate() {
const n = numeric.random.between(0, 2, { domain: "integral" });
if (n === 0) return randomLoneHighSurrogate();
return randomLoneLowSurrogate();
}
export function randomInvalidSurrogatePair() {
const low = randomLoneLowSurrogate();
const high = randomLoneHighSurrogate();
return `${low}${high}`;
}
// Generates a random lone high surrogate (from the range D800-DBFF)
export function randomLoneHighSurrogate() {
return String.fromCharCode(numeric.random.between(0xd800, 0xdbff, { domain: "integral" }));
}
// Generates a random lone high surrogate (from the range DC00-DFFF)
export function randomLoneLowSurrogate() {
return String.fromCharCode(numeric.random.between(0xdc00, 0xdfff, { domain: "integral" }));
}
export function runWithError(cb: () => unknown): Error | undefined {
try {
cb();
} catch (e) {
return e as Error;
}
return undefined;
}
export async function runWithErrorPromise(cb: () => unknown): Promise<Error | undefined> {
try {
await cb();
} catch (e) {
return e as Error;
}
return undefined;
}
export function fakeNodeRun(dir: string, file: string | string[], env?: Record<string, string>) {
var path = require("path");
const result = Bun.spawnSync([bunExe(), "--bun", "node", ...(Array.isArray(file) ? file : [file])], {
cwd: dir ?? path.dirname(file),
env: {
...bunEnv,
NODE_ENV: undefined,
...env,
},
});
if (!result.success) throw new Error(result.stderr.toString("utf8"));
return {
stdout: result.stdout.toString("utf8").trim(),
stderr: result.stderr.toString("utf8").trim(),
};
}
export function randomPort(): number {
return 1024 + Math.floor(Math.random() * (65535 - 1024));
}
const binaryTypes = {
"buffer": Buffer,
"arraybuffer": ArrayBuffer,
"uint8array": Uint8Array,
"uint16array": Uint16Array,
"uint32array": Uint32Array,
"int8array": Int8Array,
"int16array": Int16Array,
"int32array": Int32Array,
"float16array": globalThis.Float16Array,
"float32array": Float32Array,
"float64array": Float64Array,
} as const;
if (expect.extend)
expect.extend({
toHaveTestTimedOutAfter(actual: any, expected: number) {
if (typeof actual !== "string") {
return {
pass: false,
message: () => `Expected ${actual} to be a string`,
};
}
const preStartI = actual.indexOf("timed out after ");
if (preStartI === -1) {
return {
pass: false,
message: () => `Expected ${actual} to contain "timed out after "`,
};
}
const startI = preStartI + "timed out after ".length;
const endI = actual.indexOf("ms", startI);
if (endI === -1) {
return {
pass: false,
message: () => `Expected ${actual} to contain "ms" after "timed out after "`,
};
}
const int = parseInt(actual.slice(startI, endI));
if (!Number.isSafeInteger(int)) {
return {
pass: false,
message: () => `Expected ${int} to be a safe integer`,
};
}
return {
pass: int >= expected,
message: () => `Expected ${int} to be >= ${expected}`,
};
},
toBeBinaryType(actual: any, expected: keyof typeof binaryTypes) {
switch (expected) {
case "buffer":
return {
pass: Buffer.isBuffer(actual),
message: () => `Expected ${actual} to be buffer`,
};
case "arraybuffer":
return {
pass: actual instanceof ArrayBuffer,
message: () => `Expected ${actual} to be ArrayBuffer`,
};
default: {
const ctor = binaryTypes[expected];
if (!ctor) {
return {
pass: false,
message: () => `Expected ${expected} to be a binary type`,
};
}
return {
pass: actual instanceof ctor,
message: () => `Expected ${actual} to be ${expected}`,
};
}
}
},
toRun(cmds: string[], optionalStdout?: string, expectedCode: number = 0) {
const result = Bun.spawnSync({
cmd: [bunExe(), ...cmds],
env: bunEnv,
stdio: ["inherit", "pipe", "inherit"],
});
if (result.exitCode !== expectedCode) {
return {
pass: false,
message: () => `Command ${cmds.join(" ")} failed:` + "\n" + result.stdout.toString("utf-8"),
};
}
if (optionalStdout != null) {
return {
pass: result.stdout.toString("utf-8") === optionalStdout,
message: () =>
`Expected ${cmds.join(" ")} to output ${optionalStdout} but got ${result.stdout.toString("utf-8")}`,
};
}
return {
pass: true,
message: () => `Expected ${cmds.join(" ")} to fail`,
};
},
toThrowWithCode(fn: CallableFunction, cls: CallableFunction, code: string) {
try {
fn();
return {
pass: false,
message: () => `Received function did not throw`,
};
} catch (e) {
// expect(e).toBeInstanceOf(cls);
if (!(e instanceof cls)) {
return {
pass: false,
message: () => `Expected error to be instanceof ${cls.name}; got ${e.__proto__.constructor.name}`,
};
}
// expect(e).toHaveProperty("code");
if (!("code" in e)) {
return {
pass: false,
message: () => `Expected error to have property 'code'; got ${e}`,
};
}
// expect(e.code).toEqual(code);
if (e.code !== code) {
return {
pass: false,
message: () => `Expected error to have code '${code}'; got ${e.code}`,
};
}
return {
pass: true,
};
}
},
async toThrowWithCodeAsync(fn: CallableFunction, cls: CallableFunction, code: string) {
try {
await fn();
return {
pass: false,
message: () => `Received function did not throw`,
};
} catch (e) {
// expect(e).toBeInstanceOf(cls);
if (!(e instanceof cls)) {
return {
pass: false,
message: () => `Expected error to be instanceof ${cls.name}; got ${e.__proto__.constructor.name}`,
};
}
// expect(e).toHaveProperty("code");
if (!("code" in e)) {
return {
pass: false,
message: () => `Expected error to have property 'code'; got ${e}`,
};
}
// expect(e.code).toEqual(code);
if (e.code !== code) {
return {
pass: false,
message: () => `Expected error to have code '${code}'; got ${e.code}`,
};
}
return {
pass: true,
};
}
},
toBeLatin1String(actual: unknown) {
if ((actual as string).isLatin1()) {
return {
pass: true,
message: () => `Expected ${actual} to be a Latin1 string`,
};
}
return {
pass: false,
message: () => `Expected ${actual} to be a Latin1 string`,
};
},
toBeUTF16String(actual: unknown) {
if ((actual as string).isUTF16()) {
return {
pass: true,
message: () => `Expected ${actual} to be a UTF16 string`,
};
}
return {
pass: false,
message: () => `Expected ${actual} to be a UTF16 string`,
};
},
});
export function ospath(path: string) {
if (isWindows) {
return path.replace(/\//g, "\\");
}
return path;
}
/**
* Iterates through each tree in the lockfile, checking for each package
* on disk. Also requires each package dependency. Not tested well for
* non-npm packages (links, folders, git dependencies, etc.)
*/
export async function toMatchNodeModulesAt(lockfile: any, root: string) {
function shouldSkip(pkg: any, dep: any): boolean {
// Band-aid as toMatchNodeModulesAt will sometimes ask this function
// if a package depends on itself
if (pkg?.name === dep?.name) return true;
return (
!pkg ||
!pkg.resolution ||
dep.behavior.optional ||
(dep.behavior.dev && pkg.id !== 0) ||
(pkg.arch && pkg.arch !== process.arch)
);
}
for (const { path, dependencies } of lockfile.trees) {
for (const { package_id, id } of Object.values(dependencies) as any[]) {
const treeDep = lockfile.dependencies[id];
const treePkg = lockfile.packages[package_id];
if (shouldSkip(treePkg, treeDep)) continue;
const treeDepPath = join(root, path, treeDep.name);
switch (treePkg.resolution.tag) {
case "npm":
const onDisk = await Bun.file(join(treeDepPath, "package.json")).json();
if (!Bun.deepMatch({ name: treePkg.name, version: treePkg.resolution.value }, onDisk)) {
return {
pass: false,
message: () => `
Expected at ${join(path, treeDep.name)}: ${JSON.stringify({ name: treePkg.name, version: treePkg.resolution.value })}
Received ${JSON.stringify({ name: onDisk.name, version: onDisk.version })}`,
};
}
// Ok, we've confirmed the package exists and has the correct version. Now go through
// each of its transitive dependencies and confirm the same.
for (const depId of treePkg.dependencies) {
const dep = lockfile.dependencies[depId];
const pkg = lockfile.packages[dep.package_id];
if (shouldSkip(pkg, dep)) continue;
try {
const resolved = await Bun.file(Bun.resolveSync(join(dep.name, "package.json"), treeDepPath)).json();
switch (pkg.resolution.tag) {
case "npm":
const name = dep.is_alias ? dep.npm.name : dep.name;
if (!Bun.deepMatch({ name, version: pkg.resolution.value }, resolved)) {
if (dep.literal === "*") {
// allow any version, just needs to be resolvable
continue;
}
if (dep.behavior.peer && dep.npm) {
// allow peer dependencies to not match exactly, but still satisfy
if (Bun.semver.satisfies(pkg.resolution.value, dep.npm.version)) continue;
}
return {
pass: false,
message: () =>
`Expected ${dep.name} to have version ${pkg.resolution.value} in ${treeDepPath}, but got ${resolved.version}`,
};
}
break;
}
} catch (e) {
return {
pass: false,
message: () => `Expected ${dep.name} to be resolvable in ${treeDepPath}`,
};
}
}
break;
default:
if (!fs.existsSync(treeDepPath)) {
return {
pass: false,
message: () => `Expected ${treePkg.resolution.tag} "${treeDepPath}" to exist`,
};
}
for (const depId of treePkg.dependencies) {
const dep = lockfile.dependencies[depId];
const pkg = lockfile.packages[dep.package_id];
if (shouldSkip(pkg, dep)) continue;
try {
const resolved = await Bun.file(Bun.resolveSync(join(dep.name, "package.json"), treeDepPath)).json();
switch (pkg.resolution.tag) {
case "npm":
const name = dep.is_alias ? dep.npm.name : dep.name;
if (!Bun.deepMatch({ name, version: pkg.resolution.value }, resolved)) {
if (dep.literal === "*") {
// allow any version, just needs to be resolvable
continue;
}
// workspaces don't need a version
if (treePkg.resolution.tag === "workspace" && !resolved.version) continue;
if (dep.behavior.peer && dep.npm) {
// allow peer dependencies to not match exactly, but still satisfy
if (Bun.semver.satisfies(pkg.resolution.value, dep.npm.version)) continue;
}
return {
pass: false,
message: () =>
`Expected ${dep.name} to have version ${pkg.resolution.value} in ${treeDepPath}, but got ${resolved.version}`,
};
}
break;
}
} catch (e) {
return {
pass: false,
message: () => `Expected ${dep.name} to be resolvable in ${treeDepPath}`,
};
}
}
break;
}
}
}
return {
pass: true,
};
}
export async function toHaveBins(actual: string[], expectedBins: string[]) {
const message = () => `Expected ${actual} to be package bins ${expectedBins}`;
if (isWindows) {
for (var i = 0; i < actual.length; i += 2) {
if (!actual[i].includes(expectedBins[i / 2]) || !actual[i + 1].includes(expectedBins[i / 2])) {
return { pass: false, message };
}
}
return { pass: true, message };
}
return { pass: actual.every((bin, i) => bin === expectedBins[i]), message };
}
export async function toBeValidBin(actual: string, expectedLinkPath: string) {
const message = () => `Expected ${actual} to be a link to ${expectedLinkPath}`;
if (isWindows) {
const contents = await readFile(actual + ".bunx", "utf16le");
const expected = expectedLinkPath.slice(3);
return { pass: contents.includes(expected), message };
}
return { pass: (await readlink(actual)) === expectedLinkPath, message };
}
export async function toBeWorkspaceLink(actual: string, expectedLinkPath: string) {
const message = () => `Expected ${actual} to be a link to ${expectedLinkPath}`;
if (isWindows) {
if (isAbsolute(actual)) {
// junctions on windows will have an absolute path
return {
pass: actual.includes(expectedLinkPath.split("..").at(-1)!),
message,
};
}
return {
pass: actual === expectedLinkPath,
message,
};
}
const pass = actual === expectedLinkPath;
return { pass, message };
}
export function getMaxFD(): number {
if (isMacOS || isLinux) {
let max = -1;
// https://github.com/python/cpython/commit/e21a7a976a7e3368dc1eba0895e15c47cb06c810
for (let entry of fs.readdirSync(isMacOS ? "/dev/fd" : "/proc/self/fd")) {
const fd = parseInt(entry.trim(), 10);
if (Number.isSafeInteger(fd) && fd >= 0) {
max = Math.max(max, fd);
}
}
if (max >= 0) {
return max;
}
}
const maxFD = openSync("/dev/null", "r");
closeSync(maxFD);
return maxFD;
}
// This is extremely frowned upon but I think it's easier to deal with than
// remembering to do this manually everywhere
declare global {
interface Buffer {
/**
* **INTERNAL USE ONLY, NOT An API IN BUN**
*/
toUnixString(): string;
}
interface String {
/**
* **INTERNAL USE ONLY, NOT An API IN BUN**
*/
isLatin1(): boolean;
/**
* **INTERNAL USE ONLY, NOT An API IN BUN**
*/
isUTF16(): boolean;
}
}
Buffer.prototype.toUnixString = function () {
return this.toString("utf-8").replaceAll("\r\n", "\n");
};
export function dockerExe(): string | null {
return which("docker") || which("podman") || null;
}
export function isDockerEnabled(): boolean {
const dockerCLI = dockerExe();
if (!dockerCLI) {
if (isCI && isLinux) {
throw new Error("A functional `docker` is required in CI for some tests.");
}
return false;
}
// TODO: investigate why Docker tests are not working on Linux arm64
if (isLinux && process.arch === "arm64") {
return false;
}
try {
const info = execSync(`"${dockerCLI}" info`, { stdio: ["ignore", "pipe", "inherit"] });
return info.toString().indexOf("Server Version:") !== -1;
} catch {
if (isCI && isLinux) {
throw new Error("A functional `docker` is required in CI for some tests.");
}
return false;
}
}
export async function waitForPort(port: number, timeout: number = 60_000): Promise<void> {
let deadline = Date.now() + Math.max(1, timeout);
let error: unknown;
while (Date.now() < deadline) {
error = await new Promise(resolve => {
Bun.connect({
hostname: "localhost",
port,
socket: {
data: socket => {
resolve(undefined);
socket.end();
},
end: () => resolve(new Error("Socket closed")),
error: (_, cause) => resolve(new Error("Socket error", { cause })),
connectError: (_, cause) => resolve(new Error("Socket connect error", { cause })),
},
});
});
if (error) {
await Bun.sleep(1000);
} else {
return;
}
}
throw error;
}
export async function describeWithContainer(
label: string,
{
image,
env = {},
args = [],
archs,
concurrent = false,
}: {
image: string;
env?: Record<string, string>;
args?: string[];
archs?: NodeJS.Architecture[];
concurrent?: boolean;
},
fn: (container: { port: number; host: string; ready: Promise<void> }) => void,
) {
// Skip if Docker is not available
if (!isDockerEnabled()) {
describe.todo(label);
return;
}
(concurrent && Bun.version !== "1.2.22" ? describe.concurrent : describe)(label, () => {
// Check if this is one of our docker-compose services
const services: Record<string, number> = {
"postgres_plain": 5432,
"postgres_tls": 5432,
"postgres_auth": 5432,
"mysql_plain": 3306,
"mysql_native_password": 3306,
"mysql_tls": 3306,
"mysql:8": 3306, // Map mysql:8 to mysql_plain
"mysql:9": 3306, // Map mysql:9 to mysql_native_password
"redis_plain": 6379,
"redis_unified": 6379,
"minio": 9000,
"autobahn": 9002,
};
const servicePort = services[image];
if (servicePort) {
// Map mysql:8 and mysql:9 based on environment variables
let actualService = image;
if (image === "mysql:8" || image === "mysql:9") {
if (env.MYSQL_ROOT_PASSWORD === "bun") {
actualService = "mysql_native_password"; // Has password "bun"
} else if (env.MYSQL_ALLOW_EMPTY_PASSWORD === "yes") {
actualService = "mysql_plain"; // No password
} else {
actualService = "mysql_plain"; // Default to no password
}
}
// Create a container descriptor with stable references and a ready promise
let readyResolver: () => void;
let readyRejecter: (error: any) => void;
const readyPromise = new Promise<void>((resolve, reject) => {
readyResolver = resolve;
readyRejecter = reject;
});
// Internal state that will be updated when container is ready
let _host = "127.0.0.1";
let _port = 0;
// Container descriptor with live getters and ready promise
const containerDescriptor = {
get host() {
return _host;
},
get port() {
return _port;
},
ready: readyPromise,
};
// Start the service before any tests
beforeAll(async () => {
try {
const dockerHelper = await import("./docker/index.ts");
const info = await dockerHelper.ensure(actualService as any);
_host = info.host;
_port = info.ports[servicePort];