-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathtest_javascript_test_runner.py
More file actions
1101 lines (900 loc) · 43.8 KB
/
test_javascript_test_runner.py
File metadata and controls
1101 lines (900 loc) · 43.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
"""Tests for JavaScript/Jest test runner functionality."""
import sys
import tempfile
from pathlib import Path
from unittest.mock import patch, MagicMock
import pytest
class TestJestRootsConfiguration:
"""Tests for Jest --roots flag handling."""
def test_behavioral_tests_adds_roots_for_test_directories(self):
"""Test that run_jest_behavioral_tests adds --roots for test directories."""
from codeflash.languages.javascript.test_runner import run_jest_behavioral_tests
from codeflash.models.models import TestFile, TestFiles
from codeflash.models.test_type import TestType
# Create mock test files in a test directory
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir_path = Path(tmpdir).resolve()
test_dir = tmpdir_path / "test"
test_dir.mkdir()
# Create package.json to simulate a Node project
(tmpdir_path / "package.json").write_text('{"name": "test"}')
# Create mock test files
test_file1 = test_dir / "test_func__unit_test_0.test.ts"
test_file2 = test_dir / "test_func__unit_test_1.test.ts"
test_file1.write_text("// test 1")
test_file2.write_text("// test 2")
mock_test_files = TestFiles(
test_files=[
TestFile(
original_file_path=test_file1,
instrumented_behavior_file_path=test_file1,
benchmarking_file_path=test_file1,
test_type=TestType.GENERATED_REGRESSION,
),
TestFile(
original_file_path=test_file2,
instrumented_behavior_file_path=test_file2,
benchmarking_file_path=test_file2,
test_type=TestType.GENERATED_REGRESSION,
),
]
)
# Mock subprocess.run to capture the command
with patch("subprocess.run") as mock_run:
mock_result = MagicMock()
mock_result.stdout = ""
mock_result.stderr = ""
mock_result.returncode = 1
mock_run.return_value = mock_result
try:
run_jest_behavioral_tests(
test_paths=mock_test_files,
test_env={},
cwd=tmpdir_path,
project_root=tmpdir_path,
)
except Exception:
pass # Expected to fail since no real Jest
# Verify the command included --roots
if mock_run.called:
call_args = mock_run.call_args
cmd = call_args[0][0]
# Find --roots flags in the command
roots_flags = []
for i, arg in enumerate(cmd):
if arg == "--roots" and i + 1 < len(cmd):
roots_flags.append(cmd[i + 1])
# Should have added the test directory as a root
assert len(roots_flags) > 0, "Expected --roots flag in Jest command"
assert str(test_dir) in roots_flags or any(
str(test_dir) in root for root in roots_flags
), f"Expected test directory {test_dir} in --roots flags: {roots_flags}"
def test_benchmarking_tests_adds_roots_for_test_directories(self):
"""Test that run_jest_benchmarking_tests adds --roots for test directories."""
from codeflash.languages.javascript.test_runner import run_jest_benchmarking_tests
from codeflash.models.models import TestFile, TestFiles
from codeflash.models.test_type import TestType
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir_path = Path(tmpdir).resolve()
test_dir = tmpdir_path / "test"
test_dir.mkdir()
(tmpdir_path / "package.json").write_text('{"name": "test"}')
test_file = test_dir / "test_func__perf_test_0.test.ts"
test_file.write_text("// perf test")
mock_test_files = TestFiles(
test_files=[
TestFile(
original_file_path=test_file,
instrumented_behavior_file_path=test_file,
benchmarking_file_path=test_file,
test_type=TestType.GENERATED_REGRESSION,
),
]
)
with patch("subprocess.run") as mock_run:
mock_result = MagicMock()
mock_result.stdout = ""
mock_result.stderr = ""
mock_result.returncode = 1
mock_run.return_value = mock_result
try:
run_jest_benchmarking_tests(
test_paths=mock_test_files,
test_env={},
cwd=tmpdir_path,
project_root=tmpdir_path,
)
except Exception:
pass
if mock_run.called:
call_args = mock_run.call_args
cmd = call_args[0][0]
roots_flags = []
for i, arg in enumerate(cmd):
if arg == "--roots" and i + 1 < len(cmd):
roots_flags.append(cmd[i + 1])
assert len(roots_flags) > 0, "Expected --roots flag in Jest command"
def test_line_profile_tests_adds_roots_for_test_directories(self):
"""Test that run_jest_line_profile_tests adds --roots for test directories."""
from codeflash.languages.javascript.test_runner import run_jest_line_profile_tests
from codeflash.models.models import TestFile, TestFiles
from codeflash.models.test_type import TestType
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir_path = Path(tmpdir)
test_dir = tmpdir_path / "test"
test_dir.mkdir()
(tmpdir_path / "package.json").write_text('{"name": "test"}')
test_file = test_dir / "test_func__line_profile.test.ts"
test_file.write_text("// line profile test")
mock_test_files = TestFiles(
test_files=[
TestFile(
original_file_path=test_file,
instrumented_behavior_file_path=test_file,
benchmarking_file_path=test_file,
test_type=TestType.GENERATED_REGRESSION,
),
]
)
with patch("subprocess.run") as mock_run:
mock_result = MagicMock()
mock_result.stdout = ""
mock_result.stderr = ""
mock_result.returncode = 1
mock_run.return_value = mock_result
try:
run_jest_line_profile_tests(
test_paths=mock_test_files,
test_env={},
cwd=tmpdir_path,
project_root=tmpdir_path,
)
except Exception:
pass
if mock_run.called:
call_args = mock_run.call_args
cmd = call_args[0][0]
roots_flags = []
for i, arg in enumerate(cmd):
if arg == "--roots" and i + 1 < len(cmd):
roots_flags.append(cmd[i + 1])
assert len(roots_flags) > 0, "Expected --roots flag in Jest command"
def test_multiple_test_directories_all_added_to_roots(self):
"""Test that multiple test directories are all added as --roots."""
from codeflash.languages.javascript.test_runner import run_jest_behavioral_tests
from codeflash.models.models import TestFile, TestFiles
from codeflash.models.test_type import TestType
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir_path = Path(tmpdir)
test_dir1 = tmpdir_path / "test"
test_dir2 = tmpdir_path / "spec"
test_dir1.mkdir()
test_dir2.mkdir()
(tmpdir_path / "package.json").write_text('{"name": "test"}')
test_file1 = test_dir1 / "test_func__unit_test_0.test.ts"
test_file2 = test_dir2 / "test_func__unit_test_1.test.ts"
test_file1.write_text("// test 1")
test_file2.write_text("// test 2")
mock_test_files = TestFiles(
test_files=[
TestFile(
original_file_path=test_file1,
instrumented_behavior_file_path=test_file1,
benchmarking_file_path=test_file1,
test_type=TestType.GENERATED_REGRESSION,
),
TestFile(
original_file_path=test_file2,
instrumented_behavior_file_path=test_file2,
benchmarking_file_path=test_file2,
test_type=TestType.GENERATED_REGRESSION,
),
]
)
with patch("subprocess.run") as mock_run:
mock_result = MagicMock()
mock_result.stdout = ""
mock_result.stderr = ""
mock_result.returncode = 1
mock_run.return_value = mock_result
try:
run_jest_behavioral_tests(
test_paths=mock_test_files,
test_env={},
cwd=tmpdir_path,
project_root=tmpdir_path,
)
except Exception:
pass
if mock_run.called:
call_args = mock_run.call_args
cmd = call_args[0][0]
roots_flags = []
for i, arg in enumerate(cmd):
if arg == "--roots" and i + 1 < len(cmd):
roots_flags.append(cmd[i + 1])
# Should have two --roots flags (one for each directory)
assert len(roots_flags) == 2, f"Expected 2 --roots flags, got {len(roots_flags)}"
class TestVitestTimeoutConfiguration:
"""Tests for Vitest subprocess timeout handling."""
def test_vitest_behavioral_subprocess_timeout_larger_than_test_timeout(self):
"""Test that subprocess timeout is larger than per-test timeout for Vitest behavioral tests."""
from codeflash.languages.javascript.vitest_runner import run_vitest_behavioral_tests
from codeflash.models.models import TestFile, TestFiles
from codeflash.models.test_type import TestType
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir_path = Path(tmpdir)
test_dir = tmpdir_path / "test"
test_dir.mkdir()
(tmpdir_path / "package.json").write_text('{"name": "test", "devDependencies": {"vitest": "^1.0.0"}}')
test_file = test_dir / "test_func.test.ts"
test_file.write_text("// test")
mock_test_files = TestFiles(
test_files=[
TestFile(
original_file_path=test_file,
instrumented_behavior_file_path=test_file,
benchmarking_file_path=test_file,
test_type=TestType.GENERATED_REGRESSION,
),
]
)
with patch("subprocess.run") as mock_run:
mock_result = MagicMock()
mock_result.stdout = ""
mock_result.stderr = ""
mock_result.returncode = 0
mock_run.return_value = mock_result
# Run with a 15 second per-test timeout
run_vitest_behavioral_tests(
test_paths=mock_test_files,
test_env={},
cwd=tmpdir_path,
timeout=15, # 15 second per-test timeout
project_root=tmpdir_path,
)
# Verify subprocess was called with a larger timeout
assert mock_run.called
call_kwargs = mock_run.call_args[1]
subprocess_timeout = call_kwargs.get("timeout")
# Subprocess timeout should be at least 120 seconds (minimum)
# or 10x the per-test timeout (150 seconds)
assert subprocess_timeout >= 120, f"Expected subprocess timeout >= 120s, got {subprocess_timeout}s"
assert subprocess_timeout >= 15 * 10, f"Expected subprocess timeout >= 150s (10x per-test), got {subprocess_timeout}s"
def test_vitest_line_profile_subprocess_timeout_larger_than_test_timeout(self):
"""Test that subprocess timeout is larger than per-test timeout for Vitest line profile tests."""
from codeflash.languages.javascript.vitest_runner import run_vitest_line_profile_tests
from codeflash.models.models import TestFile, TestFiles
from codeflash.models.test_type import TestType
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir_path = Path(tmpdir)
test_dir = tmpdir_path / "test"
test_dir.mkdir()
(tmpdir_path / "package.json").write_text('{"name": "test", "devDependencies": {"vitest": "^1.0.0"}}')
test_file = test_dir / "test_func.test.ts"
test_file.write_text("// test")
mock_test_files = TestFiles(
test_files=[
TestFile(
original_file_path=test_file,
instrumented_behavior_file_path=test_file,
benchmarking_file_path=test_file,
test_type=TestType.GENERATED_REGRESSION,
),
]
)
with patch("subprocess.run") as mock_run:
mock_result = MagicMock()
mock_result.stdout = ""
mock_result.stderr = ""
mock_result.returncode = 0
mock_run.return_value = mock_result
run_vitest_line_profile_tests(
test_paths=mock_test_files,
test_env={},
cwd=tmpdir_path,
timeout=15,
project_root=tmpdir_path,
)
assert mock_run.called
call_kwargs = mock_run.call_args[1]
subprocess_timeout = call_kwargs.get("timeout")
assert subprocess_timeout >= 120, f"Expected subprocess timeout >= 120s, got {subprocess_timeout}s"
def test_vitest_default_subprocess_timeout_is_reasonable(self):
"""Test that default subprocess timeout is at least 120 seconds when no timeout specified."""
from codeflash.languages.javascript.vitest_runner import run_vitest_behavioral_tests
from codeflash.models.models import TestFile, TestFiles
from codeflash.models.test_type import TestType
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir_path = Path(tmpdir)
test_dir = tmpdir_path / "test"
test_dir.mkdir()
(tmpdir_path / "package.json").write_text('{"name": "test", "devDependencies": {"vitest": "^1.0.0"}}')
test_file = test_dir / "test_func.test.ts"
test_file.write_text("// test")
mock_test_files = TestFiles(
test_files=[
TestFile(
original_file_path=test_file,
instrumented_behavior_file_path=test_file,
benchmarking_file_path=test_file,
test_type=TestType.GENERATED_REGRESSION,
),
]
)
with patch("subprocess.run") as mock_run:
mock_result = MagicMock()
mock_result.stdout = ""
mock_result.stderr = ""
mock_result.returncode = 0
mock_run.return_value = mock_result
# Run without specifying a timeout
run_vitest_behavioral_tests(
test_paths=mock_test_files,
test_env={},
cwd=tmpdir_path,
project_root=tmpdir_path,
)
assert mock_run.called
call_kwargs = mock_run.call_args[1]
subprocess_timeout = call_kwargs.get("timeout")
# Default should be at least 120 seconds (or 600 from the default)
assert subprocess_timeout >= 120, f"Expected subprocess timeout >= 120s, got {subprocess_timeout}s"
class TestVitestInternalLoopingConfiguration:
"""Tests for Vitest internal looping (no external loop-runner)."""
def test_vitest_benchmarking_does_not_set_current_batch_env(self):
"""Test that Vitest runner does NOT set CODEFLASH_PERF_CURRENT_BATCH.
This is critical: when CODEFLASH_PERF_CURRENT_BATCH is not set,
capturePerf() in the npm package will do all loops internally
(PERF_LOOP_COUNT iterations) instead of just PERF_BATCH_SIZE.
"""
from codeflash.languages.javascript.vitest_runner import run_vitest_benchmarking_tests
from codeflash.models.models import TestFile, TestFiles
from codeflash.models.test_type import TestType
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir_path = Path(tmpdir)
test_dir = tmpdir_path / "test"
test_dir.mkdir()
(tmpdir_path / "package.json").write_text('{"name": "test", "devDependencies": {"vitest": "^1.0.0"}}')
test_file = test_dir / "test_func.test.ts"
test_file.write_text("// perf test")
mock_test_files = TestFiles(
test_files=[
TestFile(
original_file_path=test_file,
instrumented_behavior_file_path=test_file,
benchmarking_file_path=test_file,
test_type=TestType.GENERATED_REGRESSION,
),
]
)
with patch("subprocess.run") as mock_run:
mock_result = MagicMock()
mock_result.stdout = ""
mock_result.stderr = ""
mock_result.returncode = 0
mock_run.return_value = mock_result
run_vitest_benchmarking_tests(
test_paths=mock_test_files,
test_env={},
cwd=tmpdir_path,
project_root=tmpdir_path,
max_loops=100,
min_loops=5,
)
assert mock_run.called
call_kwargs = mock_run.call_args[1]
env = call_kwargs.get("env", {})
# CODEFLASH_PERF_CURRENT_BATCH should NOT be set
# This allows capturePerf() to do all loops internally
assert "CODEFLASH_PERF_CURRENT_BATCH" not in env, (
"CODEFLASH_PERF_CURRENT_BATCH should not be set for Vitest - "
"internal looping relies on this being undefined"
)
# But CODEFLASH_PERF_LOOP_COUNT should be set
assert "CODEFLASH_PERF_LOOP_COUNT" in env, "CODEFLASH_PERF_LOOP_COUNT should be set"
assert env["CODEFLASH_PERF_LOOP_COUNT"] == "100"
def test_vitest_benchmarking_sets_loop_configuration_env_vars(self):
"""Test that Vitest benchmarking sets correct loop configuration environment variables."""
from codeflash.languages.javascript.vitest_runner import run_vitest_benchmarking_tests
from codeflash.models.models import TestFile, TestFiles
from codeflash.models.test_type import TestType
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir_path = Path(tmpdir)
test_dir = tmpdir_path / "test"
test_dir.mkdir()
(tmpdir_path / "package.json").write_text('{"name": "test", "devDependencies": {"vitest": "^1.0.0"}}')
test_file = test_dir / "test_func.test.ts"
test_file.write_text("// perf test")
mock_test_files = TestFiles(
test_files=[
TestFile(
original_file_path=test_file,
instrumented_behavior_file_path=test_file,
benchmarking_file_path=test_file,
test_type=TestType.GENERATED_REGRESSION,
),
]
)
with patch("subprocess.run") as mock_run:
mock_result = MagicMock()
mock_result.stdout = ""
mock_result.stderr = ""
mock_result.returncode = 0
mock_run.return_value = mock_result
run_vitest_benchmarking_tests(
test_paths=mock_test_files,
test_env={},
cwd=tmpdir_path,
project_root=tmpdir_path,
max_loops=50,
min_loops=10,
target_duration_ms=5000,
stability_check=True,
)
assert mock_run.called
call_kwargs = mock_run.call_args[1]
env = call_kwargs.get("env", {})
# Verify all loop configuration env vars are set correctly
assert env.get("CODEFLASH_PERF_LOOP_COUNT") == "50"
assert env.get("CODEFLASH_PERF_MIN_LOOPS") == "10"
assert env.get("CODEFLASH_PERF_TARGET_DURATION_MS") == "5000"
assert env.get("CODEFLASH_PERF_STABILITY_CHECK") == "true"
assert env.get("CODEFLASH_MODE") == "performance"
class TestBundlerModuleResolutionFix:
"""Tests for bundler moduleResolution compatibility fix."""
def test_detect_bundler_module_resolution_true(self):
"""Test detection of bundler moduleResolution in tsconfig."""
import json
from codeflash.languages.javascript.test_runner import _detect_bundler_module_resolution
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir_path = Path(tmpdir)
# Create tsconfig with bundler moduleResolution
tsconfig = {
"compilerOptions": {
"moduleResolution": "bundler",
"module": "preserve",
"target": "ES2022",
}
}
(tmpdir_path / "tsconfig.json").write_text(json.dumps(tsconfig))
assert _detect_bundler_module_resolution(tmpdir_path) is True
def test_detect_bundler_module_resolution_false(self):
"""Test detection returns false for Node moduleResolution."""
import json
from codeflash.languages.javascript.test_runner import _detect_bundler_module_resolution
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir_path = Path(tmpdir)
# Create tsconfig with Node moduleResolution
tsconfig = {
"compilerOptions": {
"moduleResolution": "Node",
"module": "ESNext",
}
}
(tmpdir_path / "tsconfig.json").write_text(json.dumps(tsconfig))
assert _detect_bundler_module_resolution(tmpdir_path) is False
def test_detect_bundler_module_resolution_no_tsconfig(self):
"""Test detection returns false when no tsconfig exists."""
from codeflash.languages.javascript.test_runner import _detect_bundler_module_resolution
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir_path = Path(tmpdir)
assert _detect_bundler_module_resolution(tmpdir_path) is False
def test_detect_bundler_module_resolution_extended_config(self):
"""Test detection works with extended tsconfig files."""
import json
from codeflash.languages.javascript.test_runner import _detect_bundler_module_resolution
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir_path = Path(tmpdir)
# Create a base config with bundler in a subdirectory (simulating node_modules)
node_modules = tmpdir_path / "node_modules" / "@myorg" / "tsconfig"
node_modules.mkdir(parents=True)
base_tsconfig = {
"compilerOptions": {
"moduleResolution": "bundler",
"module": "preserve",
}
}
(node_modules / "tsconfig.json").write_text(json.dumps(base_tsconfig))
# Create a project tsconfig that extends the base
project_tsconfig = {
"extends": "@myorg/tsconfig/tsconfig.json",
"compilerOptions": {
"target": "ES2022",
}
}
(tmpdir_path / "tsconfig.json").write_text(json.dumps(project_tsconfig))
# Should detect bundler from extended config
assert _detect_bundler_module_resolution(tmpdir_path) is True
def test_create_codeflash_tsconfig(self):
"""Test creation of codeflash-compatible tsconfig."""
import json
from codeflash.languages.javascript.test_runner import _create_codeflash_tsconfig
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir_path = Path(tmpdir)
# Create original tsconfig
original_tsconfig = {
"compilerOptions": {
"moduleResolution": "bundler",
"module": "preserve",
"target": "ES2022",
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules"],
}
(tmpdir_path / "tsconfig.json").write_text(json.dumps(original_tsconfig))
# Create codeflash tsconfig
result_path = _create_codeflash_tsconfig(tmpdir_path)
assert result_path.exists()
assert result_path.name == "tsconfig.codeflash.json"
# Verify contents
codeflash_tsconfig = json.loads(result_path.read_text())
assert codeflash_tsconfig["extends"] == "./tsconfig.json"
assert codeflash_tsconfig["compilerOptions"]["moduleResolution"] == "Node"
assert "include" in codeflash_tsconfig
def test_create_codeflash_jest_config(self):
"""Test creation of codeflash Jest config."""
from codeflash.languages.javascript.test_runner import _create_codeflash_jest_config
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir_path = Path(tmpdir)
# Create codeflash Jest config without original
result_path = _create_codeflash_jest_config(tmpdir_path, None)
assert result_path is not None
assert result_path.exists()
assert result_path.name == "jest.codeflash.config.js"
# Verify it contains ESM package transformation patterns
content = result_path.read_text()
assert "transformIgnorePatterns" in content
assert "node_modules" in content
def test_get_jest_config_for_project_with_bundler(self):
"""Test that bundler projects get codeflash Jest config."""
import json
from codeflash.languages.javascript.test_runner import _get_jest_config_for_project
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir_path = Path(tmpdir)
# Create tsconfig with bundler
tsconfig = {
"compilerOptions": {
"moduleResolution": "bundler",
"module": "preserve",
}
}
(tmpdir_path / "tsconfig.json").write_text(json.dumps(tsconfig))
(tmpdir_path / "package.json").write_text('{"name": "test"}')
result = _get_jest_config_for_project(tmpdir_path)
assert result is not None
assert result.name == "jest.codeflash.config.js"
# Also verify tsconfig.codeflash.json was created
assert (tmpdir_path / "tsconfig.codeflash.json").exists()
def test_get_jest_config_for_project_without_bundler(self):
"""Test that non-bundler projects use original Jest config."""
import json
from codeflash.languages.javascript.test_runner import _get_jest_config_for_project
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir_path = Path(tmpdir)
# Create tsconfig with Node moduleResolution
tsconfig = {
"compilerOptions": {
"moduleResolution": "Node",
"module": "ESNext",
}
}
(tmpdir_path / "tsconfig.json").write_text(json.dumps(tsconfig))
(tmpdir_path / "package.json").write_text('{"name": "test"}')
# Create original Jest config
(tmpdir_path / "jest.config.js").write_text("module.exports = {};")
result = _get_jest_config_for_project(tmpdir_path)
assert result is not None
assert result.name == "jest.config.js"
# Verify codeflash configs were NOT created
assert not (tmpdir_path / "jest.codeflash.config.js").exists()
assert not (tmpdir_path / "tsconfig.codeflash.json").exists()
class TestBundledJestReporter:
"""Tests for the bundled codeflash/jest-reporter.
Verifies that:
1. The reporter JS file exists in the runtime package
2. Jest commands reference 'codeflash/jest-reporter' (not jest-junit)
3. The reporter produces valid JUnit XML
4. The CODEFLASH_JEST_REPORTER constant is correct
"""
def test_reporter_js_file_exists(self):
"""The jest-reporter.js file must exist in the runtime directory."""
reporter_path = Path(__file__).resolve().parents[2] / "packages" / "codeflash" / "runtime" / "jest-reporter.js"
assert reporter_path.exists(), f"jest-reporter.js not found at {reporter_path}"
def test_reporter_constant_value(self):
"""CODEFLASH_JEST_REPORTER should be 'codeflash/jest-reporter'."""
from codeflash.languages.javascript.test_runner import CODEFLASH_JEST_REPORTER
assert CODEFLASH_JEST_REPORTER == "codeflash/jest-reporter"
def test_behavioral_command_uses_bundled_reporter(self):
"""run_jest_behavioral_tests should use codeflash/jest-reporter in --reporters flag."""
from codeflash.languages.javascript.test_runner import run_jest_behavioral_tests
from codeflash.models.models import TestFile, TestFiles
from codeflash.models.test_type import TestType
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir_path = Path(tmpdir)
(tmpdir_path / "package.json").write_text('{"name": "test"}')
test_dir = tmpdir_path / "test"
test_dir.mkdir()
test_file = test_dir / "test_func.test.js"
test_file.write_text("// test")
mock_test_files = TestFiles(
test_files=[
TestFile(
original_file_path=test_file,
instrumented_behavior_file_path=test_file,
benchmarking_file_path=test_file,
test_type=TestType.GENERATED_REGRESSION,
),
]
)
with patch("subprocess.run") as mock_run:
mock_result = MagicMock()
mock_result.stdout = ""
mock_result.stderr = ""
mock_result.returncode = 1
mock_run.return_value = mock_result
try:
run_jest_behavioral_tests(
test_paths=mock_test_files,
test_env={},
cwd=tmpdir_path,
project_root=tmpdir_path,
)
except Exception:
pass
if mock_run.called:
cmd = mock_run.call_args[0][0]
reporter_args = [a for a in cmd if "--reporters=" in a and "jest-reporter" in a]
assert len(reporter_args) == 1, f"Expected exactly one codeflash/jest-reporter flag, got: {reporter_args}"
assert reporter_args[0] == "--reporters=codeflash/jest-reporter"
# Must NOT reference jest-junit
jest_junit_args = [a for a in cmd if "jest-junit" in a]
assert len(jest_junit_args) == 0, f"Should not reference jest-junit: {jest_junit_args}"
def test_benchmarking_command_uses_bundled_reporter(self):
"""run_jest_benchmarking_tests should use codeflash/jest-reporter."""
from codeflash.languages.javascript.test_runner import run_jest_benchmarking_tests
from codeflash.models.models import TestFile, TestFiles
from codeflash.models.test_type import TestType
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir_path = Path(tmpdir)
(tmpdir_path / "package.json").write_text('{"name": "test"}')
test_dir = tmpdir_path / "test"
test_dir.mkdir()
test_file = test_dir / "test_func__perf.test.js"
test_file.write_text("// test")
mock_test_files = TestFiles(
test_files=[
TestFile(
original_file_path=test_file,
instrumented_behavior_file_path=test_file,
benchmarking_file_path=test_file,
test_type=TestType.GENERATED_REGRESSION,
),
]
)
with patch("subprocess.run") as mock_run:
mock_result = MagicMock()
mock_result.stdout = ""
mock_result.stderr = ""
mock_result.returncode = 1
mock_run.return_value = mock_result
try:
run_jest_benchmarking_tests(
test_paths=mock_test_files,
test_env={},
cwd=tmpdir_path,
project_root=tmpdir_path,
)
except Exception:
pass
if mock_run.called:
cmd = mock_run.call_args[0][0]
reporter_args = [a for a in cmd if "--reporters=codeflash/jest-reporter" in a]
assert len(reporter_args) == 1
def test_line_profile_command_uses_bundled_reporter(self):
"""run_jest_line_profile_tests should use codeflash/jest-reporter."""
from codeflash.languages.javascript.test_runner import run_jest_line_profile_tests
from codeflash.models.models import TestFile, TestFiles
from codeflash.models.test_type import TestType
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir_path = Path(tmpdir)
(tmpdir_path / "package.json").write_text('{"name": "test"}')
test_dir = tmpdir_path / "test"
test_dir.mkdir()
test_file = test_dir / "test_func__line.test.js"
test_file.write_text("// test")
mock_test_files = TestFiles(
test_files=[
TestFile(
original_file_path=test_file,
instrumented_behavior_file_path=test_file,
benchmarking_file_path=test_file,
test_type=TestType.GENERATED_REGRESSION,
),
]
)
with patch("subprocess.run") as mock_run:
mock_result = MagicMock()
mock_result.stdout = ""
mock_result.stderr = ""
mock_result.returncode = 1
mock_run.return_value = mock_result
try:
run_jest_line_profile_tests(
test_paths=mock_test_files,
test_env={},
cwd=tmpdir_path,
project_root=tmpdir_path,
)
except Exception:
pass
if mock_run.called:
cmd = mock_run.call_args[0][0]
reporter_args = [a for a in cmd if "--reporters=codeflash/jest-reporter" in a]
assert len(reporter_args) == 1
@pytest.mark.skipif(sys.platform == "win32", reason="Node.js subprocess pipe behavior unreliable on Windows CI")
def test_reporter_produces_valid_junit_xml(self):
"""The reporter JS should produce JUnit XML parseable by junitparser."""
import subprocess
reporter_path = Path(__file__).resolve().parents[2] / "packages" / "codeflash" / "runtime" / "jest-reporter.js"
with tempfile.TemporaryDirectory() as tmpdir:
output_file = Path(tmpdir) / "results.xml"
# Create a Node.js script that exercises the reporter with mock data
test_script = Path(tmpdir) / "test_reporter.js"
reporter_path_js = reporter_path.as_posix()
output_file_js = output_file.as_posix()
test_script.write_text(f"""
// Set env vars BEFORE requiring reporter (matches real Jest behavior)
process.env.JEST_JUNIT_OUTPUT_FILE = '{output_file_js}';
process.env.JEST_JUNIT_CLASSNAME = '{{filepath}}';
process.env.JEST_JUNIT_SUITE_NAME = '{{filepath}}';
process.env.JEST_JUNIT_ADD_FILE_ATTRIBUTE = 'true';
process.env.JEST_JUNIT_INCLUDE_CONSOLE_OUTPUT = 'true';
const Reporter = require('{reporter_path_js}');
// Mock Jest globalConfig
const globalConfig = {{ rootDir: '/tmp/project' }};
const reporter = new Reporter(globalConfig, {{}});
// Mock test results (matches Jest's aggregatedResults structure)
const results = {{
testResults: [
{{
testFilePath: '/tmp/project/test/math.test.js',
displayName: 'math tests',
console: [{{ type: 'log', message: 'CODEFLASH_START test1' }}],
testResults: [
{{
fullName: 'math > adds numbers',
title: 'adds numbers',
status: 'passed',
duration: 12,
}},
{{
fullName: 'math > handles failure',
title: 'handles failure',
status: 'failed',
duration: 5,
failureMessages: ['Expected 4 but got 5'],
}},
{{
fullName: 'math > skipped test',
title: 'skipped test',
status: 'pending',
duration: 0,
}},
],
}},
],
}};
// Simulate onTestFileResult for console capture
reporter.onTestFileResult(null, results.testResults[0], null);
// Simulate onRunComplete
reporter.onRunComplete([], results);
console.log('OK');
""", encoding="utf-8")
result = subprocess.run(
["node", str(test_script)],
capture_output=True,
text=True,
timeout=10,
)
assert result.returncode == 0, f"Reporter script failed: {result.stderr}"
assert output_file.exists(), "Reporter did not create output file"
xml_content = output_file.read_text()
# Verify basic XML structure
assert '<?xml version="1.0"' in xml_content
assert "<testsuites" in xml_content
assert "<testsuite" in xml_content
assert "<testcase" in xml_content
# Verify classname uses filepath template
assert 'classname="/tmp/project/test/math.test.js"' in xml_content
# Verify file attribute is present
assert 'file="/tmp/project/test/math.test.js"' in xml_content
# Verify failure element
assert "<failure" in xml_content
assert "Expected 4 but got 5" in xml_content
# Verify skipped element
assert "<skipped/>" in xml_content
# Verify system-out with console output