Skip to content

Commit c6f27a5

Browse files
committed
basics
1 parent c8950f5 commit c6f27a5

10 files changed

+157
-133
lines changed

tests/test_code_utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,10 @@
1414
get_imports_from_file,
1515
get_qualified_name,
1616
get_run_tmp_file,
17+
has_any_async_functions,
1718
is_class_defined_in_file,
1819
module_name_from_file_path,
1920
path_belongs_to_site_packages,
20-
has_any_async_functions,
2121
)
2222
from codeflash.code_utils.concolic_utils import clean_concolic_tests
2323
from codeflash.code_utils.coverage_utils import generate_candidates, prepare_coverage_files
@@ -254,7 +254,7 @@ def test_get_run_tmp_file_reuses_temp_directory() -> None:
254254

255255

256256
def test_path_belongs_to_site_packages_with_site_package_path(monkeypatch: pytest.MonkeyPatch) -> None:
257-
site_packages = [Path("/usr/local/lib/python3.9/site-packages")]
257+
site_packages = [Path("/usr/local/lib/python3.9/site-packages").resolve()]
258258
monkeypatch.setattr(site, "getsitepackages", lambda: site_packages)
259259

260260
file_path = Path("/usr/local/lib/python3.9/site-packages/some_package")

tests/test_codeflash_capture.py

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def test_example_test_3(self):
4242
class MyClass:
4343
def __init__(self):
4444
self.x = 2
45-
print(f"TEST_INFO_START|{{get_test_info_from_stack('{test_dir!s}')}}|TEST_INFO_END")
45+
print(f"TEST_INFO_START|{{get_test_info_from_stack('{test_dir.resolve().as_posix()}')}}|TEST_INFO_END")
4646
"""
4747
test_file_name = "test_stack_info_temp.py"
4848

@@ -54,7 +54,7 @@ def __init__(self):
5454
with sample_code_path.open("w") as f:
5555
f.write(sample_code)
5656
result = execute_test_subprocess(
57-
cwd=test_dir, env={}, cmd_list=[f"{SAFE_SYS_EXECUTABLE}", "-m", "pytest", test_file_name, "-s"]
57+
cwd=test_dir, env=os.environ.copy(), cmd_list=[f"{SAFE_SYS_EXECUTABLE}", "-m", "pytest", test_file_name, "-s"]
5858
)
5959
assert not result.stderr
6060
assert result.returncode == 0
@@ -117,7 +117,7 @@ def test_example_test_3(self):
117117
class MyClass:
118118
def __init__(self):
119119
self.x = 2
120-
print(f"TEST_INFO_START|{{get_test_info_from_stack('{test_dir!s}')}}|TEST_INFO_END")
120+
print(f"TEST_INFO_START|{{get_test_info_from_stack('{test_dir.resolve().as_posix()}')}}|TEST_INFO_END")
121121
"""
122122
test_file_name = "test_stack_info_temp.py"
123123

