Skip to content

Commit a468ba7

Browse files
committed
Added a test for FunctionOptimizer.reformat_code_and_helpers
1 parent 6ec5ef0 commit a468ba7

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

tests/test_function_optimizer.py

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import argparse
2+
from pathlib import Path
3+
import shutil
4+
import tempfile
5+
6+
import pytest
7+
8+
from codeflash.discovery.functions_to_optimize import FunctionToOptimize
9+
from codeflash.optimization.function_optimizer import FunctionOptimizer
10+
from codeflash.verification.verification_utils import TestConfig
11+
12+
def test_bubble_sort_preserve_bad_formatting():
13+
"""
14+
Test the bubble sort implementation in code_to_optimize/bubble_sort_preserve_bad_formatting_for_nonoptimized_code.py.
15+
16+
This test sets the rubric for all other tests of formatting functionality.
17+
"""
18+
with tempfile.TemporaryDirectory() as test_dir_str:
19+
test_dir = Path(test_dir_str)
20+
target_path = test_dir / "target.py"
21+
this_file = Path(__file__).resolve()
22+
repo_root_dir = this_file.parent.parent
23+
source_file = repo_root_dir / "code_to_optimize" / "bubble_sort_preserve_bad_formatting_for_nonoptimized_code.py"
24+
shutil.copy2(source_file, target_path)
25+
26+
original_content = source_file.read_text()
27+
28+
function_to_optimize = FunctionToOptimize(
29+
function_name="sorter",
30+
file_path=target_path,
31+
parents=[],
32+
starting_line=None,
33+
ending_line=None,
34+
)
35+
test_cfg = TestConfig(
36+
tests_root=test_dir,
37+
project_root_path=test_dir,
38+
test_framework="pytest",
39+
tests_project_rootdir=test_dir,
40+
)
41+
args = argparse.Namespace(
42+
disable_imports_sorting=False,
43+
formatter_cmds=["uvx ruff check --exit-zero --fix $file", "uvx ruff format $file"],
44+
)
45+
optimizer = FunctionOptimizer(
46+
function_to_optimize=function_to_optimize,
47+
test_cfg=test_cfg,
48+
args=args,
49+
)
50+
51+
preexisting_functions_by_filepath = {
52+
target_path: {("lol", tuple())},
53+
}
54+
55+
# add a newline after the function definition
56+
target_content = target_path.read_text()
57+
target_content = target_content.replace("def sorter(arr):", "def sorter(arr):\n")
58+
assert target_content != original_content
59+
target_path.write_text(target_content)
60+
61+
optimizer.reformat_code_and_helpers(
62+
preexisting_functions_by_filepath=preexisting_functions_by_filepath,
63+
helper_functions=[],
64+
fto_path=target_path,
65+
original_code=optimizer.function_to_optimize_source_code,
66+
)
67+
content = target_path.read_text()
68+
assert content == original_content

0 commit comments

Comments
 (0)