forked from PerryTS/perry
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.rs
More file actions
1719 lines (1594 loc) · 55.8 KB
/
Copy pathtest.rs
File metadata and controls
1719 lines (1594 loc) · 55.8 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
//! Minimal `node:test` and `node:test/reporters` runtime surface.
//!
//! The implementation focuses on Perry's parity fixtures: import shapes,
//! snapshot comparison helpers, mock timer control, and deterministic reporter
//! formatting for synthetic events.
use std::cell::{Cell, RefCell};
use std::fs;
use crate::closure::{
js_closure_alloc, js_closure_call0, js_closure_call1, js_closure_get_capture_f64,
js_closure_get_capture_ptr, js_closure_set_capture_f64, js_closure_set_capture_ptr,
js_register_closure_arity, js_register_closure_rest, ClosureHeader,
};
use crate::object::{js_object_alloc, js_object_set_field_by_name};
use crate::string::js_string_from_bytes;
use crate::value::{JSValue, POINTER_MASK, TAG_UNDEFINED};
#[path = "test_mock_options.rs"]
mod mock_options;
#[path = "test_property.rs"]
mod property_mock;
#[path = "test_reporters.rs"]
mod reporters;
#[path = "test_runner.rs"]
pub(crate) mod runner;
#[path = "test_snapshot.rs"]
mod snapshot;
// Re-exported / imported so the pre-split `test::<item>` paths keep resolving.
use mock_options::{mock_option_times, parse_mock_fn_options};
pub(crate) use reporters::{
thunk_reporter_dot, thunk_reporter_junit, thunk_reporter_lcov, thunk_reporter_spec,
thunk_reporter_tap,
};
pub(crate) use runner::{
thunk_test, thunk_test_after, thunk_test_after_each, thunk_test_before, thunk_test_before_each,
thunk_test_only, thunk_test_run, thunk_test_skip, thunk_test_suite, thunk_test_suite_only,
thunk_test_suite_skip, thunk_test_suite_todo, thunk_test_todo,
};
use snapshot::{
assert_file_snapshot, assert_snapshot, snapshot_object_value, snapshot_set_default_serializers,
snapshot_set_resolve_snapshot_path,
};
const REPORTER_SPEC: i32 = 0;
const REPORTER_TAP: i32 = 1;
const REPORTER_DOT: i32 = 2;
const REPORTER_JUNIT: i32 = 3;
const REPORTER_LCOV: i32 = 4;
const TEST_OVERRIDE_NONE: i8 = 0;
const TEST_OVERRIDE_SKIP: i8 = 1;
const TEST_OVERRIDE_TODO: i8 = 2;
thread_local! {
static MOCK_OBJECT: RefCell<Option<*mut crate::object::ObjectHeader>> = const { RefCell::new(None) };
static SNAPSHOT_OBJECT: RefCell<Option<*mut crate::object::ObjectHeader>> = const { RefCell::new(None) };
static SNAPSHOT_RESOLVER: Cell<f64> = const { Cell::new(f64::from_bits(TAG_UNDEFINED)) };
static CURRENT_TEST_NAME: RefCell<Option<String>> = const { RefCell::new(None) };
static CURRENT_DIAGNOSTICS: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
static CURRENT_SNAPSHOT_INDEX: Cell<u32> = const { Cell::new(0) };
static CURRENT_ASSERT_COUNT: Cell<u32> = const { Cell::new(0) };
static CURRENT_PLAN: Cell<Option<u32>> = const { Cell::new(None) };
static CURRENT_TEST_OVERRIDE: Cell<i8> = const { Cell::new(TEST_OVERRIDE_NONE) };
static NEXT_MOCK_ID: Cell<i64> = const { Cell::new(1) };
static MOCK_STATES: RefCell<Vec<MockState>> = const { RefCell::new(Vec::new()) };
}
fn undefined_value() -> f64 {
f64::from_bits(TAG_UNDEFINED)
}
fn is_undefined_value(value: f64) -> bool {
JSValue::from_bits(value.to_bits()).is_undefined()
}
fn boxed_ptr<T>(ptr: *const T) -> f64 {
f64::from_bits(JSValue::pointer(ptr as *const u8).bits())
}
fn string_value(value: &str) -> f64 {
let ptr = js_string_from_bytes(value.as_ptr(), value.len() as u32);
f64::from_bits(JSValue::string_ptr(ptr).bits())
}
fn set_field(obj: *mut crate::object::ObjectHeader, name: &str, value: f64) {
let key = js_string_from_bytes(name.as_ptr(), name.len() as u32);
js_object_set_field_by_name(obj, key, value);
}
fn make_closure(func: *const u8, arity: u32, captures: u32) -> *mut crate::closure::ClosureHeader {
js_register_closure_arity(func, arity);
let closure = js_closure_alloc(func, captures);
// Optimized Windows links may fold identical COMDAT function bodies, so
// the function-pointer registry is not a stable identity for reflective
// metadata. Pin the requested arity to this closure instance as well.
crate::object::set_builtin_closure_length(closure as usize, arity);
closure
}
fn closure_value(func: *const u8, arity: u32) -> f64 {
boxed_ptr(make_closure(func, arity, 0))
}
fn closure_value_with_id(func: *const u8, arity: u32, id: i64) -> f64 {
let closure = make_closure(func, arity, 1);
js_closure_set_capture_ptr(closure, 0, id);
boxed_ptr(closure)
}
fn rest_closure_value_with_id(func: *const u8, fixed_arity: u32, id: i64) -> f64 {
js_register_closure_rest(func, fixed_arity);
let closure = js_closure_alloc(func, 1);
crate::object::set_builtin_closure_length(closure as usize, fixed_arity);
js_closure_set_capture_ptr(closure, 0, id);
boxed_ptr(closure)
}
fn closure_id(closure: *const ClosureHeader) -> i64 {
js_closure_get_capture_ptr(closure, 0)
}
fn raw_ptr_from_value(value: f64) -> usize {
let bits = value.to_bits();
let jsval = JSValue::from_bits(bits);
if jsval.is_pointer() || jsval.is_string() || jsval.is_bigint() {
return (bits & POINTER_MASK) as usize;
}
if bits != 0 && bits < 0x0001_0000_0000_0000 {
return bits as usize;
}
0
}
unsafe fn gc_type_for_ptr(raw: usize) -> Option<u8> {
if raw < crate::gc::GC_HEADER_SIZE + 0x1000 {
return None;
}
let header = (raw as *const u8).sub(crate::gc::GC_HEADER_SIZE) as *const crate::gc::GcHeader;
let gc_type = (*header).obj_type;
(gc_type <= crate::gc::GC_TYPE_MAX).then_some(gc_type)
}
fn is_array_value(value: f64) -> bool {
let raw = raw_ptr_from_value(value);
raw >= 0x10000
&& !crate::buffer::is_registered_buffer(raw)
&& unsafe { gc_type_for_ptr(raw) == Some(crate::gc::GC_TYPE_ARRAY) }
}
fn is_callable_value(value: f64) -> bool {
let raw = raw_ptr_from_value(value);
raw >= 0x10000
&& !crate::buffer::is_registered_buffer(raw)
&& unsafe { gc_type_for_ptr(raw) == Some(crate::gc::GC_TYPE_CLOSURE) }
&& crate::closure::is_closure_ptr(raw)
}
fn array_values(value: f64) -> Option<Vec<f64>> {
if !is_array_value(value) {
return None;
}
let arr = raw_ptr_from_value(value) as *const crate::array::ArrayHeader;
let len = crate::array::js_array_length(arr);
let mut values = Vec::with_capacity(len as usize);
for i in 0..len {
values.push(crate::array::js_array_get_f64(arr, i));
}
Some(values)
}
fn value_to_string(value: f64) -> Option<String> {
crate::builtins::jsvalue_string_content(value)
}
fn object_property(value: f64, name: &[u8]) -> Option<f64> {
super::stream_promises::get_object_property(value, name)
}
fn object_string(value: f64, name: &[u8]) -> Option<String> {
object_property(value, name).and_then(value_to_string)
}
fn catch_js<F: FnOnce() -> f64>(f: F) -> Result<f64, f64> {
crate::exception::catch_js_throw(f)
}
fn throw_error_with_code(message: &str, code: &'static str) -> ! {
let msg = js_string_from_bytes(message.as_ptr(), message.len() as u32);
crate::node_submodules::register_error_code_pub(msg, code);
let err = crate::error::js_error_new_with_message(msg);
crate::exception::js_throw(crate::value::js_nanbox_pointer(err as i64))
}
fn throw_invalid_arg_type(arg: &str, expected: &str, value: f64) -> ! {
let message = format!(
"The \"{}\" argument must be of type {}. Received {}",
arg,
expected,
crate::fs::validate::describe_received(value)
);
crate::fs::validate::throw_type_error_with_code(&message, "ERR_INVALID_ARG_TYPE");
}
fn assert_callable_arg(arg: &str, value: f64) {
if !is_callable_value(value) {
throw_invalid_arg_type(arg, "function", value);
}
}
fn assert_mock_target_method(value: f64) {
if !is_callable_value(value) {
crate::validators::throw_invalid_arg_value(
"methodName",
"must be a method",
&crate::fs::validate::describe_received(value),
);
}
}
extern "C" fn mock_timers_enable(_closure: *const ClosureHeader, options: f64) -> f64 {
let (apis, now) = parse_mock_timer_options(options);
crate::timer::js_mock_timers_enable(apis, now);
undefined_value()
}
extern "C" fn mock_timers_tick(_closure: *const ClosureHeader, ms: f64) -> f64 {
let delay = if is_undefined_value(ms) {
1.0
} else {
validate_mock_timer_number("time", ms, false)
};
crate::timer::js_mock_timers_tick(delay);
undefined_value()
}
extern "C" fn mock_timers_run_all(_closure: *const ClosureHeader) -> f64 {
crate::timer::js_mock_timers_run_all();
undefined_value()
}
extern "C" fn mock_timers_set_time(_closure: *const ClosureHeader, ms: f64) -> f64 {
let time = validate_mock_timer_number("time", ms, false);
crate::timer::js_mock_timers_set_time(time);
undefined_value()
}
extern "C" fn mock_timers_reset(_closure: *const ClosureHeader) -> f64 {
crate::timer::js_mock_timers_reset();
undefined_value()
}
fn validate_mock_timer_number(arg: &str, value: f64, reject_nan: bool) -> f64 {
let js = JSValue::from_bits(value.to_bits());
if !crate::fs::validate::is_numeric(js) {
throw_invalid_arg_type(arg, "number", value);
}
let n = crate::builtins::js_number_coerce(value);
if n < 0.0 || (reject_nan && n.is_nan()) {
let message = format!(
"The \"{}\" argument must be a non-negative number. Received {}",
arg,
crate::fs::validate::describe_received(value)
);
crate::fs::validate::throw_type_error_with_code(&message, "ERR_INVALID_ARG_VALUE");
}
n
}
fn parse_mock_timer_options(options: f64) -> (u32, f64) {
let mut apis_value = options;
let mut now = 0.0;
let js = JSValue::from_bits(options.to_bits());
if js.is_undefined() || js.is_null() || !js.is_pointer() {
return (crate::timer::MOCK_TIMERS_ALL_APIS, now);
}
if !is_array_value(options) {
apis_value = object_property(options, b"apis").unwrap_or(undefined_value());
if let Some(now_value) = object_property(options, b"now") {
now = validate_mock_timer_number("options.now", now_value, true);
}
}
if JSValue::from_bits(apis_value.to_bits()).is_undefined() {
return (crate::timer::MOCK_TIMERS_ALL_APIS, now);
}
if !is_array_value(apis_value) {
throw_invalid_arg_type("options.apis", "Array", apis_value);
}
let mut mask = 0u32;
for api in array_values(apis_value).unwrap_or_default() {
let Some(name) = value_to_string(api) else {
throw_invalid_arg_type("options.apis", "string", api);
};
match name.as_str() {
"Date" => mask |= crate::timer::MOCK_TIMERS_API_DATE,
"setTimeout" => mask |= crate::timer::MOCK_TIMERS_API_SET_TIMEOUT,
"setInterval" => mask |= crate::timer::MOCK_TIMERS_API_SET_INTERVAL,
"setImmediate" => mask |= crate::timer::MOCK_TIMERS_API_SET_IMMEDIATE,
_ => {
let message = format!(
"The property 'options.apis' option {name} is not supported. Received '{name}'"
);
crate::fs::validate::throw_type_error_with_code(&message, "ERR_INVALID_ARG_VALUE");
}
}
}
(mask, now)
}
#[derive(Clone)]
enum MockRestoreTarget {
None,
// Node 26.5 accepts Symbol method names, but its restore path only
// recognizes string names and falls through to the bare-function case.
ObjectSymbolMethod,
ObjectProperty {
target: f64,
property: String,
original: f64,
},
ObjectAccessor {
target: f64,
property: String,
original_accessor: Option<crate::object::AccessorDescriptor>,
original_attrs: Option<crate::object::PropertyAttrs>,
original_value: f64,
},
}
struct MockState {
id: i64,
tracked: bool,
original: f64,
implementation: f64,
implementation_limit: Option<u64>,
once: Vec<(usize, f64)>,
calls: f64,
context: f64,
function: f64,
restore: MockRestoreTarget,
}
fn next_mock_id() -> i64 {
NEXT_MOCK_ID.with(|slot| {
let id = slot.get();
slot.set(id + 1);
id
})
}
fn update_mock_context_calls(context: f64, calls: f64) {
let ptr = raw_ptr_from_value(context);
if ptr >= 0x10000 {
set_field(ptr as *mut crate::object::ObjectHeader, "calls", calls);
}
}
fn set_property_value(target: f64, property: &str, value: f64) {
let raw = raw_ptr_from_value(target);
if raw < 0x10000 {
throw_invalid_arg_type("object", "object", target);
}
if crate::closure::is_closure_ptr(raw) {
crate::closure::closure_set_dynamic_prop(raw, property, value);
} else {
set_field(raw as *mut crate::object::ObjectHeader, property, value);
}
}
fn set_method_property_value(target: f64, property: &str, value: f64) {
let raw = raw_ptr_from_value(target);
if let Some(class_id) = crate::object::class_id_for_decl_prototype_object(raw) {
unsafe {
crate::object::js_register_prototype_method(
class_id,
property.as_ptr(),
property.len(),
value,
);
}
} else {
set_property_value(target, property, value);
}
}
fn get_property_value(target: f64, property: &str) -> f64 {
let raw = raw_ptr_from_value(target);
if raw >= 0x10000 && crate::closure::is_closure_ptr(raw) {
return crate::closure::closure_get_dynamic_prop(raw, property);
}
object_property(target, property.as_bytes()).unwrap_or(undefined_value())
}
fn property_name(value: f64) -> String {
value_to_string(value).unwrap_or_else(|| {
throw_invalid_arg_type("propertyName", "string", value);
})
}
fn object_target_addr(target: f64) -> usize {
let js = JSValue::from_bits(target.to_bits());
if !js.is_pointer() || unsafe { crate::symbol::js_is_symbol(target) } != 0 {
throw_invalid_arg_type("object", "object", target);
}
let raw = raw_ptr_from_value(target);
if raw < 0x10000 {
throw_invalid_arg_type("object", "object", target);
}
raw
}
fn accessor_function_value(bits: u64) -> f64 {
if bits == 0 {
undefined_value()
} else {
f64::from_bits(bits)
}
}
#[derive(Clone, Copy)]
struct MockMethodOptions {
getter: bool,
setter: bool,
times: Option<u64>,
}
fn is_non_null_object(value: f64) -> bool {
let js = JSValue::from_bits(value.to_bits());
js.is_pointer() && !is_callable_value(value)
}
fn mock_option_bool(options: f64, name: &str, default: bool) -> bool {
let Some(value) = object_property(options, name.as_bytes()) else {
return default;
};
match value.to_bits() {
crate::value::TAG_TRUE => true,
crate::value::TAG_FALSE => false,
crate::value::TAG_UNDEFINED => default,
_ => throw_invalid_arg_type(&format!("options.{name}"), "boolean", value),
}
}
fn parse_mock_method_options(
options: f64,
default_getter: bool,
default_setter: bool,
) -> MockMethodOptions {
if is_undefined_value(options) {
return MockMethodOptions {
getter: default_getter,
setter: default_setter,
times: None,
};
}
crate::validators::validate_object(options, "options");
let scope = crate::gc::RuntimeHandleScope::new();
let options = scope.root_nanbox_f64(options);
let getter = mock_option_bool(options.get_nanbox_f64(), "getter", default_getter);
let setter = mock_option_bool(options.get_nanbox_f64(), "setter", default_setter);
let times = mock_option_times(options.get_nanbox_f64());
MockMethodOptions {
getter,
setter,
times,
}
}
fn normalize_mock_method_args(implementation: f64, options: f64) -> (f64, f64) {
if is_non_null_object(implementation) {
(undefined_value(), implementation)
} else {
(implementation, options)
}
}
fn throw_invalid_mock_option_value(arg: &str, value: f64, reason: &str) -> ! {
crate::validators::throw_invalid_arg_value(
arg,
reason,
&crate::fs::validate::describe_received(value),
);
}
fn validate_mock_accessor_options(options: MockMethodOptions, kind: &str) {
if kind == "getter" && !options.getter {
throw_invalid_mock_option_value(
"options.getter",
f64::from_bits(crate::value::TAG_FALSE),
"cannot be false",
);
}
if kind == "setter" && !options.setter {
throw_invalid_mock_option_value(
"options.setter",
f64::from_bits(crate::value::TAG_FALSE),
"cannot be false",
);
}
if options.getter && options.setter {
throw_invalid_mock_option_value(
"options.setter",
f64::from_bits(crate::value::TAG_TRUE),
"cannot be used with 'options.getter'",
);
}
}
fn install_accessor_mock(target: f64, property: &str, accessor: crate::object::AccessorDescriptor) {
let raw = object_target_addr(target);
let key = js_string_from_bytes(property.as_ptr(), property.len() as u32);
unsafe {
crate::object::ensure_key_in_keys_array(raw as *mut crate::object::ObjectHeader, key);
}
crate::object::set_accessor_descriptor(raw, property.to_string(), accessor);
crate::object::set_property_attrs(
raw,
property.to_string(),
crate::object::PropertyAttrs::new(true, true, true),
);
}
fn restore_accessor_mock(
target: f64,
property: &str,
original_accessor: Option<crate::object::AccessorDescriptor>,
original_attrs: Option<crate::object::PropertyAttrs>,
original_value: f64,
) {
let raw = object_target_addr(target);
if let Some(accessor) = original_accessor {
crate::object::set_accessor_descriptor(raw, property.to_string(), accessor);
} else {
crate::object::clear_accessor_descriptor(raw, property);
set_property_value(target, property, original_value);
}
if let Some(attrs) = original_attrs {
crate::object::set_property_attrs(raw, property.to_string(), attrs);
} else {
crate::object::clear_property_attrs(raw, property);
}
}
fn mock_context_object(id: i64, calls: f64, include_call_tracking: bool) -> f64 {
let obj = js_object_alloc(0, 6);
if include_call_tracking {
set_field(obj, "calls", calls);
set_field(
obj,
"callCount",
closure_value_with_id(mock_context_call_count as *const u8, 0, id),
);
set_field(
obj,
"resetCalls",
closure_value_with_id(mock_context_reset_calls as *const u8, 0, id),
);
set_field(
obj,
"mockImplementation",
closure_value_with_id(mock_context_mock_implementation as *const u8, 1, id),
);
set_field(
obj,
"mockImplementationOnce",
closure_value_with_id(mock_context_mock_implementation_once as *const u8, 2, id),
);
}
set_field(
obj,
"restore",
closure_value_with_id(mock_context_restore as *const u8, 0, id),
);
boxed_ptr(obj)
}
fn mock_function_metadata(original: f64) -> (String, u32) {
if !is_callable_value(original) {
return ("mockFn".to_string(), 0);
}
let closure = raw_ptr_from_value(original) as *const ClosureHeader;
let dynamic_name = crate::closure::closure_get_own_dynamic_prop(closure as usize, "name")
.and_then(value_to_string);
let name = dynamic_name
.or_else(|| unsafe { crate::builtins::function_name_for_ptr((*closure).func_ptr as usize) })
.unwrap_or_default();
let length = crate::closure::closure_length(closure).unwrap_or(0);
(name, length)
}
fn create_mock_function(
original: f64,
implementation: f64,
implementation_limit: Option<u64>,
restore: MockRestoreTarget,
) -> f64 {
if !JSValue::from_bits(original.to_bits()).is_undefined() {
assert_callable_arg("original", original);
}
if !JSValue::from_bits(implementation.to_bits()).is_undefined() {
assert_callable_arg("implementation", implementation);
}
let (name, length) = mock_function_metadata(original);
let scope = crate::gc::RuntimeHandleScope::new();
let original = scope.root_nanbox_f64(original);
let implementation = scope.root_nanbox_f64(implementation);
let id = next_mock_id();
let calls = scope.root_nanbox_f64(boxed_ptr(crate::array::js_array_alloc(0)));
let context = scope.root_nanbox_f64(mock_context_object(id, calls.get_nanbox_f64(), true));
let function = scope.root_nanbox_f64(rest_closure_value_with_id(
mock_function_invoke as *const u8,
0,
id,
));
let closure_ptr = raw_ptr_from_value(function.get_nanbox_f64());
if closure_ptr != 0 {
crate::object::set_bound_native_closure_name(closure_ptr as *mut ClosureHeader, &name);
let closure_ptr = raw_ptr_from_value(function.get_nanbox_f64());
crate::object::set_builtin_closure_length(closure_ptr, length);
crate::object::set_builtin_property_attrs(
closure_ptr,
"length".to_string(),
crate::object::PropertyAttrs::new(false, false, true),
);
crate::closure::closure_set_dynamic_prop(closure_ptr, "mock", context.get_nanbox_f64());
}
MOCK_STATES.with(|states| {
states.borrow_mut().push(MockState {
id,
tracked: true,
original: original.get_nanbox_f64(),
implementation: implementation.get_nanbox_f64(),
implementation_limit,
once: Vec::new(),
calls: calls.get_nanbox_f64(),
context: context.get_nanbox_f64(),
function: function.get_nanbox_f64(),
restore,
});
});
function.get_nanbox_f64()
}
fn reset_mock_state_calls(state: &mut MockState) {
state.calls = boxed_ptr(crate::array::js_array_alloc(0));
update_mock_context_calls(state.context, state.calls);
}
fn mock_state_call_count(state: &MockState) -> usize {
if !is_array_value(state.calls) {
return 0;
}
crate::array::js_array_length(
raw_ptr_from_value(state.calls) as *const crate::array::ArrayHeader
) as usize
}
fn schedule_mock_implementation_once(state: &mut MockState, call: usize, implementation: f64) {
if let Some((_, existing)) = state.once.iter_mut().find(|(index, _)| *index == call) {
*existing = implementation;
} else {
state.once.push((call, implementation));
}
crate::gc::runtime_write_barrier_root_nanbox(implementation.to_bits());
}
fn take_mock_implementation(state: &mut MockState) -> f64 {
let call = mock_state_call_count(state);
if let Some(position) = state.once.iter().position(|(index, _)| *index == call) {
state.once.remove(position).1
} else if state
.implementation_limit
.is_some_and(|limit| call as u64 >= limit)
{
state.original
} else {
state.implementation
}
}
fn prepare_mock_state_restore(state: &mut MockState) -> MockRestoreTarget {
// Node 26.5's restore path only recognizes string method names. A
// Symbol-keyed method falls through to the bare-function case, so the
// restored mock is left with no implementation and a later invocation
// throws instead of reaching the original method.
state.implementation = if matches!(state.restore, MockRestoreTarget::ObjectSymbolMethod) {
undefined_value()
} else {
state.original
};
state.restore.clone()
}
fn restore_mock_state(id: i64) {
let restore = MOCK_STATES.with(|states| {
let mut states = states.borrow_mut();
let Some(state) = states.iter_mut().find(|state| state.id == id) else {
return None;
};
Some(prepare_mock_state_restore(state))
});
match restore {
Some(MockRestoreTarget::ObjectProperty {
target,
property,
original,
}) => set_method_property_value(target, &property, original),
Some(MockRestoreTarget::ObjectAccessor {
target,
property,
original_accessor,
original_attrs,
original_value,
}) => restore_accessor_mock(
target,
&property,
original_accessor,
original_attrs,
original_value,
),
_ => {}
}
}
fn record_mock_call(id: i64, args_value: f64, this_value: f64, result: f64, error: f64) {
let calls_value = MOCK_STATES.with(|states| {
states
.borrow()
.iter()
.find(|state| state.id == id)
.map(|state| state.calls)
.unwrap_or_else(undefined_value)
});
if !is_array_value(calls_value) {
return;
}
let scope = crate::gc::RuntimeHandleScope::new();
let args_handle = scope.root_nanbox_f64(args_value);
let this_handle = scope.root_nanbox_f64(this_value);
let result_handle = scope.root_nanbox_f64(result);
let error_handle = scope.root_nanbox_f64(error);
let calls_handle = scope.root_nanbox_f64(calls_value);
let stack_message = string_value("Error");
let stack = crate::error::js_error_new_with_message(
raw_ptr_from_value(stack_message) as *mut crate::StringHeader
);
let stack_handle = scope.root_nanbox_f64(crate::value::js_nanbox_pointer(stack as i64));
let call = js_object_alloc(0, 6);
set_field(call, "arguments", args_handle.get_nanbox_f64());
set_field(call, "this", this_handle.get_nanbox_f64());
set_field(call, "target", undefined_value());
set_field(call, "result", result_handle.get_nanbox_f64());
set_field(call, "error", error_handle.get_nanbox_f64());
set_field(call, "stack", stack_handle.get_nanbox_f64());
let call_handle = scope.root_nanbox_f64(boxed_ptr(call));
let calls_ptr =
raw_ptr_from_value(calls_handle.get_nanbox_f64()) as *mut crate::array::ArrayHeader;
let new_calls = crate::array::js_array_push_f64(calls_ptr, call_handle.get_nanbox_f64());
let new_calls_value = boxed_ptr(new_calls);
MOCK_STATES.with(|states| {
if let Some(state) = states.borrow_mut().iter_mut().find(|state| state.id == id) {
state.calls = new_calls_value;
update_mock_context_calls(state.context, state.calls);
}
});
}
#[cfg(test)]
#[path = "test_metadata_unit_tests.rs"]
mod metadata_tests;
extern "C" fn mock_function_invoke(closure: *const ClosureHeader, rest: f64) -> f64 {
let id = closure_id(closure);
let args = array_values(rest).unwrap_or_default();
let (implementation, is_symbol_method) = MOCK_STATES.with(|states| {
let mut states = states.borrow_mut();
let Some(state) = states.iter_mut().find(|state| state.id == id) else {
return (undefined_value(), false);
};
(
take_mock_implementation(state),
matches!(state.restore, MockRestoreTarget::ObjectSymbolMethod),
)
});
let this_value = crate::object::js_implicit_this_get();
if JSValue::from_bits(implementation.to_bits()).is_undefined() {
if is_symbol_method {
let scope = crate::gc::RuntimeHandleScope::new();
let rest_handle = scope.root_nanbox_f64(rest);
let this_handle = scope.root_nanbox_f64(this_value);
let message_handle = scope.root_nanbox_f64(string_value("undefined is not a function"));
let error = crate::error::js_typeerror_new(raw_ptr_from_value(
message_handle.get_nanbox_f64(),
) as *mut crate::StringHeader);
let error_handle = scope.root_nanbox_f64(crate::value::js_nanbox_pointer(error as i64));
record_mock_call(
id,
rest_handle.get_nanbox_f64(),
this_handle.get_nanbox_f64(),
undefined_value(),
error_handle.get_nanbox_f64(),
);
crate::exception::js_throw(error_handle.get_nanbox_f64());
}
record_mock_call(id, rest, this_value, undefined_value(), undefined_value());
return undefined_value();
}
let scope = crate::gc::RuntimeHandleScope::new();
let implementation_handle = scope.root_nanbox_f64(implementation);
let rest_handle = scope.root_nanbox_f64(rest);
let arg_handles = scope.root_nanbox_f64_slice(&args);
let call_args = crate::gc::RuntimeHandleScope::refreshed_nanbox_f64_slice(&arg_handles);
let previous_this = scope.root_nanbox_f64(crate::object::js_implicit_this_set(this_value)); // #9445
let call_result = catch_js(|| unsafe {
crate::closure::js_native_call_value(
implementation_handle.get_nanbox_f64(),
call_args.as_ptr(),
call_args.len(),
)
});
crate::object::js_implicit_this_set(previous_this.get_nanbox_f64());
match call_result {
Ok(result) => {
let result_handle = scope.root_nanbox_f64(result);
record_mock_call(
id,
rest_handle.get_nanbox_f64(),
this_value,
result_handle.get_nanbox_f64(),
undefined_value(),
);
result_handle.get_nanbox_f64()
}
Err(err) => {
let err_handle = scope.root_nanbox_f64(err);
record_mock_call(
id,
rest_handle.get_nanbox_f64(),
this_value,
undefined_value(),
err_handle.get_nanbox_f64(),
);
crate::exception::js_throw(err_handle.get_nanbox_f64())
}
}
}
extern "C" fn mock_context_call_count(closure: *const ClosureHeader) -> f64 {
let id = closure_id(closure);
MOCK_STATES.with(|states| {
states
.borrow()
.iter()
.find(|state| state.id == id)
.and_then(|state| {
is_array_value(state.calls).then(|| {
crate::array::js_array_length(
raw_ptr_from_value(state.calls) as *const crate::array::ArrayHeader
) as f64
})
})
.unwrap_or(0.0)
})
}
extern "C" fn mock_context_reset_calls(closure: *const ClosureHeader) -> f64 {
let id = closure_id(closure);
MOCK_STATES.with(|states| {
if let Some(state) = states.borrow_mut().iter_mut().find(|state| state.id == id) {
reset_mock_state_calls(state);
}
});
undefined_value()
}
extern "C" fn mock_context_mock_implementation(
closure: *const ClosureHeader,
implementation: f64,
) -> f64 {
assert_callable_arg("implementation", implementation);
let id = closure_id(closure);
MOCK_STATES.with(|states| {
if let Some(state) = states.borrow_mut().iter_mut().find(|state| state.id == id) {
state.implementation = implementation;
}
});
undefined_value()
}
extern "C" fn mock_context_mock_implementation_once(
closure: *const ClosureHeader,
implementation: f64,
on_call: f64,
) -> f64 {
assert_callable_arg("implementation", implementation);
let id = closure_id(closure);
let next_call = MOCK_STATES.with(|states| {
states
.borrow()
.iter()
.find(|state| state.id == id)
.map(mock_state_call_count)
.unwrap_or(0)
});
let call = if is_undefined_value(on_call) {
next_call
} else {
crate::validators::validate_integer(
on_call,
"onCall",
next_call as f64,
crate::validators::MAX_SAFE_INTEGER,
) as usize
};
MOCK_STATES.with(|states| {
if let Some(state) = states.borrow_mut().iter_mut().find(|state| state.id == id) {
schedule_mock_implementation_once(state, call, implementation);
}
});
undefined_value()
}
extern "C" fn mock_context_restore(closure: *const ClosureHeader) -> f64 {
restore_mock_state(closure_id(closure));
undefined_value()
}
extern "C" fn mock_fn_thunk(
_closure: *const ClosureHeader,
original: f64,
implementation_or_options: f64,
options: f64,
) -> f64 {
let scope = crate::gc::RuntimeHandleScope::new();
let original = scope.root_nanbox_f64(original);
let implementation_or_options = scope.root_nanbox_f64(implementation_or_options);
let options = scope.root_nanbox_f64(options);
let (implementation, options) =
if is_non_null_object(implementation_or_options.get_nanbox_f64()) {
(
original.get_nanbox_f64(),
implementation_or_options.get_nanbox_f64(),
)
} else if is_undefined_value(implementation_or_options.get_nanbox_f64()) {
(original.get_nanbox_f64(), options.get_nanbox_f64())
} else {
assert_callable_arg("implementation", implementation_or_options.get_nanbox_f64());
(
implementation_or_options.get_nanbox_f64(),
options.get_nanbox_f64(),
)
};
let times = parse_mock_fn_options(options);
create_mock_function(
original.get_nanbox_f64(),
implementation,
times,
MockRestoreTarget::None,
)
}
extern "C" fn mock_method_thunk(
_closure: *const ClosureHeader,
target: f64,
property: f64,
implementation: f64,
options: f64,
) -> f64 {
let scope = crate::gc::RuntimeHandleScope::new();
let target = scope.root_nanbox_f64(target);
let property = scope.root_nanbox_f64(property);
let implementation = scope.root_nanbox_f64(implementation);
let options = scope.root_nanbox_f64(options);
object_target_addr(target.get_nanbox_f64());
let (implementation, options) =
normalize_mock_method_args(implementation.get_nanbox_f64(), options.get_nanbox_f64());
let implementation = scope.root_nanbox_f64(implementation);
let options = parse_mock_method_options(options, false, false);
validate_mock_accessor_options(options, "method");
if options.getter {
return create_getter_mock(
target.get_nanbox_f64(),
property.get_nanbox_f64(),
implementation.get_nanbox_f64(),
options.times,
);
}
if options.setter {
return create_setter_mock(
target.get_nanbox_f64(),
property.get_nanbox_f64(),