Repository navigation
Expand file tree
/
Copy pathexpect.zig
More file actions
2273 lines (1916 loc) · 99.6 KB
/
Copy pathexpect.zig
File metadata and controls
2273 lines (1916 loc) · 99.6 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
pub const Counter = struct {
expected: u32 = 0,
actual: u32 = 0,
};
/// Helper to retrieve matcher flags from a jsvalue of a class like ExpectAny, ExpectStringMatching, etc.
pub fn getMatcherFlags(comptime T: type, value: JSValue) Expect.Flags {
if (T.flagsGetCached(value)) |flagsValue| {
if (!flagsValue.isEmpty()) {
return Expect.Flags.fromBitset(flagsValue.toInt32());
}
}
return .{};
}
/// https://jestjs.io/docs/expect
// To support async tests, we need to track the test ID
pub const Expect = struct {
pub const js = jsc.Codegen.JSExpect;
pub const toJS = js.toJS;
pub const fromJS = js.fromJS;
pub const fromJSDirect = js.fromJSDirect;
flags: Flags = .{},
parent: ?*bun.jsc.Jest.bun_test.BunTest.RefData,
custom_label: bun.String = bun.String.empty,
pub const TestScope = struct {
test_id: TestRunner.Test.ID,
describe: *DescribeScope,
};
pub fn incrementExpectCallCounter(this: *Expect) void {
const parent = this.parent orelse return; // not in bun:test
var buntest_strong = parent.bunTest() orelse return; // the test file this expect() call was for is no longer
defer buntest_strong.deinit();
const buntest = buntest_strong.get();
if (parent.phase.sequence(buntest)) |sequence| {
// found active sequence
sequence.expect_call_count +|= 1;
} else {
// in concurrent group or otherwise failed to get the sequence; increment the expect call count in the reporter directly
if (buntest.reporter) |reporter| {
reporter.summary().expectations +|= 1;
}
}
}
pub fn bunTest(this: *Expect) ?bun.jsc.Jest.bun_test.BunTestPtr {
const parent = this.parent orelse return null;
return parent.bunTest();
}
pub const Flags = packed struct(u8) {
// note: keep this struct in sync with C++ implementation (at bindings.cpp)
promise: enum(u2) {
none = 0,
resolves = 1,
rejects = 2,
} = .none,
not: bool = false,
// This was originally padding.
// We don't use all the bits in the u5, so if you need to reuse this elsewhere, you could.
asymmetric_matcher_constructor_type: AsymmetricMatcherConstructorType = .none,
pub const AsymmetricMatcherConstructorType = enum(u5) {
none = 0,
Symbol = 1,
String = 2,
Object = 3,
Array = 4,
BigInt = 5,
Boolean = 6,
Number = 7,
Promise = 8,
InstanceOf = 9,
extern fn AsymmetricMatcherConstructorType__fromJS(globalObject: *JSGlobalObject, value: JSValue) i8;
pub fn fromJS(globalObject: *JSGlobalObject, value: JSValue) bun.JSError!AsymmetricMatcherConstructorType {
const result = AsymmetricMatcherConstructorType__fromJS(globalObject, value);
if (result == -1) return error.JSError;
return @enumFromInt(result);
}
};
pub const FlagsCppType = u8;
comptime {
if (@bitSizeOf(Flags) != @bitSizeOf(FlagsCppType)) @compileError("Flags size is invalid, should match FlagsCppType");
}
pub inline fn encode(this: Flags) FlagsCppType {
return @bitCast(this);
}
pub inline fn decode(bitset: FlagsCppType) Flags {
return @bitCast(bitset);
}
};
pub fn getSignature(comptime matcher_name: string, comptime args: string, comptime not: bool) [:0]const u8 {
const received = "<d>expect(<r><red>received<r><d>).<r>";
comptime if (not) {
return received ++ "not<d>.<r>" ++ matcher_name ++ "<d>(<r>" ++ args ++ "<d>)<r>";
};
return received ++ matcher_name ++ "<d>(<r>" ++ args ++ "<d>)<r>";
}
pub fn throwPrettyMatcherError(globalThis: *JSGlobalObject, custom_label: bun.String, matcher_name: anytype, matcher_params: anytype, flags: Flags, comptime message_fmt: string, message_args: anytype) bun.JSError {
switch (Output.enable_ansi_colors_stderr) {
inline else => |colors| {
const chain = switch (flags.promise) {
.resolves => if (flags.not) Output.prettyFmt("resolves<d>.<r>not<d>.<r>", colors) else Output.prettyFmt("resolves<d>.<r>", colors),
.rejects => if (flags.not) Output.prettyFmt("rejects<d>.<r>not<d>.<r>", colors) else Output.prettyFmt("rejects<d>.<r>", colors),
.none => if (flags.not) Output.prettyFmt("not<d>.<r>", colors) else "",
};
switch (!custom_label.isEmpty()) {
inline else => |use_default_label| {
if (use_default_label) {
const fmt = comptime Output.prettyFmt("<d>expect(<r><red>received<r><d>).<r>" ++ bun.deprecated.autoFormatLabel(@TypeOf(chain)) ++ bun.deprecated.autoFormatLabel(@TypeOf(matcher_name)) ++ "<d>(<r>" ++ bun.deprecated.autoFormatLabel(@TypeOf(matcher_params)) ++ "<d>)<r>\n\n" ++ message_fmt, colors);
return globalThis.throwPretty(fmt, .{ chain, matcher_name, matcher_params } ++ message_args);
} else {
const fmt = comptime Output.prettyFmt("{f}\n\n" ++ message_fmt, colors);
return globalThis.throwPretty(fmt, .{custom_label} ++ message_args);
}
},
}
},
}
}
pub fn getNot(this: *Expect, thisValue: JSValue, _: *JSGlobalObject) JSValue {
this.flags.not = !this.flags.not;
return thisValue;
}
pub fn getResolves(this: *Expect, thisValue: JSValue, globalThis: *JSGlobalObject) bun.JSError!JSValue {
this.flags.promise = switch (this.flags.promise) {
.resolves, .none => .resolves,
.rejects => {
return globalThis.throw("Cannot chain .resolves() after .rejects()", .{});
},
};
return thisValue;
}
pub fn getRejects(this: *Expect, thisValue: JSValue, globalThis: *JSGlobalObject) bun.JSError!JSValue {
this.flags.promise = switch (this.flags.promise) {
.none, .rejects => .rejects,
.resolves => {
return globalThis.throw("Cannot chain .rejects() after .resolves()", .{});
},
};
return thisValue;
}
pub fn getValue(this: *Expect, globalThis: *JSGlobalObject, thisValue: JSValue, matcher_name: string, comptime matcher_params_fmt: string) bun.JSError!JSValue {
const value = js.capturedValueGetCached(thisValue) orelse {
return globalThis.throw("Internal error: the expect(value) was garbage collected but it should not have been!", .{});
};
value.ensureStillAlive();
const matcher_params = switch (Output.enable_ansi_colors_stderr) {
inline else => |colors| comptime Output.prettyFmt(matcher_params_fmt, colors),
};
return processPromise(this.custom_label, this.flags, globalThis, value, matcher_name, matcher_params, false);
}
/// Processes the async flags (resolves/rejects), waiting for the async value if needed.
/// If no flags, returns the original value
/// If either flag is set, waits for the result, and returns either it as a JSValue, or null if the expectation failed (in which case if silent is false, also throws a js exception)
pub fn processPromise(custom_label: bun.String, flags: Expect.Flags, globalThis: *JSGlobalObject, value: JSValue, matcher_name: anytype, matcher_params: anytype, comptime silent: bool) bun.JSError!JSValue {
switch (flags.promise) {
inline .resolves, .rejects => |resolution| {
if (value.asAnyPromise()) |promise| {
const vm = globalThis.vm();
promise.setHandled(vm);
globalThis.bunVM().waitForPromise(promise);
const newValue = promise.result(vm);
switch (promise.status()) {
.fulfilled => switch (resolution) {
.resolves => {},
.rejects => {
if (!silent) {
var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true };
defer formatter.deinit();
const message = "Expected promise that rejects<r>\nReceived promise that resolved: <red>{f}<r>\n";
return throwPrettyMatcherError(globalThis, custom_label, matcher_name, matcher_params, flags, message, .{value.toFmt(&formatter)});
}
return error.JSError;
},
.none => unreachable,
},
.rejected => switch (resolution) {
.rejects => {},
.resolves => {
if (!silent) {
var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true };
defer formatter.deinit();
const message = "Expected promise that resolves<r>\nReceived promise that rejected: <red>{f}<r>\n";
return throwPrettyMatcherError(globalThis, custom_label, matcher_name, matcher_params, flags, message, .{value.toFmt(&formatter)});
}
return error.JSError;
},
.none => unreachable,
},
.pending => unreachable,
}
newValue.ensureStillAlive();
return newValue;
} else {
if (!silent) {
var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true };
defer formatter.deinit();
const message = "Expected promise<r>\nReceived: <red>{f}<r>\n";
return throwPrettyMatcherError(globalThis, custom_label, matcher_name, matcher_params, flags, message, .{value.toFmt(&formatter)});
}
return error.JSError;
}
},
else => {},
}
return value;
}
pub fn isAsymmetricMatcher(value: JSValue) bool {
if (ExpectCustomAsymmetricMatcher.fromJS(value) != null) return true;
if (ExpectAny.fromJS(value) != null) return true;
if (ExpectAnything.fromJS(value) != null) return true;
if (ExpectStringMatching.fromJS(value) != null) return true;
if (ExpectCloseTo.fromJS(value) != null) return true;
if (ExpectObjectContaining.fromJS(value) != null) return true;
if (ExpectStringContaining.fromJS(value) != null) return true;
if (ExpectArrayContaining.fromJS(value) != null) return true;
return false;
}
/// Called by C++ when matching with asymmetric matchers
fn readFlagsAndProcessPromise(instanceValue: JSValue, globalThis: *JSGlobalObject, outFlags: *Expect.Flags.FlagsCppType, value: *JSValue, any_constructor_type: *u8) callconv(.c) bool {
const flags: Expect.Flags = flags: {
if (ExpectCustomAsymmetricMatcher.fromJS(instanceValue)) |instance| {
break :flags instance.flags;
} else if (ExpectAny.fromJS(instanceValue)) |instance| {
any_constructor_type.* = @intFromEnum(instance.flags.asymmetric_matcher_constructor_type);
break :flags instance.flags;
} else if (ExpectAnything.fromJS(instanceValue)) |instance| {
break :flags instance.flags;
} else if (ExpectStringMatching.fromJS(instanceValue)) |instance| {
break :flags instance.flags;
} else if (ExpectCloseTo.fromJS(instanceValue)) |instance| {
break :flags instance.flags;
} else if (ExpectObjectContaining.fromJS(instanceValue)) |instance| {
break :flags instance.flags;
} else if (ExpectStringContaining.fromJS(instanceValue)) |instance| {
break :flags instance.flags;
} else if (ExpectArrayContaining.fromJS(instanceValue)) |instance| {
break :flags instance.flags;
} else {
break :flags Expect.Flags{};
}
};
outFlags.* = flags.encode();
// (note that matcher_name/matcher_args are not used because silent=true)
value.* = processPromise(bun.String.empty, flags, globalThis, value.*, "", "", true) catch return false;
return true;
}
pub fn getSnapshotName(this: *Expect, allocator: std.mem.Allocator, hint: string) ![]const u8 {
const parent = this.parent orelse return error.NoTest;
var buntest_strong = parent.bunTest() orelse return error.TestNotActive;
defer buntest_strong.deinit();
const buntest = buntest_strong.get();
const execution_entry = parent.phase.entry(buntest) orelse return error.SnapshotInConcurrentGroup;
const test_name = execution_entry.base.name orelse "(unnamed)";
var length: usize = 0;
var curr_scope = execution_entry.base.parent;
while (curr_scope) |scope| {
if (scope.base.name != null and scope.base.name.?.len > 0) {
length += scope.base.name.?.len + 1;
}
curr_scope = scope.base.parent;
}
length += test_name.len;
if (hint.len > 0) {
length += hint.len + 2;
}
var buf = try allocator.alloc(u8, length);
var index = buf.len;
if (hint.len > 0) {
index -= hint.len;
bun.copy(u8, buf[index..], hint);
index -= test_name.len + 2;
bun.copy(u8, buf[index..], test_name);
bun.copy(u8, buf[index + test_name.len ..], ": ");
} else {
index -= test_name.len;
bun.copy(u8, buf[index..], test_name);
}
// copy describe scopes in reverse order
curr_scope = execution_entry.base.parent;
while (curr_scope) |scope| {
if (scope.base.name != null and scope.base.name.?.len > 0) {
index -= scope.base.name.?.len + 1;
bun.copy(u8, buf[index..], scope.base.name.?);
buf[index + scope.base.name.?.len] = ' ';
}
curr_scope = scope.base.parent;
}
return buf;
}
pub fn finalize(
this: *Expect,
) callconv(.c) void {
this.custom_label.deref();
if (this.parent) |parent| parent.deref();
VirtualMachine.get().allocator.destroy(this);
}
pub fn call(globalThis: *JSGlobalObject, callframe: *CallFrame) bun.JSError!JSValue {
const arguments = callframe.arguments_old(2).slice();
const value = if (arguments.len < 1) .js_undefined else arguments[0];
var custom_label = bun.String.empty;
if (arguments.len > 1) {
if (arguments[1].isString() or try arguments[1].implementsToString(globalThis)) {
const label = try arguments[1].toBunString(globalThis);
if (globalThis.hasException()) return .zero;
custom_label = label;
}
}
var expect = globalThis.bunVM().allocator.create(Expect) catch {
custom_label.deref();
return globalThis.throwOutOfMemory();
};
const active_execution_entry_ref = if (bun.jsc.Jest.bun_test.cloneActiveStrong()) |buntest_strong_| blk: {
var buntest_strong = buntest_strong_;
defer buntest_strong.deinit();
break :blk bun.jsc.Jest.bun_test.BunTest.ref(buntest_strong, buntest_strong.get().getCurrentStateData());
} else null;
errdefer if (active_execution_entry_ref) |entry_ref| entry_ref.deinit();
expect.* = .{
.custom_label = custom_label,
.parent = active_execution_entry_ref,
};
const expect_js_value = expect.toJS(globalThis);
expect_js_value.ensureStillAlive();
js.capturedValueSetCached(expect_js_value, globalThis, value);
expect_js_value.ensureStillAlive();
expect.postMatch(globalThis);
return expect_js_value;
}
pub fn throw(this: *Expect, globalThis: *JSGlobalObject, comptime signature: [:0]const u8, comptime fmt: [:0]const u8, args: anytype) bun.JSError {
if (this.custom_label.isEmpty()) {
return globalThis.throwPretty(signature ++ fmt, args);
} else {
return globalThis.throwPretty("{f}" ++ fmt, .{this.custom_label} ++ args);
}
}
pub fn constructor(globalThis: *JSGlobalObject, _: *CallFrame) bun.JSError!*Expect {
return globalThis.throw("expect() cannot be called with new", .{});
}
// pass here has a leading underscore to avoid name collision with the pass variable in other functions
pub fn _pass(
this: *Expect,
globalThis: *JSGlobalObject,
callFrame: *CallFrame,
) bun.JSError!JSValue {
defer this.postMatch(globalThis);
const arguments_ = callFrame.arguments_old(1);
const arguments = arguments_.slice();
var _msg: ZigString = ZigString.Empty;
if (arguments.len > 0) {
const value = arguments[0];
value.ensureStillAlive();
if (!value.isString()) {
return globalThis.throwInvalidArgumentType("pass", "message", "string");
}
try value.toZigString(&_msg, globalThis);
} else {
_msg = ZigString.fromBytes("passes by .pass() assertion");
}
this.incrementExpectCallCounter();
const not = this.flags.not;
var pass = true;
if (not) pass = !pass;
if (pass) return .js_undefined;
var msg = _msg.toSlice(default_allocator);
defer msg.deinit();
if (not) {
const signature = comptime getSignature("pass", "", true);
return this.throw(globalThis, signature, "\n\n{s}\n", .{msg.slice()});
}
// should never reach here
return .zero;
}
pub fn fail(
this: *Expect,
globalThis: *JSGlobalObject,
callFrame: *CallFrame,
) bun.JSError!JSValue {
defer this.postMatch(globalThis);
const arguments_ = callFrame.arguments_old(1);
const arguments = arguments_.slice();
var _msg: ZigString = ZigString.Empty;
if (arguments.len > 0) {
const value = arguments[0];
value.ensureStillAlive();
if (!value.isString()) {
return globalThis.throwInvalidArgumentType("fail", "message", "string");
}
try value.toZigString(&_msg, globalThis);
} else {
_msg = ZigString.fromBytes("fails by .fail() assertion");
}
this.incrementExpectCallCounter();
const not = this.flags.not;
var pass = false;
if (not) pass = !pass;
if (pass) return .js_undefined;
var msg = _msg.toSlice(default_allocator);
defer msg.deinit();
const signature = comptime getSignature("fail", "", true);
return this.throw(globalThis, signature, "\n\n{s}\n", .{msg.slice()});
}
pub const toBe = @import("./expect/toBe.zig").toBe;
pub const toBeArray = @import("./expect/toBeArray.zig").toBeArray;
pub const toBeArrayOfSize = @import("./expect/toBeArrayOfSize.zig").toBeArrayOfSize;
pub const toBeBoolean = @import("./expect/toBeBoolean.zig").toBeBoolean;
pub const toBeCloseTo = @import("./expect/toBeCloseTo.zig").toBeCloseTo;
pub const toBeDate = @import("./expect/toBeDate.zig").toBeDate;
pub const toBeDefined = @import("./expect/toBeDefined.zig").toBeDefined;
pub const toBeEmpty = @import("./expect/toBeEmpty.zig").toBeEmpty;
pub const toBeEmptyObject = @import("./expect/toBeEmptyObject.zig").toBeEmptyObject;
pub const toBeEven = @import("./expect/toBeEven.zig").toBeEven;
pub const toBeFalse = @import("./expect/toBeFalse.zig").toBeFalse;
pub const toBeFalsy = @import("./expect/toBeFalsy.zig").toBeFalsy;
pub const toBeFinite = @import("./expect/toBeFinite.zig").toBeFinite;
pub const toBeFunction = @import("./expect/toBeFunction.zig").toBeFunction;
pub const toBeGreaterThan = @import("./expect/toBeGreaterThan.zig").toBeGreaterThan;
pub const toBeGreaterThanOrEqual = @import("./expect/toBeGreaterThanOrEqual.zig").toBeGreaterThanOrEqual;
pub const toBeInstanceOf = @import("./expect/toBeInstanceOf.zig").toBeInstanceOf;
pub const toBeInteger = @import("./expect/toBeInteger.zig").toBeInteger;
pub const toBeLessThan = @import("./expect/toBeLessThan.zig").toBeLessThan;
pub const toBeLessThanOrEqual = @import("./expect/toBeLessThanOrEqual.zig").toBeLessThanOrEqual;
pub const toBeNaN = @import("./expect/toBeNaN.zig").toBeNaN;
pub const toBeNegative = @import("./expect/toBeNegative.zig").toBeNegative;
pub const toBeNil = @import("./expect/toBeNil.zig").toBeNil;
pub const toBeNull = @import("./expect/toBeNull.zig").toBeNull;
pub const toBeNumber = @import("./expect/toBeNumber.zig").toBeNumber;
pub const toBeObject = @import("./expect/toBeObject.zig").toBeObject;
pub const toBeOdd = @import("./expect/toBeOdd.zig").toBeOdd;
pub const toBeOneOf = @import("./expect/toBeOneOf.zig").toBeOneOf;
pub const toBePositive = @import("./expect/toBePositive.zig").toBePositive;
pub const toBeString = @import("./expect/toBeString.zig").toBeString;
pub const toBeSymbol = @import("./expect/toBeSymbol.zig").toBeSymbol;
pub const toBeTrue = @import("./expect/toBeTrue.zig").toBeTrue;
pub const toBeTruthy = @import("./expect/toBeTruthy.zig").toBeTruthy;
pub const toBeTypeOf = @import("./expect/toBeTypeOf.zig").toBeTypeOf;
pub const toBeUndefined = @import("./expect/toBeUndefined.zig").toBeUndefined;
pub const toBeValidDate = @import("./expect/toBeValidDate.zig").toBeValidDate;
pub const toBeWithin = @import("./expect/toBeWithin.zig").toBeWithin;
pub const toContain = @import("./expect/toContain.zig").toContain;
pub const toContainAllKeys = @import("./expect/toContainAllKeys.zig").toContainAllKeys;
pub const toContainAllValues = @import("./expect/toContainAllValues.zig").toContainAllValues;
pub const toContainAnyKeys = @import("./expect/toContainAnyKeys.zig").toContainAnyKeys;
pub const toContainAnyValues = @import("./expect/toContainAnyValues.zig").toContainAnyValues;
pub const toContainEqual = @import("./expect/toContainEqual.zig").toContainEqual;
pub const toContainKey = @import("./expect/toContainKey.zig").toContainKey;
pub const toContainKeys = @import("./expect/toContainKeys.zig").toContainKeys;
pub const toContainValue = @import("./expect/toContainValue.zig").toContainValue;
pub const toContainValues = @import("./expect/toContainValues.zig").toContainValues;
pub const toEndWith = @import("./expect/toEndWith.zig").toEndWith;
pub const toEqual = @import("./expect/toEqual.zig").toEqual;
pub const toEqualIgnoringWhitespace = @import("./expect/toEqualIgnoringWhitespace.zig").toEqualIgnoringWhitespace;
pub const toHaveBeenCalled = @import("./expect/toHaveBeenCalled.zig").toHaveBeenCalled;
pub const toHaveBeenCalledOnce = @import("./expect/toHaveBeenCalledOnce.zig").toHaveBeenCalledOnce;
pub const toHaveBeenCalledTimes = @import("./expect/toHaveBeenCalledTimes.zig").toHaveBeenCalledTimes;
pub const toHaveBeenCalledWith = @import("./expect/toHaveBeenCalledWith.zig").toHaveBeenCalledWith;
pub const toHaveBeenLastCalledWith = @import("./expect/toHaveBeenLastCalledWith.zig").toHaveBeenLastCalledWith;
pub const toHaveBeenNthCalledWith = @import("./expect/toHaveBeenNthCalledWith.zig").toHaveBeenNthCalledWith;
pub const toHaveLastReturnedWith = @import("./expect/toHaveLastReturnedWith.zig").toHaveLastReturnedWith;
pub const toHaveLength = @import("./expect/toHaveLength.zig").toHaveLength;
pub const toHaveNthReturnedWith = @import("./expect/toHaveNthReturnedWith.zig").toHaveNthReturnedWith;
pub const toHaveProperty = @import("./expect/toHaveProperty.zig").toHaveProperty;
pub const toHaveReturned = @import("./expect/toHaveReturned.zig").toHaveReturned;
pub const toHaveReturnedTimes = @import("./expect/toHaveReturnedTimes.zig").toHaveReturnedTimes;
pub const toHaveReturnedWith = @import("./expect/toHaveReturnedWith.zig").toHaveReturnedWith;
pub const toInclude = @import("./expect/toInclude.zig").toInclude;
pub const toIncludeRepeated = @import("./expect/toIncludeRepeated.zig").toIncludeRepeated;
pub const toMatch = @import("./expect/toMatch.zig").toMatch;
pub const toMatchInlineSnapshot = @import("./expect/toMatchInlineSnapshot.zig").toMatchInlineSnapshot;
pub const toMatchObject = @import("./expect/toMatchObject.zig").toMatchObject;
pub const toMatchSnapshot = @import("./expect/toMatchSnapshot.zig").toMatchSnapshot;
pub const toSatisfy = @import("./expect/toSatisfy.zig").toSatisfy;
pub const toStartWith = @import("./expect/toStartWith.zig").toStartWith;
pub const toStrictEqual = @import("./expect/toStrictEqual.zig").toStrictEqual;
pub const toThrow = @import("./expect/toThrow.zig").toThrow;
pub const toThrowErrorMatchingInlineSnapshot = @import("./expect/toThrowErrorMatchingInlineSnapshot.zig").toThrowErrorMatchingInlineSnapshot;
pub const toThrowErrorMatchingSnapshot = @import("./expect/toThrowErrorMatchingSnapshot.zig").toThrowErrorMatchingSnapshot;
pub fn getValueAsToThrow(this: *Expect, globalThis: *JSGlobalObject, value: JSValue) bun.JSError!struct { ?JSValue, JSValue } {
const vm = globalThis.bunVM();
var return_value_from_function: JSValue = .zero;
if (!value.jsType().isFunction()) {
if (this.flags.promise != .none) {
return .{ value, return_value_from_function };
}
return globalThis.throw("Expected value must be a function", .{});
}
var return_value: JSValue = .zero;
// Drain existing unhandled rejections
vm.global.handleRejectedPromises();
var scope = vm.unhandledRejectionScope();
const prev_unhandled_pending_rejection_to_capture = vm.unhandled_pending_rejection_to_capture;
vm.unhandled_pending_rejection_to_capture = &return_value;
vm.onUnhandledRejection = &VirtualMachine.onQuietUnhandledRejectionHandlerCaptureValue;
return_value_from_function = value.call(globalThis, .js_undefined, &.{}) catch |err| globalThis.takeException(err);
vm.unhandled_pending_rejection_to_capture = prev_unhandled_pending_rejection_to_capture;
vm.global.handleRejectedPromises();
if (return_value == .zero) {
return_value = return_value_from_function;
}
if (return_value.asAnyPromise()) |promise| {
vm.waitForPromise(promise);
scope.apply(vm);
switch (promise.unwrap(globalThis.vm(), .mark_handled)) {
.fulfilled => {
return .{ null, return_value_from_function };
},
.rejected => |rejected| {
// since we know for sure it rejected, we should always return the error
return .{ rejected.toError() orelse rejected, return_value_from_function };
},
.pending => unreachable,
}
}
if (return_value != return_value_from_function) {
if (return_value_from_function.asAnyPromise()) |existing| {
existing.setHandled(globalThis.vm());
}
}
scope.apply(vm);
return .{ return_value.toError() orelse return_value_from_function.toError(), return_value_from_function };
}
pub fn fnToErrStringOrUndefined(this: *Expect, globalThis: *JSGlobalObject, value: JSValue) !?JSValue {
const err_value, _ = try this.getValueAsToThrow(globalThis, value);
var err_value_res = err_value orelse return null;
if (err_value_res.isAnyError()) {
const message: JSValue = try err_value_res.getTruthyComptime(globalThis, "message") orelse .js_undefined;
err_value_res = message;
} else {
err_value_res = .js_undefined;
}
return err_value_res;
}
const TrimResult = struct { trimmed: []const u8, start_indent: ?[]const u8, end_indent: ?[]const u8 };
pub fn trimLeadingWhitespaceForInlineSnapshot(str_in: []const u8, trimmed_buf: []u8) TrimResult {
std.debug.assert(trimmed_buf.len == str_in.len);
var src = str_in;
var dst = trimmed_buf[0..];
const give_up_1: TrimResult = .{ .trimmed = str_in, .start_indent = null, .end_indent = null };
// if the line is all whitespace, trim fully
// the first line containing a character determines the max trim count
// read first line (should be all-whitespace)
const first_newline = std.mem.indexOf(u8, src, "\n") orelse return give_up_1;
for (src[0..first_newline]) |char| if (char != ' ' and char != '\t') return give_up_1;
src = src[first_newline + 1 ..];
// read first real line and get indent
const indent_len = for (src, 0..) |char, i| {
if (char != ' ' and char != '\t') break i;
} else src.len;
const indent_str = src[0..indent_len];
const give_up_2: TrimResult = .{ .trimmed = str_in, .start_indent = indent_str, .end_indent = indent_str };
if (indent_len == 0) return give_up_2; // no indent to trim; save time
// we're committed now
dst[0] = '\n';
dst = dst[1..];
src = src[indent_len..];
const second_newline = (std.mem.indexOf(u8, src, "\n") orelse return give_up_2) + 1;
@memcpy(dst[0..second_newline], src[0..second_newline]);
src = src[second_newline..];
dst = dst[second_newline..];
while (src.len > 0) {
// try read indent
const max_indent_len = @min(src.len, indent_len);
const line_indent_len = for (src[0..max_indent_len], 0..) |char, i| {
if (char != ' ' and char != '\t') break i;
} else max_indent_len;
src = src[line_indent_len..];
if (line_indent_len < max_indent_len) {
if (src.len == 0) {
// perfect; done
break;
}
if (src[0] == '\n') {
// this line has less indentation than the first line, but it's empty so that's okay.
dst[0] = '\n';
src = src[1..];
dst = dst[1..];
continue;
}
// this line had less indentation than the first line, but wasn't empty. give up.
return give_up_2;
} else {
// this line has the same or more indentation than the first line. copy it.
const line_newline = (std.mem.indexOf(u8, src, "\n") orelse {
// this is the last line. if it's not all whitespace, give up
for (src) |char| {
if (char != ' ' and char != '\t') return give_up_2;
}
break;
}) + 1;
@memcpy(dst[0..line_newline], src[0..line_newline]);
src = src[line_newline..];
dst = dst[line_newline..];
}
}
const end_indent = if (std.mem.lastIndexOfScalar(u8, str_in, '\n')) |c| c + 1 else return give_up_2; // there has to have been at least a single newline to get here
for (str_in[end_indent..]) |c| if (c != ' ' and c != '\t') return give_up_2; // we already checked, but the last line is not all whitespace again
// done
return .{ .trimmed = trimmed_buf[0 .. trimmed_buf.len - dst.len], .start_indent = indent_str, .end_indent = str_in[end_indent..] };
}
pub fn inlineSnapshot(
this: *Expect,
globalThis: *JSGlobalObject,
callFrame: *CallFrame,
value: JSValue,
property_matchers: ?JSValue,
result: ?[]const u8,
comptime fn_name: []const u8,
) bun.JSError!JSValue {
// jest counts inline snapshots towards the snapshot counter for some reason
const runner = Jest.runner orelse {
const signature = comptime getSignature(fn_name, "", false);
return this.throw(globalThis, signature, "\n\n<b>Matcher error<r>: Snapshot matchers cannot be used outside of a test\n", .{});
};
_ = runner.snapshots.addCount(this, "") catch |e| switch (e) {
error.OutOfMemory => return error.OutOfMemory,
error.NoTest => {},
error.SnapshotInConcurrentGroup => {},
error.TestNotActive => {},
};
const update = runner.snapshots.update_snapshots;
var needs_write = false;
var pretty_value = std.Io.Writer.Allocating.init(default_allocator);
defer pretty_value.deinit();
try this.matchAndFmtSnapshot(globalThis, value, property_matchers, &pretty_value.writer, fn_name);
var start_indent: ?[]const u8 = null;
var end_indent: ?[]const u8 = null;
if (result) |saved_value| {
const buf = try runner.snapshots.allocator.alloc(u8, saved_value.len);
defer runner.snapshots.allocator.free(buf);
const trim_res = trimLeadingWhitespaceForInlineSnapshot(saved_value, buf);
if (strings.eqlLong(pretty_value.written(), trim_res.trimmed, true)) {
runner.snapshots.passed += 1;
return .js_undefined;
} else if (update) {
runner.snapshots.passed += 1;
needs_write = true;
start_indent = trim_res.start_indent;
end_indent = trim_res.end_indent;
} else {
runner.snapshots.failed += 1;
const signature = comptime getSignature(fn_name, "<green>expected<r>", false);
const fmt = signature ++ "\n\n{f}\n";
const diff_format = DiffFormatter{
.received_string = pretty_value.written(),
.expected_string = trim_res.trimmed,
.globalThis = globalThis,
};
return globalThis.throwPretty(fmt, .{diff_format});
}
} else {
needs_write = true;
}
if (needs_write) {
if (bun.ci.isCI()) {
if (!update) {
const signature = comptime getSignature(fn_name, "", false);
// Only creating new snapshots can reach here (updating with mismatches errors earlier with diff)
return this.throw(globalThis, signature, "\n\n<b>Matcher error<r>: Inline snapshot creation is disabled in CI environments unless --update-snapshots is used.\nTo override, set the environment variable CI=false.\n\nReceived: {s}", .{pretty_value.written()});
}
}
var buntest_strong = this.bunTest() orelse {
const signature = comptime getSignature(fn_name, "", false);
return this.throw(globalThis, signature, "\n\n<b>Matcher error<r>: Snapshot matchers cannot be used outside of a test\n", .{});
};
defer buntest_strong.deinit();
const buntest = buntest_strong.get();
// 1. find the src loc of the snapshot
const srcloc = callFrame.getCallerSrcLoc(globalThis);
defer srcloc.str.deref();
const file_id = buntest.file_id;
const fget = runner.files.get(file_id);
if (!srcloc.str.eqlUTF8(fget.source.path.text)) {
const signature = comptime getSignature(fn_name, "", false);
return this.throw(globalThis, signature,
\\
\\
\\<b>Matcher error<r>: Inline snapshot matchers must be called from the test file:
\\ Expected to be called from file: <green>"{f}"<r>
\\ {s} called from file: <red>"{f}"<r>
\\
, .{
std.zig.fmtString(fget.source.path.text),
fn_name,
std.zig.fmtString(srcloc.str.toUTF8(runner.snapshots.allocator).slice()),
});
}
// 2. save to write later
try runner.snapshots.addInlineSnapshotToWrite(file_id, .{
.line = srcloc.line,
.col = srcloc.column,
.value = try pretty_value.toOwnedSlice(),
.has_matchers = property_matchers != null,
.is_added = result == null,
.kind = fn_name,
.start_indent = if (start_indent) |ind| try runner.snapshots.allocator.dupe(u8, ind) else null,
.end_indent = if (end_indent) |ind| try runner.snapshots.allocator.dupe(u8, ind) else null,
});
}
return .js_undefined;
}
pub fn matchAndFmtSnapshot(this: *Expect, globalThis: *JSGlobalObject, value: JSValue, property_matchers: ?JSValue, pretty_value: *std.Io.Writer, comptime fn_name: []const u8) bun.JSError!void {
if (property_matchers) |_prop_matchers| {
if (!value.isObject()) {
const signature = comptime getSignature(fn_name, "<green>properties<r><d>, <r>hint", false);
return this.throw(globalThis, signature, "\n\n<b>Matcher error: <red>received<r> values must be an object when the matcher has <green>properties<r>\n", .{});
}
const prop_matchers = _prop_matchers;
if (!try value.jestDeepMatch(prop_matchers, globalThis, true)) {
// TODO: print diff with properties from propertyMatchers
const signature = comptime getSignature(fn_name, "<green>propertyMatchers<r>", false);
const fmt = signature ++ "\n\nExpected <green>propertyMatchers<r> to match properties from received object" ++
"\n\nReceived: {f}\n";
var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis };
defer formatter.deinit();
return globalThis.throwPretty(fmt, .{value.toFmt(&formatter)});
}
}
value.jestSnapshotPrettyFormat(pretty_value, globalThis) catch {
var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis };
defer formatter.deinit();
return globalThis.throw("Failed to pretty format value: {f}", .{value.toFmt(&formatter)});
};
}
pub fn snapshot(this: *Expect, globalThis: *JSGlobalObject, value: JSValue, property_matchers: ?JSValue, hint: []const u8, comptime fn_name: []const u8) bun.JSError!JSValue {
var pretty_value = std.Io.Writer.Allocating.init(default_allocator);
defer pretty_value.deinit();
try this.matchAndFmtSnapshot(globalThis, value, property_matchers, &pretty_value.writer, fn_name);
const existing_value = Jest.runner.?.snapshots.getOrPut(this, pretty_value.written(), hint) catch |err| {
var buntest_strong = this.bunTest() orelse return globalThis.throw("Snapshot matchers cannot be used outside of a test", .{});
defer buntest_strong.deinit();
const buntest = buntest_strong.get();
const test_file_path = Jest.runner.?.files.get(buntest.file_id).source.path.text;
const runner = Jest.runner.?;
return switch (err) {
error.FailedToOpenSnapshotFile => globalThis.throw("Failed to open snapshot file for test file: {s}", .{test_file_path}),
error.FailedToMakeSnapshotDirectory => globalThis.throw("Failed to make snapshot directory for test file: {s}", .{test_file_path}),
error.FailedToWriteSnapshotFile => globalThis.throw("Failed write to snapshot file: {s}", .{test_file_path}),
error.SyntaxError, error.ParseError => globalThis.throw("Failed to parse snapshot file for: {s}", .{test_file_path}),
error.SnapshotCreationNotAllowedInCI => blk: {
const snapshot_name = runner.snapshots.last_error_snapshot_name;
defer if (snapshot_name) |name| {
runner.snapshots.allocator.free(name);
runner.snapshots.last_error_snapshot_name = null;
};
if (snapshot_name) |name| {
break :blk globalThis.throw("Snapshot creation is disabled in CI environments unless --update-snapshots is used\nTo override, set the environment variable CI=false.\n\nSnapshot name: \"{s}\"\nReceived: {s}", .{ name, pretty_value.written() });
} else {
break :blk globalThis.throw("Snapshot creation is disabled in CI environments unless --update-snapshots is used\nTo override, set the environment variable CI=false.\n\nReceived: {s}", .{pretty_value.written()});
}
},
error.SnapshotInConcurrentGroup => globalThis.throw("Snapshot matchers are not supported in concurrent tests", .{}),
error.TestNotActive => globalThis.throw("Snapshot matchers are not supported after the test has finished executing", .{}),
else => blk: {
var formatter = jsc.ConsoleObject.Formatter{ .globalThis = globalThis };
defer formatter.deinit();
break :blk globalThis.throw("Failed to snapshot value: {f}", .{value.toFmt(&formatter)});
},
};
};
if (existing_value) |saved_value| {
if (strings.eqlLong(pretty_value.written(), saved_value, true)) {
Jest.runner.?.snapshots.passed += 1;
return .js_undefined;
}
Jest.runner.?.snapshots.failed += 1;
const signature = comptime getSignature(fn_name, "<green>expected<r>", false);
const fmt = signature ++ "\n\n{f}\n";
const diff_format = DiffFormatter{
.received_string = pretty_value.written(),
.expected_string = saved_value,
.globalThis = globalThis,
};
return globalThis.throwPretty(fmt, .{diff_format});
}
return .js_undefined;
}
pub fn getStaticNot(globalThis: *JSGlobalObject, _: JSValue, _: JSValue) bun.JSError!JSValue {
return ExpectStatic.create(globalThis, .{ .not = true });
}
pub fn getStaticResolvesTo(globalThis: *JSGlobalObject, _: JSValue, _: JSValue) bun.JSError!JSValue {
return ExpectStatic.create(globalThis, .{ .promise = .resolves });
}
pub fn getStaticRejectsTo(globalThis: *JSGlobalObject, _: JSValue, _: JSValue) bun.JSError!JSValue {
return ExpectStatic.create(globalThis, .{ .promise = .rejects });
}
pub fn any(globalThis: *JSGlobalObject, callFrame: *CallFrame) bun.JSError!JSValue {
return ExpectAny.call(globalThis, callFrame);
}
pub fn anything(globalThis: *JSGlobalObject, callFrame: *CallFrame) bun.JSError!JSValue {
return ExpectAnything.call(globalThis, callFrame);
}
pub fn closeTo(globalThis: *JSGlobalObject, callFrame: *CallFrame) bun.JSError!JSValue {
return ExpectCloseTo.call(globalThis, callFrame);
}
pub fn objectContaining(globalThis: *JSGlobalObject, callFrame: *CallFrame) bun.JSError!JSValue {
return ExpectObjectContaining.call(globalThis, callFrame);
}
pub fn stringContaining(globalThis: *JSGlobalObject, callFrame: *CallFrame) bun.JSError!JSValue {
return ExpectStringContaining.call(globalThis, callFrame);
}
pub fn stringMatching(globalThis: *JSGlobalObject, callFrame: *CallFrame) bun.JSError!JSValue {
return ExpectStringMatching.call(globalThis, callFrame);
}
pub fn arrayContaining(globalThis: *JSGlobalObject, callFrame: *CallFrame) bun.JSError!JSValue {
return ExpectArrayContaining.call(globalThis, callFrame);
}
/// Implements `expect.extend({ ... })`
pub fn extend(globalThis: *JSGlobalObject, callFrame: *CallFrame) bun.JSError!JSValue {
const args = callFrame.arguments_old(1).slice();
if (args.len == 0 or !args[0].isObject()) {
return globalThis.throwPretty("<d>expect.<r>extend<d>(<r>matchers<d>)<r>\n\nExpected an object containing matchers\n", .{});
}
var expect_proto = Expect__getPrototype(globalThis);
var expect_constructor = Expect.js.getConstructor(globalThis);
var expect_static_proto = ExpectStatic__getPrototype(globalThis);
// SAFETY: already checked that args[0] is an object
const matchers_to_register = args[0].getObject().?;
{
var iter = try jsc.JSPropertyIterator(.{
.skip_empty_name = false,
.include_value = true,
.own_properties_only = false,
}).init(globalThis, matchers_to_register);
defer iter.deinit();
while (try iter.next()) |*matcher_name| {
const matcher_fn: JSValue = iter.value;
if (!matcher_fn.jsType().isFunction()) {
const type_name = if (matcher_fn.isNull()) bun.String.static("null") else bun.String.init(matcher_fn.jsTypeString(globalThis).getZigString(globalThis));
return globalThis.throwInvalidArguments("expect.extend: `{f}` is not a valid matcher. Must be a function, is \"{f}\"", .{ matcher_name, type_name });
}
// Mutate the Expect/ExpectStatic prototypes/constructor with new instances of JSCustomExpectMatcherFunction.
// Even though they point to the same native functions for all matchers,
// multiple instances are created because each instance will hold the matcher_fn as a property
const wrapper_fn = Bun__JSWrappingFunction__create(globalThis, matcher_name, jsc.toJSHostFn(Expect.applyCustomMatcher), matcher_fn, true);
expect_proto.put(globalThis, matcher_name, wrapper_fn);
expect_constructor.put(globalThis, matcher_name, wrapper_fn);
expect_static_proto.put(globalThis, matcher_name, wrapper_fn);
}
}
globalThis.bunVM().autoGarbageCollect();
return .js_undefined;
}
const CustomMatcherParamsFormatter = struct {
colors: bool,
globalThis: *JSGlobalObject,
matcher_fn: JSValue,
pub fn format(this: CustomMatcherParamsFormatter, writer: *std.Io.Writer) !void {
// try to detect param names from matcher_fn (user function) source code
if (jsc.JSFunction.getSourceCode(this.matcher_fn)) |source_str| {
const source_slice = source_str.toUTF8(this.globalThis.allocator());
defer source_slice.deinit();
var source: string = source_slice.slice();
if (std.mem.indexOfScalar(u8, source, '(')) |lparen| {
if (std.mem.indexOfScalarPos(u8, source, lparen, ')')) |rparen| {
const params_str = source[(lparen + 1)..rparen];
var param_index: usize = 0;
var iter = std.mem.splitScalar(u8, params_str, ',');
while (iter.next()) |param_name| : (param_index += 1) {
if (param_index > 0) { // skip the first param from the matcher_fn, which is the received value
if (param_index > 1) {
try writer.writeAll(if (this.colors) Output.prettyFmt("<r><d>, <r><green>", true) else ", ");
} else if (this.colors) {
try writer.writeAll("<green>");
}
const param_name_trimmed = std.mem.trim(u8, param_name, " ");
if (param_name_trimmed.len > 0) {
try writer.writeAll(param_name_trimmed);
} else {
try writer.print("arg{d}", .{param_index - 1});
}