@@ -129,7 +129,7 @@ def __init__(self):
129129
with sample_code_path.open("w") as f:
130130
f.write(sample_code)
131131
result = execute_test_subprocess(
132-
cwd=test_dir, env={}, cmd_list=[f"{SAFE_SYS_EXECUTABLE}", "-m", "pytest", test_file_name, "-s"]
132+
cwd=test_dir, env=os.environ.copy(), cmd_list=[f"{SAFE_SYS_EXECUTABLE}", "-m", "pytest", test_file_name, "-s"]
133133
)
134134
assert not result.stderr
135135
assert result.returncode == 0
@@ -181,7 +181,7 @@ def test_example_test_3(self):
181181
class MyClass:
182182
def __init__(self):
183183
self.x = 2
184-
print(f"TEST_INFO_START|{{get_test_info_from_stack('{test_dir!s}')}}|TEST_INFO_END")
184+
print(f"TEST_INFO_START|{{get_test_info_from_stack('{test_dir.resolve().as_posix()}')}}|TEST_INFO_END")
185185
"""
186186
test_dir = (Path(__file__).parent.parent / "code_to_optimize" / "tests" / "pytest").resolve()
187187
test_file_name = "test_stack_info_temp.py"
@@ -194,7 +194,7 @@ def __init__(self):
194194
with sample_code_path.open("w") as f:
195195
f.write(sample_code)
196196
result = execute_test_subprocess(
197-
cwd=test_dir, env={}, cmd_list=[f"{SAFE_SYS_EXECUTABLE}", "-m", "pytest", test_file_name, "-s"]
197+
cwd=test_dir, env=os.environ.copy(), cmd_list=[f"{SAFE_SYS_EXECUTABLE}", "-m", "pytest", test_file_name, "-s"]
198198
)
199199
assert not result.stderr
200200
assert result.returncode == 0
@@ -261,7 +261,7 @@ class MyClass:
261261
def __init__(self):
262262
self.x = 2
263263
# Print out the detected test info each time we instantiate MyClass
264-
print(f"TEST_INFO_START|{{get_test_info_from_stack('{test_dir!s}')}}|TEST_INFO_END")
264+
print(f"TEST_INFO_START|{{get_test_info_from_stack('{test_dir.resolve().as_posix()}')}}|TEST_INFO_END")
265265
"""
266266

267267
test_file_name = "test_stack_info_recursive_temp.py"
@@ -279,7 +279,7 @@ def __init__(self):
279279

280280
# Run pytest as a subprocess
281281
result = execute_test_subprocess(
282-
cwd=test_dir, env={}, cmd_list=[f"{SAFE_SYS_EXECUTABLE}", "-m", "pytest", test_file_name, "-s"]
282+
cwd=test_dir, env=os.environ.copy(), cmd_list=[f"{SAFE_SYS_EXECUTABLE}", "-m", "pytest", test_file_name, "-s"]
283283
)
284284

