-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathtest_unit_test_discovery.py
More file actions
2025 lines (1620 loc) · 71.3 KB
/
test_unit_test_discovery.py
File metadata and controls
2025 lines (1620 loc) · 71.3 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
import os
import tempfile
from pathlib import Path
from codeflash.discovery.discover_unit_tests import (
analyze_imports_in_test_file,
discover_unit_tests,
filter_test_files_by_imports,
)
from codeflash.discovery.functions_to_optimize import FunctionToOptimize
from codeflash.models.models import TestsInFile, TestType, FunctionParent
from codeflash.verification.verification_utils import TestConfig
from pathlib import Path
from codeflash.discovery.discover_unit_tests import discover_unit_tests
def test_unit_test_discovery_pytest():
project_path = Path(__file__).parent.parent.resolve() / "code_to_optimize"
tests_path = project_path / "tests" / "pytest"
test_config = TestConfig(
tests_root=tests_path,
project_root_path=project_path,
test_framework="pytest",
tests_project_rootdir=tests_path.parent,
)
tests, _, _ = discover_unit_tests(test_config)
assert len(tests) > 0
def test_benchmark_test_discovery_pytest():
project_path = Path(__file__).parent.parent.resolve() / "code_to_optimize"
tests_path = project_path / "tests" / "pytest" / "benchmarks"
test_config = TestConfig(
tests_root=tests_path,
project_root_path=project_path,
test_framework="pytest",
tests_project_rootdir=tests_path.parent,
)
tests, _, _ = discover_unit_tests(test_config)
assert len(tests) == 1 # Should not discover benchmark tests
def test_unit_test_discovery_unittest():
project_path = Path(__file__).parent.parent.resolve() / "code_to_optimize"
test_path = project_path / "tests" / "unittest"
test_config = TestConfig(
tests_root=project_path,
project_root_path=project_path,
test_framework="unittest",
tests_project_rootdir=project_path.parent,
)
os.chdir(project_path)
tests, _, _ = discover_unit_tests(test_config)
# assert len(tests) > 0
# Unittest discovery within a pytest environment does not work
def test_benchmark_unit_test_discovery_pytest():
with tempfile.TemporaryDirectory() as tmpdirname:
# Create a dummy test file
test_file_path = Path(tmpdirname) / "test_dummy.py"
test_file_content = """
from bubble_sort import sorter
def test_benchmark_sort(benchmark):
benchmark(sorter, [5, 4, 3, 2, 1, 0])
def test_normal_test():
assert sorter(list(reversed(range(100)))) == list(range(100))
def test_normal_test2():
assert sorter(list(reversed(range(100)))) == list(range(100))"""
test_file_path.write_text(test_file_content)
path_obj_tempdirname = Path(tmpdirname)
# Create a file that the test file is testing
code_file_path = path_obj_tempdirname / "bubble_sort.py"
code_file_content = """
def sorter(arr):
return sorted(arr)"""
code_file_path.write_text(code_file_content)
# Create a TestConfig with the temporary directory as the root
test_config = TestConfig(
tests_root=path_obj_tempdirname,
project_root_path=path_obj_tempdirname,
test_framework="pytest",
tests_project_rootdir=path_obj_tempdirname.parent,
)
# Discover tests
tests, _, _ = discover_unit_tests(test_config)
assert len(tests) == 1
assert "bubble_sort.sorter" in tests
assert len(tests["bubble_sort.sorter"]) == 2
functions = [test.tests_in_file.test_function for test in tests["bubble_sort.sorter"]]
assert "test_normal_test" in functions
assert "test_normal_test2" in functions
assert "test_benchmark_sort" not in functions
def test_discover_tests_pytest_with_temp_dir_root():
with tempfile.TemporaryDirectory() as tmpdirname:
# Create a dummy test file
test_file_path = Path(tmpdirname) / "test_dummy.py"
test_file_content = (
"import pytest\n"
"from dummy_code import dummy_function\n\n"
"def test_dummy_function():\n"
" assert dummy_function() is True\n"
"@pytest.mark.parametrize('param', [True])\n"
"def test_dummy_parametrized_function(param):\n"
" assert dummy_function() is True\n"
)
test_file_path.write_text(test_file_content)
path_obj_tempdirname = Path(tmpdirname)
# Create a file that the test file is testing
code_file_path = path_obj_tempdirname / "dummy_code.py"
code_file_content = "def dummy_function():\n return True\n"
code_file_path.write_text(code_file_content)
# Create a TestConfig with the temporary directory as the root
test_config = TestConfig(
tests_root=path_obj_tempdirname,
project_root_path=path_obj_tempdirname,
test_framework="pytest",
tests_project_rootdir=path_obj_tempdirname.parent,
)
# Discover tests
discovered_tests, _, _ = discover_unit_tests(test_config)
# Check if the dummy test file is discovered
assert len(discovered_tests) == 1
assert len(discovered_tests["dummy_code.dummy_function"]) == 2
dummy_tests = discovered_tests["dummy_code.dummy_function"]
assert all(test.tests_in_file.test_file.resolve() == test_file_path.resolve() for test in dummy_tests)
assert {test.tests_in_file.test_function for test in dummy_tests} == {
"test_dummy_parametrized_function[True]",
"test_dummy_function",
}
def test_discover_tests_pytest_with_multi_level_dirs():
with tempfile.TemporaryDirectory() as tmpdirname:
path_obj_tmpdirname = Path(tmpdirname)
# Create multi-level directories
level1_dir = path_obj_tmpdirname / "level1"
level2_dir = level1_dir / "level2"
level2_dir.mkdir(parents=True)
# Create code files at each level
root_code_file_path = path_obj_tmpdirname / "root_code.py"
root_code_file_content = "def root_function():\n return True\n"
root_code_file_path.write_text(root_code_file_content)
level1_code_file_path = level1_dir / "level1_code.py"
level1_code_file_content = "def level1_function():\n return True\n"
level1_code_file_path.write_text(level1_code_file_content)
level2_code_file_path = level2_dir / "level2_code.py"
level2_code_file_content = "def level2_function():\n return True\n"
level2_code_file_path.write_text(level2_code_file_content)
# Create a test file at the root level
root_test_file_path = path_obj_tmpdirname / "test_root.py"
root_test_file_content = (
"from root_code import root_function\n\n"
"def test_root_function():\n"
" assert True\n"
" assert root_function() is True\n"
)
root_test_file_path.write_text(root_test_file_content)
# Create a test file at level 1
level1_test_file_path = level1_dir / "test_level1.py"
level1_test_file_content = (
"from level1_code import level1_function\n\n"
"def test_level1_function():\n"
" assert True\n"
" assert level1_function() is True\n"
)
level1_test_file_path.write_text(level1_test_file_content)
# Create a test file at level 2
level2_test_file_path = level2_dir / "test_level2.py"
level2_test_file_content = (
"from level2_code import level2_function\n\n"
"def test_level2_function():\n"
" assert True\n"
" assert level2_function() is True\n"
)
level2_test_file_path.write_text(level2_test_file_content)
# Create a TestConfig with the temporary directory as the root
test_config = TestConfig(
tests_root=path_obj_tmpdirname,
project_root_path=path_obj_tmpdirname,
test_framework="pytest",
tests_project_rootdir=path_obj_tmpdirname.parent,
)
# Discover tests
discovered_tests, _, _ = discover_unit_tests(test_config)
# Check if the test files at all levels are discovered
assert len(discovered_tests) == 3
discovered_root_test = next(iter(discovered_tests["root_code.root_function"])).tests_in_file.test_file
assert discovered_root_test.resolve() == root_test_file_path.resolve()
discovered_level1_test = next(iter(discovered_tests["level1.level1_code.level1_function"])).tests_in_file.test_file
assert discovered_level1_test.resolve() == level1_test_file_path.resolve()
discovered_level2_test = next(iter(discovered_tests["level1.level2.level2_code.level2_function"])).tests_in_file.test_file
assert discovered_level2_test.resolve() == level2_test_file_path.resolve()
def test_discover_tests_pytest_dirs():
with tempfile.TemporaryDirectory() as tmpdirname:
path_obj_tmpdirname = Path(tmpdirname)
# Create multi-level directories
level1_dir = Path(tmpdirname) / "level1"
level2_dir = level1_dir / "level2"
level2_dir.mkdir(parents=True)
level3_dir = level1_dir / "level3"
level3_dir.mkdir(parents=True)
# Create code files at each level
root_code_file_path = path_obj_tmpdirname / "root_code.py"
root_code_file_content = "def root_function():\n return True\n"
root_code_file_path.write_text(root_code_file_content)
level1_code_file_path = level1_dir / "level1_code.py"
level1_code_file_content = "def level1_function():\n return True\n"
level1_code_file_path.write_text(level1_code_file_content)
level2_code_file_path = level2_dir / "level2_code.py"
level2_code_file_content = "def level2_function():\n return True\n"
level2_code_file_path.write_text(level2_code_file_content)
level3_code_file_path = level3_dir / "level3_code.py"
level3_code_file_content = "def level3_function():\n return True\n"
level3_code_file_path.write_text(level3_code_file_content)
# Create a test file at the root level
root_test_file_path = path_obj_tmpdirname / "test_root.py"
root_test_file_content = (
"from root_code import root_function\n\n"
"def test_root_function():\n"
" assert True\n"
" assert root_function() is True\n"
)
root_test_file_path.write_text(root_test_file_content)
# Create a test file at level 1
level1_test_file_path = level1_dir / "test_level1.py"
level1_test_file_content = (
"from level1_code import level1_function\n\n"
"def test_level1_function():\n"
" assert True\n"
" assert level1_function() is True\n"
)
level1_test_file_path.write_text(level1_test_file_content)
# Create a test file at level 2
level2_test_file_path = level2_dir / "test_level2.py"
level2_test_file_content = (
"from level2_code import level2_function\n\n"
"def test_level2_function():\n"
" assert True\n"
" assert level2_function() is True\n"
)
level2_test_file_path.write_text(level2_test_file_content)
level3_test_file_path = level3_dir / "test_level3.py"
level3_test_file_content = (
"from level3_code import level3_function\n\n"
"def test_level3_function():\n"
" assert True\n"
" assert level3_function() is True\n"
)
level3_test_file_path.write_text(level3_test_file_content)
# Create a TestConfig with the temporary directory as the root
test_config = TestConfig(
tests_root=path_obj_tmpdirname,
project_root_path=path_obj_tmpdirname,
test_framework="pytest",
tests_project_rootdir=path_obj_tmpdirname.parent,
)
# Discover tests
discovered_tests, _, _ = discover_unit_tests(test_config)
# Check if the test files at all levels are discovered
assert len(discovered_tests) == 4
discovered_root_test = next(iter(discovered_tests["root_code.root_function"])).tests_in_file.test_file
assert discovered_root_test.resolve() == root_test_file_path.resolve()
discovered_level1_test = next(iter(discovered_tests["level1.level1_code.level1_function"])).tests_in_file.test_file
assert discovered_level1_test.resolve() == level1_test_file_path.resolve()
discovered_level2_test = next(iter(discovered_tests["level1.level2.level2_code.level2_function"])).tests_in_file.test_file
assert discovered_level2_test.resolve() == level2_test_file_path.resolve()
discovered_level3_test = next(iter(discovered_tests["level1.level3.level3_code.level3_function"])).tests_in_file.test_file
assert discovered_level3_test.resolve() == level3_test_file_path.resolve()
def test_discover_tests_pytest_with_class():
with tempfile.TemporaryDirectory() as tmpdirname:
path_obj_tmpdirname = Path(tmpdirname)
# Create a code file with a class
code_file_path = path_obj_tmpdirname / "some_class_code.py"
code_file_content = "class SomeClass:\n def some_method(self):\n return True\n"
code_file_path.write_text(code_file_content)
# Create a test file with a test class and a test method
test_file_path = path_obj_tmpdirname / "test_some_class.py"
test_file_content = (
"from some_class_code import SomeClass\n\n"
"def test_some_method():\n"
" instance = SomeClass()\n"
" assert instance.some_method() is True\n"
)
test_file_path.write_text(test_file_content)
# Create a TestConfig with the temporary directory as the root
test_config = TestConfig(
tests_root=path_obj_tmpdirname,
project_root_path=path_obj_tmpdirname,
test_framework="pytest",
tests_project_rootdir=path_obj_tmpdirname.parent,
)
# Discover tests
discovered_tests, _, _ = discover_unit_tests(test_config)
# Check if the test class and method are discovered
assert len(discovered_tests) == 1
discovered_class_test = next(iter(discovered_tests["some_class_code.SomeClass.some_method"])).tests_in_file.test_file
assert discovered_class_test.resolve() == test_file_path.resolve()
def test_discover_tests_pytest_with_double_nested_directories():
with tempfile.TemporaryDirectory() as tmpdirname:
path_obj_tmpdirname = Path(tmpdirname)
# Create nested directories
nested_dir = path_obj_tmpdirname / "nested" / "more_nested"
nested_dir.mkdir(parents=True)
# Create a code file with a class in the nested directory
code_file_path = nested_dir / "nested_class_code.py"
code_file_content = "class NestedClass:\n def nested_method(self):\n return True\n"
code_file_path.write_text(code_file_content)
# Create a test file with a test class and a test method in the nested directory
test_file_path = nested_dir / "test_nested_class.py"
test_file_content = (
"from nested_class_code import NestedClass\n\n"
"def test_nested_method():\n"
" instance = NestedClass()\n"
" assert instance.nested_method() is True\n"
)
test_file_path.write_text(test_file_content)
# Create a TestConfig with the temporary directory as the root
test_config = TestConfig(
tests_root=path_obj_tmpdirname,
project_root_path=path_obj_tmpdirname,
test_framework="pytest",
tests_project_rootdir=path_obj_tmpdirname.parent,
)
# Discover tests
discovered_tests, _, _ = discover_unit_tests(test_config)
# Check if the test class and method are discovered
assert len(discovered_tests) == 1
discovered_nested_test = next(
iter(discovered_tests["nested.more_nested.nested_class_code.NestedClass.nested_method"])
).tests_in_file.test_file
assert discovered_nested_test.resolve() == test_file_path.resolve()
def test_discover_tests_with_code_in_dir_and_test_in_subdir():
with tempfile.TemporaryDirectory() as tmpdirname:
path_obj_tmpdirname = Path(tmpdirname)
# Create a directory for the code file
code_dir = path_obj_tmpdirname / "code"
code_dir.mkdir()
# Create a code file in the code directory
code_file_path = code_dir / "some_code.py"
code_file_content = "def some_function():\n return True\n"
code_file_path.write_text(code_file_content)
# Create a subdirectory for the test file within the code directory
test_subdir = code_dir / "tests"
test_subdir.mkdir()
# Create a test file in the test subdirectory
test_file_path = test_subdir / "test_some_code.py"
test_file_content = (
"import sys\n"
"import os\n"
# I am suspicious of this line, we should not need to insert the code directory into the path
"sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))\n"
"from some_code import some_function\n\n"
"def test_some_function():\n"
" assert some_function() is True\n"
)
test_file_path.write_text(test_file_content)
# Create a TestConfig with the code directory as the root
test_config = TestConfig(
tests_root=test_subdir,
project_root_path=path_obj_tmpdirname,
test_framework="pytest",
tests_project_rootdir=test_subdir.parent,
)
# Discover tests
discovered_tests, _, _ = discover_unit_tests(test_config)
# Check if the test file is discovered and associated with the code file
assert len(discovered_tests) == 1
discovered_test_file = next(iter(discovered_tests["code.some_code.some_function"])).tests_in_file.test_file
assert discovered_test_file.resolve() == test_file_path.resolve()
def test_discover_tests_pytest_with_nested_class():
with tempfile.TemporaryDirectory() as tmpdirname:
path_obj_tmpdirname = Path(tmpdirname)
# Create a code file with a nested class
code_file_path = path_obj_tmpdirname / "nested_class_code.py"
code_file_content = (
"class OuterClass:\n class InnerClass:\n def inner_method(self):\n return True\n"
)
code_file_path.write_text(code_file_content)
# Create a test file with a test for the nested class method
test_file_path = path_obj_tmpdirname / "test_nested_class.py"
test_file_content = (
"from nested_class_code import OuterClass\n\n"
"def test_inner_method():\n"
" instance = OuterClass.InnerClass()\n"
" assert instance.inner_method() is True\n"
)
test_file_path.write_text(test_file_content)
# Create a TestConfig with the temporary directory as the root
test_config = TestConfig(
tests_root=path_obj_tmpdirname,
project_root_path=path_obj_tmpdirname,
test_framework="pytest",
tests_project_rootdir=path_obj_tmpdirname.parent,
)
# Discover tests
discovered_tests, _, _ = discover_unit_tests(test_config)
# Check if the test for the nested class method is discovered
assert len(discovered_tests) == 1
discovered_inner_test = next(iter(discovered_tests["nested_class_code.OuterClass.InnerClass.inner_method"])).tests_in_file.test_file
assert discovered_inner_test.resolve() == test_file_path.resolve()
def test_discover_tests_pytest_separate_moduledir():
with tempfile.TemporaryDirectory() as tmpdirname:
rootdir = Path(tmpdirname)
# Create a code file with a nested class
codedir = rootdir / "src" / "mypackage"
codedir.mkdir(parents=True)
code_file_path = codedir / "code.py"
code_file_content = "def find_common_tags(articles):\n if not articles:\n return set()\n"
code_file_path.write_text(code_file_content)
# Create a test file with a test for the nested class method
testdir = rootdir / "tests"
testdir.mkdir()
test_file_path = testdir / "test_code.py"
test_file_content = (
"from mypackage.code import find_common_tags\n\n"
"def test_common_tags():\n"
" assert find_common_tags(None) == set()\n"
)
test_file_path.write_text(test_file_content)
# Create a TestConfig with the temporary directory as the root
test_config = TestConfig(
tests_root=testdir,
project_root_path=codedir.parent.resolve(),
test_framework="pytest",
tests_project_rootdir=testdir.parent,
)
# Discover tests
discovered_tests, _, _ = discover_unit_tests(test_config)
# Check if the test for the nested class method is discovered
assert len(discovered_tests) == 1
discovered_test_file = next(iter(discovered_tests["mypackage.code.find_common_tags"])).tests_in_file.test_file
assert discovered_test_file.resolve() == test_file_path.resolve()
def test_unittest_discovery_with_pytest():
with tempfile.TemporaryDirectory() as tmpdirname:
path_obj_tmpdirname = Path(tmpdirname)
# Create a simple code file
code_file_path = path_obj_tmpdirname / "calculator.py"
code_file_content = """
class Calculator:
def add(self, a, b):
return a + b
"""
code_file_path.write_text(code_file_content)
# Create a unittest test file
test_file_path = path_obj_tmpdirname / "test_calculator.py"
test_file_content = """
import unittest
from calculator import Calculator
class TestCalculator(unittest.TestCase):
def test_add(self):
calc = Calculator()
self.assertEqual(calc.add(2, 2), 4)
"""
test_file_path.write_text(test_file_content)
# Configure test discovery
test_config = TestConfig(
tests_root=path_obj_tmpdirname,
project_root_path=path_obj_tmpdirname,
test_framework="pytest", # Using pytest framework to discover unittest tests
tests_project_rootdir=path_obj_tmpdirname.parent,
)
# Discover tests
discovered_tests, _, _ = discover_unit_tests(test_config)
# Verify the unittest was discovered
assert len(discovered_tests) == 1
assert "calculator.Calculator.add" in discovered_tests
assert len(discovered_tests["calculator.Calculator.add"]) == 1
calculator_test = next(iter(discovered_tests["calculator.Calculator.add"]))
assert calculator_test.tests_in_file.test_file.resolve() == test_file_path.resolve()
assert calculator_test.tests_in_file.test_function == "test_add"
def test_unittest_discovery_with_pytest_parent_class():
with tempfile.TemporaryDirectory() as tmpdirname:
path_obj_tmpdirname = Path(tmpdirname)
# Create a simple code file
code_file_path = path_obj_tmpdirname / "calculator.py"
code_file_content = """
class Calculator:
def add(self, a, b):
return a + b
"""
code_file_path.write_text(code_file_content)
# Create a base test class file
base_test_file_path = path_obj_tmpdirname / "base_test.py"
base_test_content = """
import unittest
class BaseTestCase(unittest.TestCase):
def setUp(self):
self.setup_called = True
def tearDown(self):
self.setup_called = False
def assert_setup_called(self):
self.assertTrue(self.setup_called, "Setup was not called")
"""
base_test_file_path.write_text(base_test_content)
# Create a unittest test file that extends the base test
test_file_path = path_obj_tmpdirname / "test_calculator.py"
test_file_content = """
from base_test import BaseTestCase
from calculator import Calculator
class ExtendedTestCase(BaseTestCase):
def setUp(self):
super().setUp()
self.calc = Calculator()
class TestCalculator(ExtendedTestCase):
def test_add(self):
self.assert_setup_called()
self.assertEqual(self.calc.add(2, 2), 4)
"""
test_file_path.write_text(test_file_content)
# Configure test discovery
test_config = TestConfig(
tests_root=path_obj_tmpdirname,
project_root_path=path_obj_tmpdirname,
test_framework="pytest", # Using pytest framework to discover unittest tests
tests_project_rootdir=path_obj_tmpdirname.parent,
)
# Discover tests
discovered_tests, _, _ = discover_unit_tests(test_config)
# Verify the unittest was discovered
assert len(discovered_tests) == 2
assert "calculator.Calculator.add" in discovered_tests
assert len(discovered_tests["calculator.Calculator.add"]) == 1
calculator_test = next(iter(discovered_tests["calculator.Calculator.add"]))
assert calculator_test.tests_in_file.test_file.resolve() == test_file_path.resolve()
assert calculator_test.tests_in_file.test_function == "test_add"
def test_unittest_discovery_with_pytest_private():
with tempfile.TemporaryDirectory() as tmpdirname:
path_obj_tmpdirname = Path(tmpdirname)
# Create a simple code file
code_file_path = path_obj_tmpdirname / "calculator.py"
code_file_content = """
class Calculator:
def add(self, a, b):
return a + b
"""
code_file_path.write_text(code_file_content)
# Create a unittest test file with a private test method (prefixed with _)
test_file_path = path_obj_tmpdirname / "test_calculator.py"
test_file_content = """
import unittest
from calculator import Calculator
class TestCalculator(unittest.TestCase):
def _test_add(self): # Private test method should not be discovered
calc = Calculator()
self.assertEqual(calc.add(2, 2), 4)
"""
test_file_path.write_text(test_file_content)
# Configure test discovery
test_config = TestConfig(
tests_root=path_obj_tmpdirname,
project_root_path=path_obj_tmpdirname,
test_framework="pytest", # Using pytest framework to discover unittest tests
tests_project_rootdir=path_obj_tmpdirname.parent,
)
# Discover tests
discovered_tests, _, _ = discover_unit_tests(test_config)
# Verify no tests were discovered
assert len(discovered_tests) == 0
assert "calculator.Calculator.add" not in discovered_tests
def test_unittest_discovery_with_pytest_subtest():
with tempfile.TemporaryDirectory() as tmpdirname:
path_obj_tmpdirname = Path(tmpdirname)
# Create a simple code file
code_file_path = path_obj_tmpdirname / "calculator.py"
code_file_content = """
class Calculator:
def add(self, a, b):
return a + b
"""
code_file_path.write_text(code_file_content)
# Create a unittest test file with parameterized tests
test_file_path = path_obj_tmpdirname / "test_calculator.py"
test_file_content = """
import unittest
from calculator import Calculator
class TestCalculator(unittest.TestCase):
def test_add_with_parameters(self):
calc = Calculator()
test_cases = [
{"a": 2, "b": 2, "expected": 4},
{"a": 0, "b": 0, "expected": 0},
{"a": -1, "b": 1, "expected": 0},
{"a": 10, "b": -5, "expected": 5}
]
for case in test_cases:
with self.subTest(a=case["a"], b=case["b"]):
result = calc.add(case["a"], case["b"])
self.assertEqual(result, case["expected"])
"""
test_file_path.write_text(test_file_content)
# Configure test discovery
test_config = TestConfig(
tests_root=path_obj_tmpdirname,
project_root_path=path_obj_tmpdirname,
test_framework="pytest", # Using pytest framework to discover unittest tests
tests_project_rootdir=path_obj_tmpdirname.parent,
)
# Discover tests
discovered_tests, _, _ = discover_unit_tests(test_config)
# Verify the unittest was discovered
assert len(discovered_tests) == 1
assert "calculator.Calculator.add" in discovered_tests
assert len(discovered_tests["calculator.Calculator.add"]) == 1
calculator_test = next(iter(discovered_tests["calculator.Calculator.add"]))
assert calculator_test.tests_in_file.test_file.resolve() == test_file_path.resolve()
assert calculator_test.tests_in_file.test_function == "test_add_with_parameters"
def test_unittest_discovery_with_pytest_fixture():
with tempfile.TemporaryDirectory() as tmpdirname:
path_obj_tmpdirname = Path(tmpdirname)
# Create a simple code file
code_file_path = path_obj_tmpdirname / "topological_sort.py"
code_file_content = """
import uuid
from collections import defaultdict
class Graph:
def __init__(self, vertices: int):
self.vertices=vertices
def dummy_fn(self):
return 1
def topologicalSort(self):
return self.vertices
"""
code_file_path.write_text(code_file_content)
# Create a unittest test file with parameterized tests
test_file_path = path_obj_tmpdirname / "test_topological_sort.py"
test_file_content = """
from topological_sort import Graph
import pytest
@pytest.fixture
def g():
return Graph(6)
def test_topological_sort(g):
assert g.dummy_fn() == 1
assert g.topologicalSort() == 6
"""
test_file_path.write_text(test_file_content)
# Configure test discovery
test_config = TestConfig(
tests_root=path_obj_tmpdirname,
project_root_path=path_obj_tmpdirname,
test_framework="pytest", # Using pytest framework to discover unittest tests
tests_project_rootdir=path_obj_tmpdirname.parent,
)
fto = FunctionToOptimize(function_name="topologicalSort", file_path=code_file_path, parents=[FunctionParent(name="Graph", type="ClassDef")])
# Discover tests
discovered_tests, _, _ = discover_unit_tests(test_config, file_to_funcs_to_optimize={code_file_path: [fto]})
# Verify the unittest was discovered
assert len(discovered_tests) == 2
assert "topological_sort.Graph.topologicalSort" in discovered_tests
assert len(discovered_tests["topological_sort.Graph.topologicalSort"]) == 1
tpsort_test = next(iter(discovered_tests["topological_sort.Graph.topologicalSort"]))
assert tpsort_test.tests_in_file.test_file.resolve() == test_file_path.resolve()
assert tpsort_test.tests_in_file.test_function == "test_topological_sort"
def test_unittest_discovery_with_pytest_class_fixture():
with tempfile.TemporaryDirectory() as tmpdirname:
path_obj_tmpdirname = Path(tmpdirname)
# Create a simple code file
code_file_path = path_obj_tmpdirname / "router_file.py"
code_file_content = """
from __future__ import annotations
import hashlib
import json
class Router:
model_names: list
cache_responses = False
tenacity = None
def __init__( # noqa: PLR0915
self,
model_list = None,
) -> None:
self.model_list = model_list
self.model_id_to_deployment_index_map = {}
self.model_name_to_deployment_indices = {}
def _generate_model_id(self, model_group, litellm_params):
# Optimized: Use list and join instead of string concatenation in loop
# This avoids creating many temporary string objects (O(n) vs O(n²) complexity)
parts = [model_group]
for k, v in litellm_params.items():
if isinstance(k, str):
parts.append(k)
elif isinstance(k, dict):
parts.append(json.dumps(k))
else:
parts.append(str(k))
if isinstance(v, str):
parts.append(v)
elif isinstance(v, dict):
parts.append(json.dumps(v))
else:
parts.append(str(v))
concat_str = "".join(parts)
hash_object = hashlib.sha256(concat_str.encode())
return hash_object.hexdigest()
def _add_model_to_list_and_index_map(
self, model, model_id = None
) -> None:
idx = len(self.model_list)
self.model_list.append(model)
# Update model_id index for O(1) lookup
if model_id is not None:
self.model_id_to_deployment_index_map[model_id] = idx
elif model.get("model_info", {}).get("id") is not None:
self.model_id_to_deployment_index_map[model["model_info"]["id"]] = idx
# Update model_name index for O(1) lookup
model_name = model.get("model_name")
if model_name:
if model_name not in self.model_name_to_deployment_indices:
self.model_name_to_deployment_indices[model_name] = []
self.model_name_to_deployment_indices[model_name].append(idx)
def _build_model_id_to_deployment_index_map(self, model_list):
# First populate the model_list
self.model_list = []
for _, model in enumerate(model_list):
# Extract model_info from the model dict
model_info = model.get("model_info", {})
model_id = model_info.get("id")
# If no ID exists, generate one using the same logic as set_model_list
if model_id is None:
model_name = model.get("model_name", "")
litellm_params = model.get("litellm_params", {})
model_id = self._generate_model_id(model_name, litellm_params)
# Update the model_info in the original list
if "model_info" not in model:
model["model_info"] = {}
model["model_info"]["id"] = model_id
self._add_model_to_list_and_index_map(model=model, model_id=model_id)
"""
code_file_path.write_text(code_file_content)
# Create a unittest test file with parameterized tests
test_file_path = path_obj_tmpdirname / "test_router_file.py"
test_file_content = """
import pytest
from router_file import Router
class TestRouterIndexManagement:
@pytest.fixture
def router(self):
return Router(model_list=[])
def test_build_model_id_to_deployment_index_map(self, router):
model_list = [
{
"model_name": "gpt-3.5-turbo",
"litellm_params": {"model": "gpt-3.5-turbo"},
"model_info": {"id": "model-1"},
},
{
"model_name": "gpt-4",
"litellm_params": {"model": "gpt-4"},
"model_info": {"id": "model-2"},
},
]
# Test: Build index from model list
router._build_model_id_to_deployment_index_map(model_list)
# Verify: model_list is populated
assert len(router.model_list) == 2
# Verify: model_id_to_deployment_index_map is correctly built
assert router.model_id_to_deployment_index_map["model-1"] == 0
assert router.model_id_to_deployment_index_map["model-2"] == 1
"""
test_file_path.write_text(test_file_content)
# Configure test discovery
test_config = TestConfig(
tests_root=path_obj_tmpdirname,
project_root_path=path_obj_tmpdirname,
test_framework="pytest", # Using pytest framework to discover unittest tests
tests_project_rootdir=path_obj_tmpdirname.parent,
)
fto = FunctionToOptimize(function_name="_build_model_id_to_deployment_index_map", file_path=code_file_path, parents=[FunctionParent(name="Router", type="ClassDef")])
# Discover tests
discovered_tests, _, _ = discover_unit_tests(test_config, file_to_funcs_to_optimize={code_file_path: [fto]})
# Verify the unittest was discovered
assert len(discovered_tests) == 1
assert "router_file.Router._build_model_id_to_deployment_index_map" in discovered_tests
assert len(discovered_tests["router_file.Router._build_model_id_to_deployment_index_map"]) == 1
router_test = next(iter(discovered_tests["router_file.Router._build_model_id_to_deployment_index_map"]))
assert router_test.tests_in_file.test_file.resolve() == test_file_path.resolve()
assert router_test.tests_in_file.test_function == "test_build_model_id_to_deployment_index_map"
def test_unittest_discovery_with_pytest_parameterized():
with tempfile.TemporaryDirectory() as tmpdirname:
path_obj_tmpdirname = Path(tmpdirname)
# Create a simple code file
code_file_path = path_obj_tmpdirname / "calculator.py"
code_file_content = """
class Calculator:
def add(self, a, b):
return a + b
def multiply(self, a, b):
return a * b
"""
code_file_path.write_text(code_file_content)
# Create a unittest test file with different parameterized patterns
test_file_path = path_obj_tmpdirname / "test_calculator.py"
test_file_content = """
import unittest
from parameterized import parameterized
from calculator import Calculator
class TestCalculator(unittest.TestCase):
# Test with named parameters
@parameterized.expand([
("positive_numbers", 2, 2, 4),
("zeros", 0, 0, 0),
("negative_and_positive", -1, 1, 0),
("negative_result", 10, -15, -5),
])
def test_add(self, name, a, b, expected):
calc = Calculator()
result = calc.add(a, b)
self.assertEqual(result, expected)
# Test with unnamed parameters
@parameterized.expand([
(2, 3, 6),
(0, 5, 0),
(-2, 3, -6),
])
def test_multiply(self, a, b, expected):
calc = Calculator()
result = calc.multiply(a, b)
self.assertEqual(result, expected)
# Test with mixed naming patterns
@parameterized.expand([
("test with spaces", 1, 1, 2),
("test_with_underscores", 2, 2, 4),
("test.with.dots", 3, 3, 6),
("test-with-hyphens", 4, 4, 8),
])
def test_add_mixed(self, name, a, b, expected):
calc = Calculator()
result = calc.add(a, b)
self.assertEqual(result, expected)
"""
test_file_path.write_text(test_file_content)
# Configure test discovery
test_config = TestConfig(
tests_root=path_obj_tmpdirname,
project_root_path=path_obj_tmpdirname,
test_framework="pytest",
tests_project_rootdir=path_obj_tmpdirname.parent,
)
# Discover tests
discovered_tests, _, _ = discover_unit_tests(test_config)
# Verify the basic structure
assert len(discovered_tests) == 2 # Should have tests for both add and multiply
assert "calculator.Calculator.add" in discovered_tests
assert "calculator.Calculator.multiply" in discovered_tests
# Import Filtering Tests