-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathtest_instrument_line_profiler.py
More file actions
1063 lines (873 loc) · 26.4 KB
/
test_instrument_line_profiler.py
File metadata and controls
1063 lines (873 loc) · 26.4 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
from pathlib import Path
from tempfile import TemporaryDirectory
from codeflash.languages.python.static_analysis.line_profile_utils import add_decorator_imports, contains_jit_decorator
from codeflash.discovery.functions_to_optimize import FunctionToOptimize
from codeflash.models.models import CodeOptimizationContext
from codeflash.languages.python.function_optimizer import PythonFunctionOptimizer
from codeflash.verification.verification_utils import TestConfig
def test_add_decorator_imports_helper_in_class():
code_path = (Path(__file__).parent.resolve() / "../code_to_optimize/bubble_sort_classmethod.py").resolve()
tests_root = Path(__file__).parent.resolve() / "../code_to_optimize/tests/pytest/"
project_root_path = (Path(__file__).parent / "..").resolve()
run_cwd = Path(__file__).parent.parent.resolve()
test_config = TestConfig(
tests_root=tests_root,
tests_project_rootdir=project_root_path,
project_root_path=project_root_path,
test_framework="pytest",
pytest_cmd="pytest",
)
func = FunctionToOptimize(function_name="sort_classmethod", parents=[], file_path=code_path)
func_optimizer = PythonFunctionOptimizer(function_to_optimize=func, test_cfg=test_config)
os.chdir(run_cwd)
# func_optimizer = pass
try:
ctx_result = func_optimizer.get_code_optimization_context()
code_context: CodeOptimizationContext = ctx_result.unwrap()
original_helper_code: dict[Path, str] = {}
helper_function_paths = {hf.file_path for hf in code_context.helper_functions}
for helper_function_path in helper_function_paths:
with helper_function_path.open(encoding="utf8") as f:
helper_code = f.read()
original_helper_code[helper_function_path] = helper_code
line_profiler_output_file = add_decorator_imports(func_optimizer.function_to_optimize, code_context)
expected_code_main = f"""from line_profiler import profile as codeflash_line_profile
codeflash_line_profile.enable(output_prefix='{line_profiler_output_file.as_posix()}')
from code_to_optimize.bubble_sort_in_class import BubbleSortClass
@codeflash_line_profile
def sort_classmethod(x):
y = BubbleSortClass()
return y.sorter(x)
"""
expected_code_helper = """from line_profiler import profile as codeflash_line_profile
def hi():
pass
class BubbleSortClass:
@codeflash_line_profile
def __init__(self):
pass
@codeflash_line_profile
def sorter(self, arr):
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
def helper(self, arr, j):
return arr[j] > arr[j + 1]
"""
assert code_path.read_text("utf-8") == expected_code_main
assert code_context.helper_functions[0].file_path.read_text("utf-8") == expected_code_helper
finally:
func_optimizer.write_code_and_helpers(
func_optimizer.function_to_optimize_source_code,
original_helper_code,
func_optimizer.function_to_optimize.file_path,
)
def test_add_decorator_imports_helper_in_nested_class():
# Need to invert the assert once the helper detection is fixed
code_path = (Path(__file__).parent.resolve() / "../code_to_optimize/bubble_sort_nested_classmethod.py").resolve()
tests_root = Path(__file__).parent.resolve() / "../code_to_optimize/tests/pytest/"
project_root_path = (Path(__file__).parent / "..").resolve()
run_cwd = Path(__file__).parent.parent.resolve()
test_config = TestConfig(
tests_root=tests_root,
tests_project_rootdir=project_root_path,
project_root_path=project_root_path,
test_framework="pytest",
pytest_cmd="pytest",
)
func = FunctionToOptimize(function_name="sort_classmethod", parents=[], file_path=code_path)
func_optimizer = PythonFunctionOptimizer(function_to_optimize=func, test_cfg=test_config)
os.chdir(run_cwd)
# func_optimizer = pass
try:
ctx_result = func_optimizer.get_code_optimization_context()
code_context: CodeOptimizationContext = ctx_result.unwrap()
original_helper_code: dict[Path, str] = {}
helper_function_paths = {hf.file_path for hf in code_context.helper_functions}
for helper_function_path in helper_function_paths:
with helper_function_path.open(encoding="utf8") as f:
helper_code = f.read()
original_helper_code[helper_function_path] = helper_code
line_profiler_output_file = add_decorator_imports(func_optimizer.function_to_optimize, code_context)
expected_code_main = f"""from line_profiler import profile as codeflash_line_profile
codeflash_line_profile.enable(output_prefix='{line_profiler_output_file.as_posix()}')
from code_to_optimize.bubble_sort_in_nested_class import WrapperClass
@codeflash_line_profile
def sort_classmethod(x):
y = WrapperClass.BubbleSortClass()
return y.sorter(x)
"""
assert code_path.read_text("utf-8") == expected_code_main
# WrapperClass.__init__ is now detected as a helper since WrapperClass.BubbleSortClass() instantiates it
assert len(code_context.helper_functions) == 1
assert code_context.helper_functions[0].qualified_name == "WrapperClass.__init__"
finally:
func_optimizer.write_code_and_helpers(
func_optimizer.function_to_optimize_source_code,
original_helper_code,
func_optimizer.function_to_optimize.file_path,
)
def test_add_decorator_imports_nodeps():
code_path = (Path(__file__).parent.resolve() / "../code_to_optimize/bubble_sort.py").resolve()
tests_root = Path(__file__).parent.resolve() / "../code_to_optimize/tests/pytest/"
project_root_path = (Path(__file__).parent / "..").resolve()
run_cwd = Path(__file__).parent.parent.resolve()
test_config = TestConfig(
tests_root=tests_root,
tests_project_rootdir=project_root_path,
project_root_path=project_root_path,
test_framework="pytest",
pytest_cmd="pytest",
)
func = FunctionToOptimize(function_name="sorter", parents=[], file_path=code_path)
func_optimizer = PythonFunctionOptimizer(function_to_optimize=func, test_cfg=test_config)
os.chdir(run_cwd)
# func_optimizer = pass
try:
ctx_result = func_optimizer.get_code_optimization_context()
code_context: CodeOptimizationContext = ctx_result.unwrap()
original_helper_code: dict[Path, str] = {}
helper_function_paths = {hf.file_path for hf in code_context.helper_functions}
for helper_function_path in helper_function_paths:
with helper_function_path.open(encoding="utf8") as f:
helper_code = f.read()
original_helper_code[helper_function_path] = helper_code
line_profiler_output_file = add_decorator_imports(func_optimizer.function_to_optimize, code_context)
expected_code_main = f"""from line_profiler import profile as codeflash_line_profile
codeflash_line_profile.enable(output_prefix='{line_profiler_output_file.as_posix()}')
@codeflash_line_profile
def sorter(arr):
print("codeflash stdout: Sorting list")
for i in range(len(arr)):
for j in range(len(arr) - 1):
if arr[j] > arr[j + 1]:
temp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = temp
print(f"result: {{arr}}")
return arr
"""
assert code_path.read_text("utf-8") == expected_code_main
finally:
func_optimizer.write_code_and_helpers(
func_optimizer.function_to_optimize_source_code,
original_helper_code,
func_optimizer.function_to_optimize.file_path,
)
def test_add_decorator_imports_helper_outside():
code_path = (Path(__file__).parent.resolve() / "../code_to_optimize/bubble_sort_deps.py").resolve()
tests_root = Path(__file__).parent.resolve() / "../code_to_optimize/tests/pytest/"
project_root_path = (Path(__file__).parent / "..").resolve()
run_cwd = Path(__file__).parent.parent.resolve()
test_config = TestConfig(
tests_root=tests_root,
tests_project_rootdir=project_root_path,
project_root_path=project_root_path,
test_framework="pytest",
pytest_cmd="pytest",
)
func = FunctionToOptimize(function_name="sorter_deps", parents=[], file_path=code_path)
func_optimizer = PythonFunctionOptimizer(function_to_optimize=func, test_cfg=test_config)
os.chdir(run_cwd)
# func_optimizer = pass
try:
ctx_result = func_optimizer.get_code_optimization_context()
code_context: CodeOptimizationContext = ctx_result.unwrap()
original_helper_code: dict[Path, str] = {}
helper_function_paths = {hf.file_path for hf in code_context.helper_functions}
for helper_function_path in helper_function_paths:
with helper_function_path.open(encoding="utf8") as f:
helper_code = f.read()
original_helper_code[helper_function_path] = helper_code
line_profiler_output_file = add_decorator_imports(func_optimizer.function_to_optimize, code_context)
expected_code_main = f"""from line_profiler import profile as codeflash_line_profile
codeflash_line_profile.enable(output_prefix='{line_profiler_output_file.as_posix()}')
from code_to_optimize.bubble_sort_dep1_helper import dep1_comparer
from code_to_optimize.bubble_sort_dep2_swap import dep2_swap
@codeflash_line_profile
def sorter_deps(arr):
for i in range(len(arr)):
for j in range(len(arr) - 1):
if dep1_comparer(arr, j):
dep2_swap(arr, j)
return arr
"""
expected_code_helper1 = """from line_profiler import profile as codeflash_line_profile
@codeflash_line_profile
def dep1_comparer(arr, j: int) -> bool:
return arr[j] > arr[j + 1]
"""
expected_code_helper2 = """from line_profiler import profile as codeflash_line_profile
@codeflash_line_profile
def dep2_swap(arr, j):
temp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = temp
"""
assert code_path.read_text("utf-8") == expected_code_main
assert code_context.helper_functions[0].file_path.read_text("utf-8") == expected_code_helper1
assert code_context.helper_functions[1].file_path.read_text("utf-8") == expected_code_helper2
finally:
func_optimizer.write_code_and_helpers(
func_optimizer.function_to_optimize_source_code,
original_helper_code,
func_optimizer.function_to_optimize.file_path,
)
def test_add_decorator_imports_helper_in_dunder_class():
code_str = """def sorter(arr):
ans = helper(arr)
return ans
class helper:
def __init__(self, arr):
return arr.sort()"""
code_path = TemporaryDirectory()
code_write_path = Path(code_path.name) / "dunder_class.py"
code_write_path.write_text(code_str, "utf-8")
tests_root = Path(__file__).parent.resolve() / "../code_to_optimize/tests/pytest/"
project_root_path = Path(code_path.name)
run_cwd = Path(__file__).parent.parent.resolve()
test_config = TestConfig(
tests_root=tests_root,
tests_project_rootdir=project_root_path,
project_root_path=project_root_path,
test_framework="pytest",
pytest_cmd="pytest",
)
func = FunctionToOptimize(function_name="sorter", parents=[], file_path=code_write_path)
func_optimizer = PythonFunctionOptimizer(function_to_optimize=func, test_cfg=test_config)
os.chdir(run_cwd)
# func_optimizer = pass
try:
ctx_result = func_optimizer.get_code_optimization_context()
code_context: CodeOptimizationContext = ctx_result.unwrap()
original_helper_code: dict[Path, str] = {}
helper_function_paths = {hf.file_path for hf in code_context.helper_functions}
for helper_function_path in helper_function_paths:
with helper_function_path.open(encoding="utf8") as f:
helper_code = f.read()
original_helper_code[helper_function_path] = helper_code
line_profiler_output_file = add_decorator_imports(func_optimizer.function_to_optimize, code_context)
expected_code_main = f"""from line_profiler import profile as codeflash_line_profile
codeflash_line_profile.enable(output_prefix='{line_profiler_output_file.as_posix()}')
@codeflash_line_profile
def sorter(arr):
ans = helper(arr)
return ans
class helper:
@codeflash_line_profile
def __init__(self, arr):
return arr.sort()
"""
assert code_write_path.read_text("utf-8") == expected_code_main
finally:
pass
# ============================================================================
# Tests for contains_jit_decorator
# ============================================================================
class TestContainsJitDecoratorNumba:
"""Tests for numba JIT decorator detection."""
def test_numba_jit_with_module_prefix(self):
code = """
import numba
@numba.jit
def my_func():
pass
"""
assert contains_jit_decorator(code)
def test_numba_jit_with_alias(self):
code = """
import numba as nb
@nb.jit
def my_func():
pass
"""
assert contains_jit_decorator(code)
def test_numba_jit_direct_import(self):
code = """
from numba import jit
@jit
def my_func():
pass
"""
assert contains_jit_decorator(code)
def test_numba_jit_direct_import_with_alias(self):
code = """
from numba import jit as my_jit
@my_jit
def my_func():
pass
"""
assert contains_jit_decorator(code)
def test_numba_jit_with_arguments(self):
code = """
import numba
@numba.jit(nopython=True)
def my_func():
pass
"""
assert contains_jit_decorator(code)
def test_numba_jit_direct_import_with_arguments(self):
code = """
from numba import jit
@jit(nopython=True, cache=True)
def my_func():
pass
"""
assert contains_jit_decorator(code)
def test_numba_njit(self):
code = """
from numba import njit
@njit
def my_func():
pass
"""
assert contains_jit_decorator(code)
def test_numba_njit_with_module_prefix(self):
code = """
import numba
@numba.njit
def my_func():
pass
"""
assert contains_jit_decorator(code)
def test_numba_vectorize(self):
code = """
from numba import vectorize
@vectorize
def my_func(x):
return x * 2
"""
assert contains_jit_decorator(code)
def test_numba_guvectorize(self):
code = """
import numba
@numba.guvectorize(['void(float64[:], float64[:])'], '(n)->(n)')
def my_func(x, res):
pass
"""
assert contains_jit_decorator(code)
def test_numba_stencil(self):
code = """
from numba import stencil
@stencil
def my_kernel(a):
return a[0, 0] + a[0, 1]
"""
assert contains_jit_decorator(code)
def test_numba_cfunc(self):
code = """
from numba import cfunc
@cfunc("float64(float64)")
def my_func(x):
return x * 2
"""
assert contains_jit_decorator(code)
def test_numba_generated_jit(self):
code = """
from numba import generated_jit
@generated_jit
def my_func(x):
pass
"""
assert contains_jit_decorator(code)
def test_numba_cuda_jit(self):
code = """
import numba
@numba.cuda.jit
def my_kernel():
pass
"""
assert contains_jit_decorator(code)
def test_numba_cuda_jit_with_alias(self):
code = """
import numba as nb
@nb.cuda.jit
def my_kernel():
pass
"""
assert contains_jit_decorator(code)
class TestContainsJitDecoratorTorch:
"""Tests for torch JIT decorator detection."""
def test_torch_compile(self):
code = """
import torch
@torch.compile
def my_func():
pass
"""
assert contains_jit_decorator(code)
def test_torch_compile_with_alias(self):
code = """
import torch as th
@th.compile
def my_func():
pass
"""
assert contains_jit_decorator(code)
def test_torch_compile_direct_import(self):
code = """
from torch import compile
@compile
def my_func():
pass
"""
assert contains_jit_decorator(code)
def test_torch_compile_with_arguments(self):
code = """
import torch
@torch.compile(mode="reduce-overhead")
def my_func():
pass
"""
assert contains_jit_decorator(code)
def test_torch_jit_script(self):
code = """
import torch
@torch.jit.script
def my_func():
pass
"""
assert contains_jit_decorator(code)
def test_torch_jit_script_with_alias(self):
code = """
import torch as th
@th.jit.script
def my_func():
pass
"""
assert contains_jit_decorator(code)
def test_torch_jit_trace(self):
code = """
import torch
@torch.jit.trace
def my_func():
pass
"""
assert contains_jit_decorator(code)
def test_torch_jit_imported_then_script(self):
code = """
from torch import jit
@jit.script
def my_func():
pass
"""
assert contains_jit_decorator(code)
def test_torch_jit_imported_then_trace(self):
code = """
from torch import jit
@jit.trace
def my_func():
pass
"""
assert contains_jit_decorator(code)
class TestContainsJitDecoratorTensorFlow:
"""Tests for TensorFlow JIT decorator detection."""
def test_tensorflow_function_with_tf_alias(self):
code = """
import tensorflow as tf
@tf.function
def my_func():
pass
"""
assert contains_jit_decorator(code)
def test_tensorflow_function_full_name(self):
code = """
import tensorflow
@tensorflow.function
def my_func():
pass
"""
assert contains_jit_decorator(code)
def test_tensorflow_function_direct_import(self):
code = """
from tensorflow import function
@function
def my_func():
pass
"""
assert contains_jit_decorator(code)
def test_tensorflow_function_with_arguments(self):
code = """
import tensorflow as tf
@tf.function(jit_compile=True)
def my_func():
pass
"""
assert contains_jit_decorator(code)
def test_tf_function_direct_import_alias(self):
code = """
from tensorflow import function as tf_func
@tf_func
def my_func():
pass
"""
assert contains_jit_decorator(code)
class TestContainsJitDecoratorJax:
"""Tests for JAX JIT decorator detection."""
def test_jax_jit(self):
code = """
import jax
@jax.jit
def my_func():
pass
"""
assert contains_jit_decorator(code)
def test_jax_jit_with_alias(self):
code = """
import jax as j
@j.jit
def my_func():
pass
"""
assert contains_jit_decorator(code)
def test_jax_jit_direct_import(self):
code = """
from jax import jit
@jit
def my_func():
pass
"""
assert contains_jit_decorator(code)
def test_jax_jit_direct_import_with_alias(self):
code = """
from jax import jit as jax_jit
@jax_jit
def my_func():
pass
"""
assert contains_jit_decorator(code)
def test_jax_jit_with_arguments(self):
code = """
import jax
@jax.jit(static_argnums=(0,))
def my_func(x, y):
pass
"""
assert contains_jit_decorator(code)
class TestContainsJitDecoratorNegativeCases:
"""Tests that should NOT detect JIT decorators."""
def test_no_decorators(self):
code = """
def my_func():
pass
"""
assert not contains_jit_decorator(code)
def test_other_decorator(self):
code = """
import functools
@functools.lru_cache
def my_func():
pass
"""
assert not contains_jit_decorator(code)
def test_custom_decorator(self):
code = """
def my_decorator(func):
return func
@my_decorator
def my_func():
pass
"""
assert not contains_jit_decorator(code)
def test_property_decorator(self):
code = """
class MyClass:
@property
def my_prop(self):
return self._value
"""
assert not contains_jit_decorator(code)
def test_staticmethod_decorator(self):
code = """
class MyClass:
@staticmethod
def my_func():
pass
"""
assert not contains_jit_decorator(code)
def test_classmethod_decorator(self):
code = """
class MyClass:
@classmethod
def my_func(cls):
pass
"""
assert not contains_jit_decorator(code)
def test_jit_in_comment(self):
code = """
# @numba.jit
def my_func():
pass
"""
assert not contains_jit_decorator(code)
def test_jit_in_string(self):
code = '''
def my_func():
"""This function could use @numba.jit decorator."""
pass
'''
assert not contains_jit_decorator(code)
def test_unrelated_jit_name(self):
code = """
def jit():
pass
@jit
def my_func():
pass
"""
assert not contains_jit_decorator(code)
def test_unrelated_module_with_jit_attribute(self):
code = """
import my_module
@my_module.jit
def my_func():
pass
"""
assert not contains_jit_decorator(code)
def test_numba_import_but_no_decorator(self):
code = """
import numba
def my_func():
pass
"""
assert not contains_jit_decorator(code)
def test_jit_variable_not_decorator(self):
code = """
from numba import jit
def my_func():
x = jit
pass
"""
assert not contains_jit_decorator(code)
class TestContainsJitDecoratorEdgeCases:
"""Edge case tests for JIT decorator detection."""
def test_multiple_decorators_with_jit(self):
code = """
import numba
import functools
@functools.lru_cache
@numba.jit
def my_func():
pass
"""
assert contains_jit_decorator(code)
def test_multiple_decorators_jit_first(self):
code = """
import numba
import functools
@numba.jit
@functools.lru_cache
def my_func():
pass
"""
assert contains_jit_decorator(code)
def test_async_function_with_jit(self):
code = """
import numba
@numba.jit
async def my_func():
pass
"""
assert contains_jit_decorator(code) is False
def test_method_in_class_with_jit(self):
code = """
import numba
class MyClass:
@numba.jit
def my_method(self):
pass
"""
assert contains_jit_decorator(code)
def test_nested_class_method_with_jit(self):
code = """
import numba
class Outer:
class Inner:
@numba.jit
def my_method(self):
pass
"""
assert contains_jit_decorator(code)
def test_multiple_functions_one_with_jit(self):
code = """
import numba
def func_a():
pass
@numba.jit
def func_b():
pass
def func_c():
pass
"""
assert contains_jit_decorator(code)
def test_multiple_jit_functions(self):
code = """
import numba
import jax
@numba.jit
def func_a():
pass
@jax.jit
def func_b():
pass
"""
assert contains_jit_decorator(code)
def test_empty_code(self):
code = ""
assert not contains_jit_decorator(code)
def test_syntax_error_code(self):
code = """
def func(
pass
"""
assert not contains_jit_decorator(code)
def test_whitespace_only(self):
code = " \n\n \t\t\n"
assert not contains_jit_decorator(code)
def test_only_imports(self):
code = """
import numba
from jax import jit
"""
assert not contains_jit_decorator(code)
def test_lambda_cannot_have_decorator(self):
# Lambdas cannot have decorators in Python
code = """
import numba
f = lambda x: x * 2
"""
assert not contains_jit_decorator(code)
def test_mixed_imports_and_aliases(self):
code = """
import numba as nb
from torch import compile as torch_compile
import jax
@nb.jit
def func_a():
pass
"""
assert contains_jit_decorator(code)
def test_decorator_in_different_module_context(self):
code = """
# Import numba for numeric computation
import numba
# Some other code
x = 5
class Processor:
@numba.njit
def process(self, data):
return data * 2
"""
assert contains_jit_decorator(code)
def test_from_import_star_not_tracked(self):
# Star imports are not tracked, so @jit won't be detected
code = """
from numba import *
@jit
def my_func():
pass
"""
# Star imports are not tracked, so this returns False
assert not contains_jit_decorator(code)
def test_multiple_from_imports_same_module(self):
code = """
from numba import jit
from numba import njit
@njit
def my_func():
pass
"""
assert contains_jit_decorator(code)
def test_reimport_with_different_alias(self):
code = """
from numba import jit
from numba import jit as fast_jit
@fast_jit
def my_func():
pass
"""
assert contains_jit_decorator(code)
class TestContainsJitDecoratorComplexCases:
"""Complex real-world scenarios for JIT decorator detection."""
def test_realistic_numba_code(self):
code = """
import numpy as np
from numba import jit, prange
@jit(nopython=True, parallel=True)
def compute_sum(arr):
total = 0.0
for i in prange(len(arr)):
total += arr[i]
return total
def main():
data = np.random.rand(1000000)
result = compute_sum(data)
print(result)
"""
assert contains_jit_decorator(code)
def test_realistic_torch_code(self):
code = """
import torch
import torch.nn as nn
class MyModel(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(10, 5)
@torch.compile
def forward(self, x):
return self.linear(x)
"""