285285
# Check for errors
@@ -343,7 +343,7 @@ def test_example_test():
343343
class MyClass:
344344
def __init__(self):
345345
self.x = 2
346-
print(f"TEST_INFO_START|{{get_test_info_from_stack('{test_dir!s}')}}|TEST_INFO_END")
346+
print(f"TEST_INFO_START|{{get_test_info_from_stack('{test_dir.resolve().as_posix()}')}}|TEST_INFO_END")
347347
"""
348348
test_dir = (Path(__file__).parent.parent / "code_to_optimize" / "tests" / "pytest").resolve()
349349
test_file_name = "test_stack_info_temp.py"
@@ -356,7 +356,7 @@ def __init__(self):
356356
with sample_code_path.open("w") as f:
357357
f.write(sample_code)
358358
result = execute_test_subprocess(
359-
cwd=test_dir, env={}, cmd_list=[f"{SAFE_SYS_EXECUTABLE}", "-m", "pytest", test_file_name, "-s"]
359+
cwd=test_dir, env=os.environ.copy(), cmd_list=[f"{SAFE_SYS_EXECUTABLE}", "-m", "pytest", test_file_name, "-s"]
360360
)
361361
assert not result.stderr
362362
assert result.returncode == 0
@@ -413,7 +413,7 @@ def test_example_test_3(self):
413413
sample_code = f"""
414414
from codeflash.verification.codeflash_capture import codeflash_capture
415415
class MyClass:
416-
@codeflash_capture(function_name="some_function", tmp_dir_path="{get_run_tmp_file(Path("test_return_values"))}", tests_root="{test_dir!s}")
416+
@codeflash_capture(function_name="some_function", tmp_dir_path="{get_run_tmp_file(Path("test_return_values")).resolve().as_posix()}", tests_root="{test_dir.resolve().as_posix()}")
417417
def __init__(self, x=2):
418418
self.x = x
419419
"""
@@ -536,7 +536,7 @@ def __init__(self):
536536
self.x = 2
537537
538538
class MyClass(ParentClass):
539-
@codeflash_capture(function_name="some_function", tmp_dir_path="{get_run_tmp_file(Path("test_return_values"))}", tests_root="{test_dir!s}")
539+
@codeflash_capture(function_name="some_function", tmp_dir_path="{get_run_tmp_file(Path("test_return_values")).resolve().as_posix()}", tests_root="{test_dir.resolve().as_posix()}")
540540
def __init__(self, *args, **kwargs):
541541
super().__init__(*args, **kwargs)
542542
"""
@@ -653,9 +653,9 @@ def test_example_test():
653653
654654
class MyClass:
655655
@codeflash_capture(
656-
function_name="some_function",
657-
tmp_dir_path="{get_run_tmp_file(Path("test_return_values"))}",
658-
tests_root="{test_dir!s}"
656+
function_name="some_function",
657+
tmp_dir_path="{get_run_tmp_file(Path("test_return_values")).resolve().as_posix()}",
658+
tests_root="{test_dir.resolve().as_posix()}"
659659
)
660660
def __init__(self, x=2):
661661
self.x = x
@@ -771,7 +771,7 @@ def test_helper_classes():
771771
from code_to_optimize.tests.pytest.helper_file_2 import HelperClass2, AnotherHelperClass
772772
773773
class MyClass:
774-
@codeflash_capture(function_name='MyClass.__init__', tmp_dir_path='{get_run_tmp_file(Path("test_return_values"))}', tests_root="{test_dir!s}" , is_fto=True)
774+
@codeflash_capture(function_name='MyClass.__init__', tmp_dir_path='{get_run_tmp_file(Path("test_return_values")).resolve().as_posix()}', tests_root="{test_dir.resolve().as_posix()}" , is_fto=True)
775775
def __init__(self):
776776
self.x = 1
777777
@@ -785,7 +785,7 @@ def target_function(self):
785785
from codeflash.verification.codeflash_capture import codeflash_capture
786786
787787
class HelperClass1:
788-
@codeflash_capture(function_name='HelperClass1.__init__', tmp_dir_path='{get_run_tmp_file(Path("test_return_values"))}', tests_root="{test_dir!s}", is_fto=False)
788+
@codeflash_capture(function_name='HelperClass1.__init__', tmp_dir_path='{get_run_tmp_file(Path("test_return_values")).resolve().as_posix()}', tests_root="{test_dir.resolve().as_posix()}", is_fto=False)
789789
def __init__(self):
790790
self.y = 1
791791
@@ -797,15 +797,15 @@ def helper1(self):
797797
from codeflash.verification.codeflash_capture import codeflash_capture
798798
799799
class HelperClass2:
800-
@codeflash_capture(function_name='HelperClass2.__init__', tmp_dir_path='{get_run_tmp_file(Path("test_return_values"))}', tests_root="{test_dir!s}", is_fto=False)
800+
@codeflash_capture(function_name='HelperClass2.__init__', tmp_dir_path='{get_run_tmp_file(Path("test_return_values")).resolve().as_posix()}', tests_root="{test_dir.resolve().as_posix()}", is_fto=False)
801801
def __init__(self):
802802
self.z = 2
803803
804804
def helper2(self):
805805
return 2
806806
807807
class AnotherHelperClass:
808-
@codeflash_capture(function_name='AnotherHelperClass.__init__', tmp_dir_path='{get_run_tmp_file(Path("test_return_values"))}', tests_root="{test_dir!s}", is_fto=False)
808+
@codeflash_capture(function_name='AnotherHelperClass.__init__', tmp_dir_path='{get_run_tmp_file(Path("test_return_values")).resolve().as_posix()}', tests_root="{test_dir.resolve().as_posix()}", is_fto=False)
809809
def __init__(self, *args, **kwargs):
810810
super().__init__(*args, **kwargs)
811811

tests/test_formatter.py

Lines changed: 30 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,10 @@ def test_sorting_imports():
3333

