Skip to content

Commit cf55e96

Browse files
committed
first pass tests - windows fixes
first pass fix codeflash_capture fix formatter more tempfile changes Update test_get_code.py
1 parent a035af8 commit cf55e96

File tree

7 files changed

+147
-135
lines changed

7 files changed

+147
-135
lines changed

codeflash/code_utils/coverage_utils.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,11 @@ def build_fully_qualified_name(function_name: str, code_context: CodeOptimizatio
4141

4242
def generate_candidates(source_code_path: Path) -> list[str]:
4343
"""Generate all the possible candidates for coverage data based on the source code path."""
44-
candidates = [source_code_path.name]
45-
current_path = source_code_path.parent
44+
candidates: list[str] = [source_code_path.name]
45+
current_path: Path = source_code_path.parent
4646

4747
while current_path != current_path.parent:
48-
candidate_path = str(Path(current_path.name) / candidates[-1])
48+
candidate_path = (Path(current_path.name) / candidates[-1]).as_posix()
4949
candidates.append(candidate_path)
5050
current_path = current_path.parent
5151

tests/test_code_context_extractor.py

Lines changed: 25 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -356,10 +356,9 @@ def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R:
356356
lifespan=self.__duration__,
357357
)
358358
'''
359-
with tempfile.NamedTemporaryFile(mode="w") as f:
360-
f.write(code)
361-
f.flush()
362-
file_path = Path(f.name).resolve()
359+
with tempfile.TemporaryDirectory() as temp_dir:
360+
file_path = Path(temp_dir) / "test.py"
361+
file_path.write_text(code)
363362
opt = Optimizer(
364363
Namespace(
365364
project_root=file_path.parent.resolve(),
@@ -368,7 +367,7 @@ def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R:
368367
test_framework="pytest",
369368
pytest_cmd="pytest",
370369
experiment_id=None,
371-
test_project_root=Path().resolve(),
370+
test_project_root=Path.cwd(),
372371
)
373372
)
374373
function_to_optimize = FunctionToOptimize(
@@ -557,10 +556,9 @@ def __repr__(self):
557556
def helper_method(self):
558557
return self.x
559558
"""
560-
with tempfile.NamedTemporaryFile(mode="w") as f:
561-
f.write(code)
562-
f.flush()
563-
file_path = Path(f.name).resolve()
559+
with tempfile.TemporaryDirectory() as temp_dir:
560+
file_path = Path(temp_dir) / "test.py"
561+
file_path.write_text(code)
564562
opt = Optimizer(
565563
Namespace(
566564
project_root=file_path.parent.resolve(),
@@ -569,7 +567,7 @@ def helper_method(self):
569567
test_framework="pytest",
570568
pytest_cmd="pytest",
571569
experiment_id=None,
572-
test_project_root=Path().resolve(),
570+
test_project_root=Path.cwd(),
573571
)
574572
)
575573
function_to_optimize = FunctionToOptimize(
@@ -637,10 +635,9 @@ def __repr__(self):
637635
def helper_method(self):
638636
return self.x
639637
"""
640-
with tempfile.NamedTemporaryFile(mode="w") as f:
641-
f.write(code)
642-
f.flush()
643-
file_path = Path(f.name).resolve()
638+
with tempfile.TemporaryDirectory() as temp_dir:
639+
file_path = Path(temp_dir) / "test.py"
640+
file_path.write_text(code)
644641
opt = Optimizer(
645642
Namespace(
646643
project_root=file_path.parent.resolve(),
@@ -649,7 +646,7 @@ def helper_method(self):
649646
test_framework="pytest",
650647
pytest_cmd="pytest",
651648
experiment_id=None,
652-
test_project_root=Path().resolve(),
649+
test_project_root=Path.cwd(),
653650
)
654651
)
655652
function_to_optimize = FunctionToOptimize(
@@ -717,10 +714,9 @@ def __repr__(self):
717714
def helper_method(self):
718715
return self.x
719716
"""
720-
with tempfile.NamedTemporaryFile(mode="w") as f:
721-
f.write(code)
722-
f.flush()
723-
file_path = Path(f.name).resolve()
717+
with tempfile.TemporaryDirectory() as temp_dir:
718+
file_path = Path(temp_dir) / "test.py"
719+
file_path.write_text(code)
724720
opt = Optimizer(
725721
Namespace(
726722
project_root=file_path.parent.resolve(),
@@ -729,7 +725,7 @@ def helper_method(self):
729725
test_framework="pytest",
730726
pytest_cmd="pytest",
731727
experiment_id=None,
732-
test_project_root=Path().resolve(),
728+
test_project_root=Path.cwd(),
733729
)
734730
)
735731
function_to_optimize = FunctionToOptimize(
@@ -787,10 +783,9 @@ def __repr__(self):
787783
def helper_method(self):
788784
return self.x
789785
"""
790-
with tempfile.NamedTemporaryFile(mode="w") as f:
791-
f.write(code)
792-
f.flush()
793-
file_path = Path(f.name).resolve()
786+
with tempfile.TemporaryDirectory() as temp_dir:
787+
file_path = Path(temp_dir) / "test.py"
788+
file_path.write_text(code)
794789
opt = Optimizer(
795790
Namespace(
796791
project_root=file_path.parent.resolve(),
@@ -838,10 +833,9 @@ def __repr__(self):
838833
def helper_method(self):
839834
return self.x
840835
"""
841-
with tempfile.NamedTemporaryFile(mode="w") as f:
842-
f.write(code)
843-
f.flush()
844-
file_path = Path(f.name).resolve()
836+
with tempfile.TemporaryDirectory() as temp_dir:
837+
file_path = Path(temp_dir) / "test.py"
838+
file_path.write_text(code)
845839
opt = Optimizer(
846840
Namespace(
847841
project_root=file_path.parent.resolve(),
@@ -1272,10 +1266,9 @@ def target_method(self):
12721266
def outside_method():
12731267
return 1
12741268
"""
1275-
with tempfile.NamedTemporaryFile(mode="w") as f:
1276-
f.write(code)
1277-
f.flush()
1278-
file_path = Path(f.name).resolve()
1269+
with tempfile.TemporaryDirectory() as temp_dir:
1270+
file_path = Path(temp_dir) / "test.py"
1271+
file_path.write_text(code)
12791272
opt = Optimizer(
12801273
Namespace(
12811274
project_root=file_path.parent.resolve(),

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: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def test_example_test_3(self):
4343
class MyClass:
4444
def __init__(self):
4545
self.x = 2
46-
print(f"TEST_INFO_START|{{get_test_info_from_stack('{test_dir!s}')}}|TEST_INFO_END")
46+
print(f"TEST_INFO_START|{{get_test_info_from_stack('{test_dir.resolve().as_posix()}')}}|TEST_INFO_END")
4747
"""
4848
test_file_name = "test_stack_info_temp.py"
4949

@@ -118,7 +118,7 @@ def test_example_test_3(self):
118118
class MyClass:
119119
def __init__(self):
120120
self.x = 2
121-
print(f"TEST_INFO_START|{{get_test_info_from_stack('{test_dir!s}')}}|TEST_INFO_END")
121+
print(f"TEST_INFO_START|{{get_test_info_from_stack('{test_dir.resolve().as_posix()}')}}|TEST_INFO_END")
122122
"""
123123
test_file_name = "test_stack_info_temp.py"
124124

@@ -182,7 +182,7 @@ def test_example_test_3(self):
182182
class MyClass:
183183
def __init__(self):
184184
self.x = 2
185-
print(f"TEST_INFO_START|{{get_test_info_from_stack('{test_dir!s}')}}|TEST_INFO_END")
185+
print(f"TEST_INFO_START|{{get_test_info_from_stack('{test_dir.resolve().as_posix()}')}}|TEST_INFO_END")
186186
"""
187187
test_dir = (Path(__file__).parent.parent / "code_to_optimize" / "tests" / "pytest").resolve()
188188
test_file_name = "test_stack_info_temp.py"
@@ -262,7 +262,7 @@ class MyClass:
262262
def __init__(self):
263263
self.x = 2
264264
# Print out the detected test info each time we instantiate MyClass
265-
print(f"TEST_INFO_START|{{get_test_info_from_stack('{test_dir!s}')}}|TEST_INFO_END")
265+
print(f"TEST_INFO_START|{{get_test_info_from_stack('{test_dir.resolve().as_posix()}')}}|TEST_INFO_END")
266266
"""
267267

268268
test_file_name = "test_stack_info_recursive_temp.py"
@@ -344,7 +344,7 @@ def test_example_test():
344344
class MyClass:
345345
def __init__(self):
346346
self.x = 2
347-
print(f"TEST_INFO_START|{{get_test_info_from_stack('{test_dir!s}')}}|TEST_INFO_END")
347+
print(f"TEST_INFO_START|{{get_test_info_from_stack('{test_dir.resolve().as_posix()}')}}|TEST_INFO_END")
348348
"""
349349
test_dir = (Path(__file__).parent.parent / "code_to_optimize" / "tests" / "pytest").resolve()
350350
test_file_name = "test_stack_info_temp.py"
@@ -414,7 +414,7 @@ def test_example_test_3(self):
414414
sample_code = f"""
415415
from codeflash.verification.codeflash_capture import codeflash_capture
416416
class MyClass:
417-
@codeflash_capture(function_name="some_function", tmp_dir_path="{get_run_tmp_file(Path("test_return_values"))}", tests_root="{test_dir!s}")
417+
@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()}")
418418
def __init__(self, x=2):
419419
self.x = x
420420
"""
@@ -537,7 +537,7 @@ def __init__(self):
537537
self.x = 2
538538
539539
class MyClass(ParentClass):
540-
@codeflash_capture(function_name="some_function", tmp_dir_path="{get_run_tmp_file(Path("test_return_values"))}", tests_root="{test_dir!s}")
540+
@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()}")
541541
def __init__(self, *args, **kwargs):
542542
super().__init__(*args, **kwargs)
543543
"""
@@ -654,9 +654,9 @@ def test_example_test():
654654
655655
class MyClass:
656656
@codeflash_capture(
657-
function_name="some_function",
658-
tmp_dir_path="{get_run_tmp_file(Path("test_return_values"))}",
659-
tests_root="{test_dir!s}"
657+
function_name="some_function",
658+
tmp_dir_path="{get_run_tmp_file(Path("test_return_values")).resolve().as_posix()}",
659+
tests_root="{test_dir.resolve().as_posix()}"
660660
)
661661
def __init__(self, x=2):
662662
self.x = x
@@ -772,7 +772,7 @@ def test_helper_classes():
772772
from code_to_optimize.tests.pytest.helper_file_2 import HelperClass2, AnotherHelperClass
773773
774774
class MyClass:
775-
@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)
775+
@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)
776776
def __init__(self):
777777
self.x = 1
778778
@@ -786,7 +786,7 @@ def target_function(self):
786786
from codeflash.verification.codeflash_capture import codeflash_capture
787787
788788
class HelperClass1:
789-
@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)
789+
@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)
790790
def __init__(self):
791791
self.y = 1
792792
@@ -798,15 +798,15 @@ def helper1(self):
798798
from codeflash.verification.codeflash_capture import codeflash_capture
799799
800800
class HelperClass2:
801-
@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)
801+
@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)
802802
def __init__(self):
803803
self.z = 2
804804
805805
def helper2(self):
806806
return 2
807807
808808
class AnotherHelperClass:
809-
@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)
809+
@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)
810810
def __init__(self, *args, **kwargs):
811811
super().__init__(*args, **kwargs)
812812

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())

0 commit comments

Comments
 (0)