3434
def test_sort_imports_without_formatting():
3535
"""Test that imports are sorted when formatting is disabled and should_sort_imports is True."""
36-
with tempfile.NamedTemporaryFile() as tmp:
37-
tmp.write(b"import sys\nimport unittest\nimport os\n")
38-
tmp.flush()
39-
tmp_path = Path(tmp.name)
36+
with tempfile.TemporaryDirectory() as tmp_dir:
37+
tmp_path = Path(tmp_dir) / "test.py"
38+
with tmp_path.open("w") as tmp:
39+
tmp.write("import sys\nimport unittest\nimport os\n")
4040

4141
new_code = format_code(formatter_cmds=["disabled"], path=tmp_path)
4242
assert new_code is not None
@@ -105,16 +105,13 @@ def test_formatter_cmds_non_existent():
105105
ignore-paths = []
106106
"""
107107

108-
with tempfile.NamedTemporaryFile(suffix=".toml", delete=False) as tmp:
109-
tmp.write(config_data.encode())
110-
tmp.flush()
111-
tmp_path = Path(tmp.name)
108+
with tempfile.TemporaryDirectory() as tmp_dir:
109+
tmp_path = Path(tmp_dir) / "pyproject.toml"
110+
with tmp_path.open("w") as tmp:
111+
tmp.write(config_data)
112112

113-
try:
114113
config, _ = parse_config_file(tmp_path)
115114
assert config["formatter_cmds"] == ["black $file"]
116-
finally:
117-
os.remove(tmp_path)
118115

119116
try:
120117
import black
@@ -133,12 +130,13 @@ def foo():
133130
def foo():
134131
return os.path.join(sys.path[0], "bar")
135132
"""
136-
with tempfile.NamedTemporaryFile() as tmp:
137-
tmp.write(original_code)
138-
tmp.flush()
139-
tmp_path = tmp.name
133+
with tempfile.TemporaryDirectory() as tmp_dir:
134+
tmp_path = Path(tmp_dir) / "test.py"
135+
with tmp_path.open("wb") as tmp:
136+
tmp.write(original_code)
137+
tmp.flush()
140138

141-
actual = format_code(formatter_cmds=["black $file"], path=Path(tmp_path))
139+
actual = format_code(formatter_cmds=["black $file"], path=tmp_path.resolve())
142140
assert actual == expected
143141

144142

@@ -159,10 +157,11 @@ def foo():
159157
def foo():
160158
return os.path.join(sys.path[0], "bar")
161159
"""
162-
with tempfile.NamedTemporaryFile() as tmp:
163-
tmp.write(original_code)
164-
tmp.flush()
165-
tmp_path = tmp.name
160+
with tempfile.TemporaryDirectory() as tmp_dir:
161+
tmp_path = Path(tmp_dir) / "test.py"
162+
with tmp_path.open("wb") as tmp:
163+
tmp.write(original_code)
164+
tmp.flush()
166165

167166
actual = format_code(formatter_cmds=["black $file"], path=Path(tmp_path))
168167
assert actual == expected
@@ -185,10 +184,11 @@ def foo():
185184
def foo():
186185
return os.path.join(sys.path[0], "bar")
187186
"""
188-
with tempfile.NamedTemporaryFile(suffix=".py") as tmp:
189-
tmp.write(original_code)
190-
tmp.flush()
191-
tmp_path = tmp.name
187+
with tempfile.TemporaryDirectory() as tmp_dir:
188+
tmp_path = Path(tmp_dir) / "test.py"
189+
with tmp_path.open("wb") as tmp:
190+
tmp.write(original_code)
191+
tmp.flush()
192192

193193
actual = format_code(
194194
formatter_cmds=["ruff check --exit-zero --fix $file", "ruff format $file"], path=Path(tmp_path)
@@ -203,9 +203,10 @@ def test_formatter_error():
203203
def foo():
204204
return os.path.join(sys.path[0], 'bar')"""
205205
expected = original_code
206-
with tempfile.NamedTemporaryFile("w") as tmp:
207-
tmp.write(original_code)
208-
tmp.flush()
209-
tmp_path = tmp.name
206+
with tempfile.TemporaryDirectory() as tmp_dir:
207+
tmp_path = Path(tmp_dir) / "test.py"
208+
with tmp_path.open("w") as tmp:
209+
tmp.write(original_code)
210+
210211
with pytest.raises(FileNotFoundError):
211-
format_code(formatter_cmds=["exit 1"], path=Path(tmp_path))
212+
format_code(formatter_cmds=["exit 1"], path=tmp_path.resolve())

tests/test_function_discovery.py

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -16,28 +16,29 @@ def test_function_eligible_for_optimization() -> None:
1616
return a**2
1717
"""
1818
functions_found = {}
19-
with tempfile.NamedTemporaryFile(mode="w", suffix=".py") as f:
20-
f.write(function)
21-
f.flush()
22-
functions_found = find_all_functions_in_file(Path(f.name))
23-
assert functions_found[Path(f.name)][0].function_name == "test_function_eligible_for_optimization"
19+
with tempfile.TemporaryDirectory() as temp_dir:
20+
temp_file = Path(temp_dir) / "temp_file.py"
21+
temp_file.write_text(function)
22+
functions_found = find_all_functions_in_file(temp_file)
23+
assert functions_found[temp_file][0].function_name == "test_function_eligible_for_optimization"
2424

2525
# Has no return statement
2626
function = """def test_function_not_eligible_for_optimization():
2727
a = 5
2828
print(a)
2929
"""
3030
functions_found = {}
31-
with tempfile.NamedTemporaryFile(mode="w", suffix=".py") as f:
32-
f.write(function)
33-
f.flush()
34-
functions_found = find_all_functions_in_file(Path(f.name))
35-
assert len(functions_found[Path(f.name)]) == 0
31+
with tempfile.TemporaryDirectory() as temp_dir:
32+
temp_file = Path(temp_dir) / "temp_file.py"
33+
temp_file.write_text(function)
34+
functions_found = find_all_functions_in_file(temp_file)
35+
assert len(functions_found[temp_file]) == 0
3636

3737

3838
def test_find_top_level_function_or_method():
39-
with tempfile.NamedTemporaryFile(mode="w", suffix=".py") as f:
40-
f.write(
39+
with tempfile.TemporaryDirectory() as temp_dir:
40+
temp_file = Path(temp_dir) / "temp_file.py"
41+
temp_file.write_text(
4142
"""def functionA():
4243
def functionB():
4344
return 5
@@ -61,8 +62,7 @@ def non_classmethod_function(cls, name):
6162
return cls.name
6263
"""
6364
)
64-
f.flush()
65-
path_obj_name = Path(f.name)
65+
path_obj_name = temp_file
6666
assert inspect_top_level_functions_or_methods(path_obj_name, "functionA").is_top_level
6767
assert not inspect_top_level_functions_or_methods(path_obj_name, "functionB").is_top_level
6868
assert inspect_top_level_functions_or_methods(path_obj_name, "functionC", class_name="A").is_top_level
@@ -84,8 +84,9 @@ def non_classmethod_function(cls, name):
8484

8585

8686
def test_class_method_discovery():
87-
with tempfile.NamedTemporaryFile(mode="w", suffix=".py") as f:
88-
f.write(
87+
with tempfile.TemporaryDirectory() as temp_dir:
88+
temp_file = Path(temp_dir) / "temp_file.py"
89+
temp_file.write_text(
8990
"""class A:
9091
def functionA():
9192
return True
@@ -99,11 +100,10 @@ def functionB():
99100
def functionA():
100101
return True"""
101102
)
102-
f.flush()
103103
test_config = TestConfig(
104104
tests_root="tests", project_root_path=".", test_framework="pytest", tests_project_rootdir=Path()
105105
)
106-
path_obj_name = Path(f.name)
106+
path_obj_name = temp_file
107107
functions, functions_count = get_functions_to_optimize(
108108
optimize_all=None,
109109
replay_test=None,

0 commit comments

Comments
 (0)