codeflash/tests/test_instrument_tests.py

3230 lines
135 KiB
Python
Raw Normal View History

2024-05-15 11:47:05 +00:00
from __future__ import annotations
2024-03-08 20:15:05 +00:00
import ast
2024-10-18 22:43:26 +00:00
import math
import os
2024-01-14 06:36:57 +00:00
import sys
import tempfile
2024-10-13 00:40:07 +00:00
from pathlib import Path
from codeflash.code_utils.code_utils import get_run_tmp_file
from codeflash.code_utils.instrument_existing_tests import (
FunctionImportedAsVisitor,
inject_profiling_into_existing_test,
)
from codeflash.code_utils.line_profile_utils import add_decorator_imports
2024-10-29 23:39:47 +00:00
from codeflash.discovery.functions_to_optimize import FunctionToOptimize
2025-03-28 22:26:27 +00:00
from codeflash.models.models import (
CodeOptimizationContext,
2025-03-28 22:26:27 +00:00
CodePosition,
FunctionParent,
TestFile,
TestFiles,
TestingMode,
TestsInFile,
TestType,
2025-03-28 22:26:27 +00:00
)
from codeflash.optimization.function_optimizer import FunctionOptimizer
from codeflash.verification.verification_utils import TestConfig
codeflash_wrap_string = """def codeflash_wrap(wrapped, test_module_name, test_class_name, test_name, function_name, line_id, loop_index, codeflash_cur, codeflash_con, *args, **kwargs):
test_id = f'{{test_module_name}}:{{test_class_name}}:{{test_name}}:{{line_id}}:{{loop_index}}'
if not hasattr(codeflash_wrap, 'index'):
codeflash_wrap.index = {{}}
if test_id in codeflash_wrap.index:
codeflash_wrap.index[test_id] += 1
else:
codeflash_wrap.index[test_id] = 0
codeflash_test_index = codeflash_wrap.index[test_id]
invocation_id = f'{{line_id}}_{{codeflash_test_index}}'
2025-06-03 00:59:29 +00:00
test_stdout_tag = f"{{test_module_name}}:{{(test_class_name + '.' if test_class_name else '')}}{{test_name}}:{{function_name}}:{{loop_index}}:{{invocation_id}}"
2025-06-03 08:13:38 +00:00
print(f"!$######{{test_stdout_tag}}######$!")
exception = None
2024-12-10 15:30:50 +00:00
gc.disable()
try:
counter = time.perf_counter_ns()
return_value = wrapped(*args, **kwargs)
codeflash_duration = time.perf_counter_ns() - counter
except Exception as e:
codeflash_duration = time.perf_counter_ns() - counter
2024-12-11 20:43:06 +00:00
exception = e
gc.enable()
2025-06-03 08:13:38 +00:00
print(f"!######{{test_stdout_tag}}######!")
pickled_return_value = pickle.dumps(exception) if exception else pickle.dumps(return_value)
codeflash_cur.execute('INSERT INTO test_results VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', (test_module_name, test_class_name, test_name, function_name, loop_index, invocation_id, codeflash_duration, pickled_return_value, 'function_call'))
codeflash_con.commit()
if exception:
raise exception
return return_value
"""
codeflash_wrap_perfonly_string = """def codeflash_wrap(wrapped, test_module_name, test_class_name, test_name, function_name, line_id, loop_index, *args, **kwargs):
test_id = f'{{test_module_name}}:{{test_class_name}}:{{test_name}}:{{line_id}}:{{loop_index}}'
if not hasattr(codeflash_wrap, 'index'):
codeflash_wrap.index = {{}}
if test_id in codeflash_wrap.index:
codeflash_wrap.index[test_id] += 1
else:
codeflash_wrap.index[test_id] = 0
codeflash_test_index = codeflash_wrap.index[test_id]
invocation_id = f'{{line_id}}_{{codeflash_test_index}}'
2025-06-03 00:59:29 +00:00
test_stdout_tag = f"{{test_module_name}}:{{(test_class_name + '.' if test_class_name else '')}}{{test_name}}:{{function_name}}:{{loop_index}}:{{invocation_id}}"
print(f"!$######{{test_stdout_tag}}######$!")
2025-06-03 08:13:38 +00:00
exception = None
gc.disable()
try:
counter = time.perf_counter_ns()
return_value = wrapped(*args, **kwargs)
codeflash_duration = time.perf_counter_ns() - counter
except Exception as e:
codeflash_duration = time.perf_counter_ns() - counter
exception = e
gc.enable()
2025-06-03 00:59:29 +00:00
print(f"!######{{test_stdout_tag}}:{{codeflash_duration}}######!")
if exception:
raise exception
return return_value
"""
2024-05-15 11:47:05 +00:00
def test_perfinjector_bubble_sort() -> None:
code = """import unittest
from code_to_optimize.bubble_sort import sorter
class TestPigLatin(unittest.TestCase):
def test_sort(self):
input = [5, 4, 3, 2, 1, 0]
output = sorter(input)
self.assertEqual(output, [0, 1, 2, 3, 4, 5])
input = [5.0, 4.0, 3.0, 2.0, 1.0, 0.0]
output = sorter(input)
self.assertEqual(output, [0.0, 1.0, 2.0, 3.0, 4.0, 5.0])
input = list(reversed(range(5000)))
self.assertEqual(sorter(input), list(range(5000)))
"""
2024-05-23 02:05:22 +00:00
expected = """import gc
import os
import sqlite3
2024-05-23 02:05:22 +00:00
import time
import unittest
2024-04-18 01:57:43 +00:00
import dill as pickle
2024-06-05 20:58:51 +00:00
import timeout_decorator
2024-05-31 22:38:34 +00:00
2024-05-23 02:05:22 +00:00
from code_to_optimize.bubble_sort import sorter
2024-02-09 22:05:06 +00:00
def codeflash_wrap(wrapped, test_module_name, test_class_name, test_name, function_name, line_id, loop_index, codeflash_cur, codeflash_con, *args, **kwargs):
test_id = f'{{test_module_name}}:{{test_class_name}}:{{test_name}}:{{line_id}}:{{loop_index}}'
2024-02-09 22:05:06 +00:00
if not hasattr(codeflash_wrap, 'index'):
codeflash_wrap.index = {{}}
if test_id in codeflash_wrap.index:
codeflash_wrap.index[test_id] += 1
else:
codeflash_wrap.index[test_id] = 0
codeflash_test_index = codeflash_wrap.index[test_id]
invocation_id = f'{{line_id}}_{{codeflash_test_index}}'
2024-06-02 01:13:01 +00:00
"""
if sys.version_info < (3, 12):
2025-06-03 00:59:29 +00:00
expected += """test_stdout_tag = f"{{test_module_name}}:{{(test_class_name + '.' if test_class_name else '')}}{{test_name}}:{{function_name}}:{{loop_index}}:{{invocation_id}}"
print(f"!$######{{test_stdout_tag}}######$!")"""
2024-06-02 01:13:01 +00:00
else:
2025-06-03 08:13:38 +00:00
expected += """test_stdout_tag = f'{{test_module_name}}:{{(test_class_name + '.' if test_class_name else '')}}{{test_name}}:{{function_name}}:{{loop_index}}:{{invocation_id}}'
2025-06-03 00:59:29 +00:00
print(f'!$######{{test_stdout_tag}}######$!')"""
2024-06-02 01:13:01 +00:00
expected += """
exception = None
2024-12-10 15:30:50 +00:00
gc.disable()
try:
counter = time.perf_counter_ns()
return_value = wrapped(*args, **kwargs)
codeflash_duration = time.perf_counter_ns() - counter
except Exception as e:
codeflash_duration = time.perf_counter_ns() - counter
2024-12-11 20:43:06 +00:00
exception = e
gc.enable()
2025-06-03 08:13:38 +00:00
"""
if sys.version_info < (3, 12):
expected += """print(f"!######{{test_stdout_tag}}######!")"""
else:
expected += """print(f'!######{{test_stdout_tag}}######!')"""
expected += """
pickled_return_value = pickle.dumps(exception) if exception else pickle.dumps(return_value)
codeflash_cur.execute('INSERT INTO test_results VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', (test_module_name, test_class_name, test_name, function_name, loop_index, invocation_id, codeflash_duration, pickled_return_value, 'function_call'))
2024-02-09 22:05:06 +00:00
codeflash_con.commit()
if exception:
raise exception
2024-02-09 22:05:06 +00:00
return return_value
class TestPigLatin(unittest.TestCase):
2024-06-05 20:58:51 +00:00
@timeout_decorator.timeout(15)
def test_sort(self):
2024-10-03 19:06:48 +00:00
codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
codeflash_iteration = os.environ['CODEFLASH_TEST_ITERATION']
codeflash_con = sqlite3.connect(f'{tmp_dir_path}_{{codeflash_iteration}}.sqlite')
codeflash_cur = codeflash_con.cursor()
codeflash_cur.execute('CREATE TABLE IF NOT EXISTS test_results (test_module_path TEXT, test_class_name TEXT, test_function_name TEXT, function_getting_tested TEXT, loop_index INTEGER, iteration_id TEXT, runtime INTEGER, return_value BLOB, verification_type TEXT)')
input = [5, 4, 3, 2, 1, 0]
output = codeflash_wrap(sorter, '{module_path}', 'TestPigLatin', 'test_sort', 'sorter', '1', codeflash_loop_index, codeflash_cur, codeflash_con, input)
self.assertEqual(output, [0, 1, 2, 3, 4, 5])
input = [5.0, 4.0, 3.0, 2.0, 1.0, 0.0]
output = codeflash_wrap(sorter, '{module_path}', 'TestPigLatin', 'test_sort', 'sorter', '4', codeflash_loop_index, codeflash_cur, codeflash_con, input)
self.assertEqual(output, [0.0, 1.0, 2.0, 3.0, 4.0, 5.0])
input = list(reversed(range(5000)))
self.assertEqual(codeflash_wrap(sorter, '{module_path}', 'TestPigLatin', 'test_sort', 'sorter', '7', codeflash_loop_index, codeflash_cur, codeflash_con, input), list(range(5000)))
2024-05-23 02:05:22 +00:00
codeflash_con.close()
"""
with tempfile.NamedTemporaryFile(mode="w") as f:
f.write(code)
f.flush()
func = FunctionToOptimize(function_name="sorter", parents=[], file_path=Path(f.name))
2024-10-13 00:07:42 +00:00
original_cwd = Path.cwd()
run_cwd = Path(__file__).parent.parent.resolve()
os.chdir(run_cwd)
success, new_test = inject_profiling_into_existing_test(
2024-10-13 00:07:42 +00:00
Path(f.name),
[CodePosition(9, 17), CodePosition(13, 17), CodePosition(17, 17)],
func,
2024-10-13 00:07:42 +00:00
Path(f.name).parent,
"unittest",
)
os.chdir(original_cwd)
assert success
assert new_test == expected.format(
module_path=Path(f.name).name, tmp_dir_path=get_run_tmp_file(Path("test_return_values"))
)
2024-05-15 11:47:05 +00:00
def test_perfinjector_only_replay_test() -> None:
2024-04-18 01:57:43 +00:00
code = """import dill as pickle
import pytest
from codeflash.tracing.replay_test import get_next_arg_and_return
from codeflash.validation.equivalence import compare_results
from packagename.ml.yolo.image_reshaping_utils import prepare_image_for_yolo as packagename_ml_yolo_image_reshaping_utils_prepare_image_for_yolo
def test_prepare_image_for_yolo():
for arg_val_pkl, return_val_pkl in get_next_arg_and_return('/home/saurabh/packagename/traces/first.trace', 3):
args = pickle.loads(arg_val_pkl)
return_val_1= pickle.loads(return_val_pkl)
ret = packagename_ml_yolo_image_reshaping_utils_prepare_image_for_yolo(**args)
assert compare_results(return_val_1, ret)
"""
2024-05-23 02:05:22 +00:00
expected = """import gc
import os
import sqlite3
2024-05-23 02:05:22 +00:00
import time
2024-04-18 01:57:43 +00:00
import dill as pickle
2024-05-23 02:05:22 +00:00
import pytest
from packagename.ml.yolo.image_reshaping_utils import \\
prepare_image_for_yolo as \\
packagename_ml_yolo_image_reshaping_utils_prepare_image_for_yolo
2024-05-31 22:45:32 +00:00
2024-05-31 22:38:34 +00:00
from codeflash.tracing.replay_test import get_next_arg_and_return
from codeflash.validation.equivalence import compare_results
2024-05-23 02:05:22 +00:00
2024-02-09 22:05:06 +00:00
2024-09-30 19:18:11 +00:00
def codeflash_wrap(wrapped, test_module_name, test_class_name, test_name, function_name, line_id, loop_index, codeflash_cur, codeflash_con, *args, **kwargs):
test_id = f'{{test_module_name}}:{{test_class_name}}:{{test_name}}:{{line_id}}:{{loop_index}}'
2024-02-09 22:05:06 +00:00
if not hasattr(codeflash_wrap, 'index'):
codeflash_wrap.index = {{}}
if test_id in codeflash_wrap.index:
codeflash_wrap.index[test_id] += 1
else:
codeflash_wrap.index[test_id] = 0
codeflash_test_index = codeflash_wrap.index[test_id]
invocation_id = f'{{line_id}}_{{codeflash_test_index}}'
2024-06-02 01:13:01 +00:00
"""
if sys.version_info < (3, 12):
2025-06-03 08:13:38 +00:00
expected += """test_stdout_tag = f"{{test_module_name}}:{{(test_class_name + '.' if test_class_name else '')}}{{test_name}}:{{function_name}}:{{loop_index}}:{{invocation_id}}"
print(f"!$######{{test_stdout_tag}}######$!")"""
2024-06-02 01:13:01 +00:00
else:
2025-06-03 08:13:38 +00:00
expected += """test_stdout_tag = f'{{test_module_name}}:{{(test_class_name + '.' if test_class_name else '')}}{{test_name}}:{{function_name}}:{{loop_index}}:{{invocation_id}}'
print(f'!$######{{test_stdout_tag}}######$!')"""
2024-06-02 01:13:01 +00:00
expected += """
exception = None
2024-12-10 15:30:50 +00:00
gc.disable()
try:
counter = time.perf_counter_ns()
return_value = wrapped(*args, **kwargs)
codeflash_duration = time.perf_counter_ns() - counter
except Exception as e:
codeflash_duration = time.perf_counter_ns() - counter
2024-12-11 20:43:06 +00:00
exception = e
gc.enable()
2025-06-03 08:13:38 +00:00
"""
if sys.version_info < (3, 12):
expected += """print(f"!######{{test_stdout_tag}}######!")"""
else:
expected += """print(f'!######{{test_stdout_tag}}######!')"""
expected += """
pickled_return_value = pickle.dumps(exception) if exception else pickle.dumps(return_value)
codeflash_cur.execute('INSERT INTO test_results VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', (test_module_name, test_class_name, test_name, function_name, loop_index, invocation_id, codeflash_duration, pickled_return_value, 'function_call'))
2024-02-09 22:05:06 +00:00
codeflash_con.commit()
if exception:
raise exception
2024-02-09 22:05:06 +00:00
return return_value
2024-09-30 18:03:42 +00:00
def test_prepare_image_for_yolo():
2024-10-03 19:06:48 +00:00
codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
codeflash_iteration = os.environ['CODEFLASH_TEST_ITERATION']
codeflash_con = sqlite3.connect(f'{tmp_dir_path}_{{codeflash_iteration}}.sqlite')
codeflash_cur = codeflash_con.cursor()
codeflash_cur.execute('CREATE TABLE IF NOT EXISTS test_results (test_module_path TEXT, test_class_name TEXT, test_function_name TEXT, function_getting_tested TEXT, loop_index INTEGER, iteration_id TEXT, runtime INTEGER, return_value BLOB, verification_type TEXT)')
2024-01-14 06:36:57 +00:00
"""
2024-01-14 06:40:59 +00:00
if sys.version_info < (3, 11):
2024-01-14 06:36:57 +00:00
expected += """ for (arg_val_pkl, return_val_pkl) in get_next_arg_and_return('/home/saurabh/packagename/traces/first.trace', 3):
"""
else:
expected += """ for arg_val_pkl, return_val_pkl in get_next_arg_and_return('/home/saurabh/packagename/traces/first.trace', 3):
"""
expected += """ args = pickle.loads(arg_val_pkl)
return_val_1 = pickle.loads(return_val_pkl)
2024-09-30 19:18:11 +00:00
ret = codeflash_wrap(packagename_ml_yolo_image_reshaping_utils_prepare_image_for_yolo, '{module_path}', None, 'test_prepare_image_for_yolo', 'packagename_ml_yolo_image_reshaping_utils_prepare_image_for_yolo', '0_2', codeflash_loop_index, codeflash_cur, codeflash_con, **args)
assert compare_results(return_val_1, ret)
2024-05-23 02:05:22 +00:00
codeflash_con.close()
"""
with tempfile.NamedTemporaryFile(mode="w") as f:
f.write(code)
f.flush()
2025-01-24 23:23:35 +00:00
func = FunctionToOptimize(function_name="prepare_image_for_yolo", parents=[], file_path=Path("module.py"))
2024-10-13 00:07:42 +00:00
original_cwd = Path.cwd()
run_cwd = Path(__file__).parent.parent.resolve()
os.chdir(run_cwd)
success, new_test = inject_profiling_into_existing_test(
Path(f.name), [CodePosition(10, 14)], func, Path(f.name).parent, "pytest"
)
os.chdir(original_cwd)
assert success
assert new_test == expected.format(
module_path=Path(f.name).name, tmp_dir_path=get_run_tmp_file(Path("test_return_values"))
)
2024-02-09 22:05:06 +00:00
2024-05-15 11:47:05 +00:00
def test_perfinjector_bubble_sort_results() -> None:
computed_fn_opt = False
2024-02-09 22:05:06 +00:00
code = """from code_to_optimize.bubble_sort import sorter
2025-06-03 09:04:30 +00:00
import datetime
2024-02-09 22:05:06 +00:00
def test_sort():
input = [5, 4, 3, 2, 1, 0]
2025-06-03 09:04:30 +00:00
print(datetime.datetime.now().isoformat())
2024-02-09 22:05:06 +00:00
output = sorter(input)
assert output == [0, 1, 2, 3, 4, 5]
input = [5.0, 4.0, 3.0, 2.0, 1.0, 0.0]
output = sorter(input)
assert output == [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]"""
2024-10-30 03:02:39 +00:00
expected = (
2025-06-03 09:04:30 +00:00
"""import datetime
import gc
2024-02-09 22:05:06 +00:00
import os
import sqlite3
2024-05-23 02:05:22 +00:00
import time
2024-04-18 01:57:43 +00:00
import dill as pickle
2024-05-31 22:38:34 +00:00
2024-05-23 02:05:22 +00:00
from code_to_optimize.bubble_sort import sorter
2024-02-09 22:05:06 +00:00
"""
2024-10-30 03:02:39 +00:00
+ codeflash_wrap_string
+ """
2024-09-30 18:03:42 +00:00
def test_sort():
2024-10-03 19:06:48 +00:00
codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
codeflash_iteration = os.environ['CODEFLASH_TEST_ITERATION']
2024-02-09 22:05:06 +00:00
codeflash_con = sqlite3.connect(f'{tmp_dir_path}_{{codeflash_iteration}}.sqlite')
codeflash_cur = codeflash_con.cursor()
codeflash_cur.execute('CREATE TABLE IF NOT EXISTS test_results (test_module_path TEXT, test_class_name TEXT, test_function_name TEXT, function_getting_tested TEXT, loop_index INTEGER, iteration_id TEXT, runtime INTEGER, return_value BLOB, verification_type TEXT)')
2024-02-09 22:05:06 +00:00
input = [5, 4, 3, 2, 1, 0]
2025-06-03 09:04:30 +00:00
print(datetime.datetime.now().isoformat())
output = codeflash_wrap(sorter, '{module_path}', None, 'test_sort', 'sorter', '2', codeflash_loop_index, codeflash_cur, codeflash_con, input)
2024-02-09 22:05:06 +00:00
assert output == [0, 1, 2, 3, 4, 5]
input = [5.0, 4.0, 3.0, 2.0, 1.0, 0.0]
2025-06-03 09:04:30 +00:00
output = codeflash_wrap(sorter, '{module_path}', None, 'test_sort', 'sorter', '5', codeflash_loop_index, codeflash_cur, codeflash_con, input)
2024-02-09 22:05:06 +00:00
assert output == [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
2024-05-23 02:05:22 +00:00
codeflash_con.close()
"""
2024-10-30 03:02:39 +00:00
)
2024-02-09 22:05:06 +00:00
expected_perfonly = (
2025-06-03 09:04:30 +00:00
"""import datetime
import gc
import os
import time
from code_to_optimize.bubble_sort import sorter
"""
+ codeflash_wrap_perfonly_string
+ """
def test_sort():
codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
input = [5, 4, 3, 2, 1, 0]
2025-06-03 23:09:35 +00:00
print(datetime.datetime.now().isoformat())
2025-06-03 09:04:30 +00:00
output = codeflash_wrap(sorter, '{module_path}', None, 'test_sort', 'sorter', '2', codeflash_loop_index, input)
assert output == [0, 1, 2, 3, 4, 5]
input = [5.0, 4.0, 3.0, 2.0, 1.0, 0.0]
2025-06-03 09:04:30 +00:00
output = codeflash_wrap(sorter, '{module_path}', None, 'test_sort', 'sorter', '5', codeflash_loop_index, input)
assert output == [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
"""
)
2024-02-10 00:46:38 +00:00
test_path = (
2024-10-13 00:07:42 +00:00
Path(__file__).parent.resolve()
/ "../code_to_optimize/tests/pytest/test_perfinjector_bubble_sort_results_temp.py"
2024-10-09 01:37:13 +00:00
).resolve()
test_path_perf = (
Path(__file__).parent.resolve()
/ "../code_to_optimize/tests/pytest/test_perfinjector_bubble_sort_results_perf_temp.py"
).resolve()
try:
2024-10-13 00:07:42 +00:00
with test_path.open("w") as f:
f.write(code)
code_path = (Path(__file__).parent.resolve() / "../code_to_optimize/bubble_sort.py").resolve()
2024-10-13 00:07:42 +00:00
tests_root = Path(__file__).parent.resolve() / "../code_to_optimize/tests/pytest/"
project_root_path = (Path(__file__).parent / "..").resolve()
original_cwd = Path.cwd()
run_cwd = Path(__file__).parent.parent.resolve()
func = FunctionToOptimize(function_name="sorter", parents=[], file_path=code_path)
2024-10-13 00:07:42 +00:00
os.chdir(run_cwd)
success, new_test = inject_profiling_into_existing_test(
2024-12-30 03:11:20 +00:00
test_path,
2025-06-03 23:09:35 +00:00
[CodePosition(8, 14), CodePosition(12, 14)],
2024-12-30 03:11:20 +00:00
func,
project_root_path,
"pytest",
mode=TestingMode.BEHAVIOR,
)
os.chdir(original_cwd)
assert success
2024-10-13 00:40:07 +00:00
assert new_test is not None
2024-05-31 23:36:43 +00:00
assert new_test.replace('"', "'") == expected.format(
2024-10-09 01:37:13 +00:00
module_path="code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_results_temp",
2024-10-13 00:40:07 +00:00
tmp_dir_path=get_run_tmp_file(Path("test_return_values")),
2024-05-31 23:36:43 +00:00
).replace('"', "'")
2024-10-09 01:37:13 +00:00
success, new_perf_test = inject_profiling_into_existing_test(
2024-12-30 03:11:20 +00:00
test_path,
2025-06-03 23:09:35 +00:00
[CodePosition(8, 14), CodePosition(12, 14)],
2024-12-30 03:11:20 +00:00
func,
project_root_path,
"pytest",
mode=TestingMode.PERFORMANCE,
)
assert success
assert new_perf_test is not None
assert new_perf_test.replace('"', "'") == expected_perfonly.format(
module_path="code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_results_temp",
tmp_dir_path=get_run_tmp_file(Path("test_return_values")),
).replace('"', "'")
2024-10-13 00:07:42 +00:00
with test_path.open("w") as f:
2024-10-09 01:37:13 +00:00
f.write(new_test)
# Overwrite old test with new instrumented test
2025-01-24 23:23:35 +00:00
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",
2024-10-10 04:37:16 +00:00
)
func_optimizer = FunctionOptimizer(function_to_optimize=func, test_cfg=test_config)
2024-10-09 01:37:13 +00:00
test_env = os.environ.copy()
test_env["CODEFLASH_TEST_ITERATION"] = "0"
test_env["CODEFLASH_LOOP_INDEX"] = "1"
test_type = TestType.EXISTING_UNIT_TEST
test_files = TestFiles(
test_files=[
TestFile(
instrumented_behavior_file_path=test_path,
test_type=test_type,
original_file_path=test_path,
benchmarking_file_path=test_path_perf,
)
]
2024-10-09 01:37:13 +00:00
)
test_results, coverage_data = func_optimizer.run_and_parse_tests(
2024-12-30 03:11:20 +00:00
testing_type=TestingMode.BEHAVIOR,
2024-10-09 01:37:13 +00:00
test_env=test_env,
test_files=test_files,
optimization_iteration=0,
2024-10-10 04:37:16 +00:00
pytest_min_loops=1,
pytest_max_loops=1,
testing_time=0.1,
2024-10-09 01:37:13 +00:00
)
assert test_results[0].id.function_getting_tested == "sorter"
2025-06-03 23:09:35 +00:00
assert test_results[0].id.iteration_id == "2_0"
2024-10-09 01:37:13 +00:00
assert test_results[0].id.test_class_name is None
assert test_results[0].id.test_function_name == "test_sort"
assert (
test_results[0].id.test_module_path
== "code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_results_temp"
)
assert test_results[0].runtime > 0
assert test_results[0].did_pass
assert test_results[0].return_value == ([0, 1, 2, 3, 4, 5],)
2024-10-09 01:37:13 +00:00
assert test_results[1].id.function_getting_tested == "sorter"
2025-06-03 23:09:35 +00:00
assert test_results[1].id.iteration_id == "5_0"
2024-10-09 01:37:13 +00:00
assert test_results[1].id.test_class_name is None
assert test_results[1].id.test_function_name == "test_sort"
assert (
test_results[1].id.test_module_path
== "code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_results_temp"
)
assert test_results[1].runtime > 0
assert test_results[1].did_pass
with test_path_perf.open("w") as f:
f.write(new_perf_test)
test_results_perf, _ = func_optimizer.run_and_parse_tests(
2024-12-30 03:11:20 +00:00
testing_type=TestingMode.PERFORMANCE,
test_env=test_env,
test_files=test_files,
optimization_iteration=0,
pytest_min_loops=1,
pytest_max_loops=1,
testing_time=0.1,
)
assert test_results_perf[0].id.function_getting_tested == "sorter"
2025-06-03 23:09:35 +00:00
assert test_results_perf[0].id.iteration_id == "2_0"
assert test_results_perf[0].id.test_class_name is None
assert test_results_perf[0].id.test_function_name == "test_sort"
assert (
test_results_perf[0].id.test_module_path
== "code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_results_temp"
)
assert test_results_perf[0].runtime > 0
assert test_results_perf[0].did_pass
assert test_results_perf[0].return_value is None
2025-06-03 08:13:38 +00:00
assert (
test_results_perf[0].stdout
== """codeflash stdout: Sorting list
result: [0, 1, 2, 3, 4, 5]
"""
)
assert test_results_perf[1].id.function_getting_tested == "sorter"
2025-06-03 23:09:35 +00:00
assert test_results_perf[1].id.iteration_id == "5_0"
assert test_results_perf[1].id.test_class_name is None
assert test_results_perf[1].id.test_function_name == "test_sort"
assert (
test_results_perf[1].id.test_module_path
== "code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_results_temp"
)
assert test_results_perf[1].runtime > 0
assert test_results_perf[1].did_pass
2025-02-21 08:18:37 +00:00
2025-06-03 08:13:38 +00:00
out_str = """codeflash stdout: Sorting list
result: [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
"""
assert test_results_perf[1].stdout == out_str
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
computed_fn_opt = True
2025-06-03 08:13:38 +00:00
line_profiler_output_file = add_decorator_imports(func_optimizer.function_to_optimize, code_context)
line_profile_results, _ = func_optimizer.run_and_parse_tests(
testing_type=TestingMode.LINE_PROFILE,
test_env=test_env,
test_files=test_files,
optimization_iteration=0,
pytest_min_loops=1,
pytest_max_loops=1,
testing_time=0.1,
2025-06-03 08:13:38 +00:00
line_profiler_output_file=line_profiler_output_file,
)
tmp_lpr = list(line_profile_results["timings"].keys())
2025-06-03 08:13:38 +00:00
assert len(tmp_lpr) == 1 and line_profile_results["timings"][tmp_lpr[0]][0][1] == 2
finally:
if computed_fn_opt:
func_optimizer.write_code_and_helpers(
2025-06-03 08:13:38 +00:00
func_optimizer.function_to_optimize_source_code,
original_helper_code,
func_optimizer.function_to_optimize.file_path,
)
2024-10-13 00:07:42 +00:00
test_path.unlink(missing_ok=True)
test_path_perf.unlink(missing_ok=True)
2024-02-09 22:05:06 +00:00
2024-05-15 11:47:05 +00:00
def test_perfinjector_bubble_sort_parametrized_results() -> None:
computed_fn_opt = False
2024-02-09 22:05:06 +00:00
code = """from code_to_optimize.bubble_sort import sorter
import pytest
@pytest.mark.parametrize(
"input, expected_output",
[
([5, 4, 3, 2, 1, 0], [0, 1, 2, 3, 4, 5]),
([5.0, 4.0, 3.0, 2.0, 1.0, 0.0], [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]),
(list(reversed(range(50))), list(range(50))),
],
)
def test_sort_parametrized(input, expected_output):
output = sorter(input)
assert output == expected_output
"""
2024-10-30 03:02:39 +00:00
expected = (
"""import gc
2024-02-09 22:05:06 +00:00
import os
import sqlite3
2024-05-23 02:05:22 +00:00
import time
2024-04-18 01:57:43 +00:00
import dill as pickle
2024-05-23 02:05:22 +00:00
import pytest
2024-05-31 22:38:34 +00:00
2024-05-23 02:05:22 +00:00
from code_to_optimize.bubble_sort import sorter
2024-02-09 22:05:06 +00:00
"""
2024-10-30 03:02:39 +00:00
+ codeflash_wrap_string
+ """
2024-02-09 22:05:06 +00:00
@pytest.mark.parametrize('input, expected_output', [([5, 4, 3, 2, 1, 0], [0, 1, 2, 3, 4, 5]), ([5.0, 4.0, 3.0, 2.0, 1.0, 0.0], [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]), (list(reversed(range(50))), list(range(50)))])
2024-09-30 18:03:42 +00:00
def test_sort_parametrized(input, expected_output):
2024-10-03 19:06:48 +00:00
codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
codeflash_iteration = os.environ['CODEFLASH_TEST_ITERATION']
2024-02-09 22:05:06 +00:00
codeflash_con = sqlite3.connect(f'{tmp_dir_path}_{{codeflash_iteration}}.sqlite')
codeflash_cur = codeflash_con.cursor()
codeflash_cur.execute('CREATE TABLE IF NOT EXISTS test_results (test_module_path TEXT, test_class_name TEXT, test_function_name TEXT, function_getting_tested TEXT, loop_index INTEGER, iteration_id TEXT, runtime INTEGER, return_value BLOB, verification_type TEXT)')
output = codeflash_wrap(sorter, '{module_path}', None, 'test_sort_parametrized', 'sorter', '0', codeflash_loop_index, codeflash_cur, codeflash_con, input)
2024-02-09 22:05:06 +00:00
assert output == expected_output
2024-05-23 02:05:22 +00:00
codeflash_con.close()
"""
2024-10-30 03:02:39 +00:00
)
expected_perfonly = (
"""import gc
import os
import time
import pytest
from code_to_optimize.bubble_sort import sorter
"""
+ codeflash_wrap_perfonly_string
+ """
@pytest.mark.parametrize('input, expected_output', [([5, 4, 3, 2, 1, 0], [0, 1, 2, 3, 4, 5]), ([5.0, 4.0, 3.0, 2.0, 1.0, 0.0], [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]), (list(reversed(range(50))), list(range(50)))])
def test_sort_parametrized(input, expected_output):
codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
output = codeflash_wrap(sorter, '{module_path}', None, 'test_sort_parametrized', 'sorter', '0', codeflash_loop_index, input)
assert output == expected_output
"""
)
code_path = (Path(__file__).parent.resolve() / "../code_to_optimize/bubble_sort.py").resolve()
2024-02-10 00:46:38 +00:00
test_path = (
2024-10-13 00:07:42 +00:00
Path(__file__).parent.resolve()
/ "../code_to_optimize/tests/pytest/test_perfinjector_bubble_sort_parametrized_results_temp.py"
).resolve()
test_path_perf = (
Path(__file__).parent.resolve()
/ "../code_to_optimize/tests/pytest/test_perfinjector_bubble_sort_parametrized_results_temp_perf.py"
).resolve()
try:
with open(test_path, "w") as f:
f.write(code)
2024-02-09 22:05:06 +00:00
2024-10-13 00:07:42 +00:00
tests_root = (Path(__file__).parent.resolve() / "../code_to_optimize/tests/pytest/").resolve()
project_root_path = (Path(__file__).parent.resolve() / "../").resolve()
original_cwd = Path.cwd()
run_cwd = Path(__file__).parent.parent.resolve()
2024-02-10 00:46:38 +00:00
func = FunctionToOptimize(function_name="sorter", parents=[], file_path=code_path)
2024-10-13 00:07:42 +00:00
os.chdir(run_cwd)
success, new_test = inject_profiling_into_existing_test(
2025-06-03 23:09:35 +00:00
test_path, [CodePosition(14, 13)], func, project_root_path, "pytest", mode=TestingMode.BEHAVIOR
)
assert success
success, new_test_perf = inject_profiling_into_existing_test(
2025-06-03 23:09:35 +00:00
test_path, [CodePosition(14, 13)], func, project_root_path, "pytest", mode=TestingMode.PERFORMANCE
)
os.chdir(original_cwd)
assert success
2024-10-13 00:40:07 +00:00
assert new_test is not None
2024-05-31 23:36:43 +00:00
assert new_test.replace('"', "'") == expected.format(
2024-10-10 05:10:44 +00:00
module_path="code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_parametrized_results_temp",
2024-10-13 00:40:07 +00:00
tmp_dir_path=get_run_tmp_file(Path("test_return_values")),
2024-05-31 23:36:43 +00:00
).replace('"', "'")
assert new_test_perf.replace('"', "'") == expected_perfonly.format(
module_path="code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_parametrized_results_temp",
tmp_dir_path=get_run_tmp_file(Path("test_return_values")),
).replace('"', "'")
#
2024-10-10 05:10:44 +00:00
# Overwrite old test with new instrumented test
2024-10-13 00:07:42 +00:00
with test_path.open("w") as f:
2024-10-10 05:10:44 +00:00
f.write(new_test)
with test_path_perf.open("w") as f:
f.write(new_test_perf)
2024-10-10 05:10:44 +00:00
test_env = os.environ.copy()
test_env["CODEFLASH_TEST_ITERATION"] = "0"
test_type = TestType.EXISTING_UNIT_TEST
test_files = TestFiles(
test_files=[
TestFile(
instrumented_behavior_file_path=test_path,
test_type=test_type,
original_file_path=test_path,
benchmarking_file_path=test_path_perf,
)
]
2024-10-10 05:10:44 +00:00
)
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",
2024-10-10 05:10:44 +00:00
)
func_optimizer = FunctionOptimizer(function_to_optimize=func, test_cfg=test_config)
test_results, coverage_data = func_optimizer.run_and_parse_tests(
2024-12-30 03:11:20 +00:00
testing_type=TestingMode.BEHAVIOR,
2024-10-10 05:10:44 +00:00
test_env=test_env,
test_files=test_files,
optimization_iteration=0,
pytest_min_loops=1,
pytest_max_loops=1,
testing_time=0.1,
)
assert test_results[0].id.function_getting_tested == "sorter"
assert test_results[0].id.iteration_id == "0_0"
assert test_results[0].id.test_class_name is None
assert test_results[0].id.test_function_name == "test_sort_parametrized"
assert (
test_results[0].id.test_module_path
== "code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_parametrized_results_temp"
)
assert test_results[0].runtime > 0
assert test_results[0].did_pass
2025-06-03 08:13:38 +00:00
assert (
test_results[0].stdout
== """codeflash stdout: Sorting list
result: [0, 1, 2, 3, 4, 5]
"""
)
2024-10-10 05:10:44 +00:00
assert test_results[1].id.function_getting_tested == "sorter"
assert test_results[1].id.iteration_id == "0_1"
assert test_results[1].id.test_class_name is None
assert test_results[1].id.test_function_name == "test_sort_parametrized"
assert (
test_results[1].id.test_module_path
== "code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_parametrized_results_temp"
)
assert test_results[1].runtime > 0
assert test_results[1].did_pass
2025-06-03 08:13:38 +00:00
assert (
test_results[1].stdout
== """codeflash stdout: Sorting list
result: [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
"""
)
2024-10-10 05:10:44 +00:00
assert test_results[2].id.function_getting_tested == "sorter"
assert test_results[2].id.iteration_id == "0_2"
assert test_results[2].id.test_class_name is None
assert test_results[2].id.test_function_name == "test_sort_parametrized"
assert (
test_results[2].id.test_module_path
== "code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_parametrized_results_temp"
)
assert test_results[2].runtime > 0
assert test_results[2].did_pass
2024-02-09 22:05:06 +00:00
test_results_perf, coverage_data = func_optimizer.run_and_parse_tests(
2024-12-30 03:11:20 +00:00
testing_type=TestingMode.PERFORMANCE,
test_env=test_env,
test_files=test_files,
optimization_iteration=0,
pytest_min_loops=1,
pytest_max_loops=1,
testing_time=0.1,
)
assert test_results_perf[0].id.function_getting_tested == "sorter"
assert test_results_perf[0].id.iteration_id == "0_0"
assert test_results_perf[0].id.test_class_name is None
assert test_results_perf[0].id.test_function_name == "test_sort_parametrized"
assert (
test_results_perf[0].id.test_module_path
== "code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_parametrized_results_temp"
)
assert test_results_perf[0].runtime > 0
assert test_results_perf[0].did_pass
assert test_results_perf[0].return_value is None
assert test_results_perf[1].id.function_getting_tested == "sorter"
assert test_results_perf[1].id.iteration_id == "0_1"
assert test_results_perf[1].id.test_class_name is None
assert test_results_perf[1].id.test_function_name == "test_sort_parametrized"
assert (
test_results_perf[1].id.test_module_path
== "code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_parametrized_results_temp"
)
assert test_results_perf[1].runtime > 0
assert test_results_perf[1].did_pass
out_str = """codeflash stdout: Sorting list
2025-06-03 08:13:38 +00:00
result: [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
"""
assert out_str == test_results_perf[1].stdout
2025-02-21 02:23:16 +00:00
assert test_results_perf[2].id.function_getting_tested == "sorter"
assert test_results_perf[2].id.iteration_id == "0_2"
assert test_results_perf[2].id.test_class_name is None
assert test_results_perf[2].id.test_function_name == "test_sort_parametrized"
assert (
test_results_perf[2].id.test_module_path
== "code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_parametrized_results_temp"
)
assert test_results_perf[2].runtime > 0
assert test_results_perf[2].did_pass
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
computed_fn_opt = True
2025-06-03 08:13:38 +00:00
line_profiler_output_file = add_decorator_imports(func_optimizer.function_to_optimize, code_context)
line_profile_results, _ = func_optimizer.run_and_parse_tests(
testing_type=TestingMode.LINE_PROFILE,
test_env=test_env,
test_files=test_files,
optimization_iteration=0,
pytest_min_loops=1,
pytest_max_loops=1,
testing_time=0.1,
2025-06-03 08:13:38 +00:00
line_profiler_output_file=line_profiler_output_file,
)
tmp_lpr = list(line_profile_results["timings"].keys())
2025-06-03 08:13:38 +00:00
assert len(tmp_lpr) == 1 and line_profile_results["timings"][tmp_lpr[0]][0][1] == 3
finally:
if computed_fn_opt:
func_optimizer.write_code_and_helpers(
2025-06-03 08:13:38 +00:00
func_optimizer.function_to_optimize_source_code,
original_helper_code,
func_optimizer.function_to_optimize.file_path,
)
2024-10-13 00:07:42 +00:00
test_path.unlink(missing_ok=True)
test_path_perf.unlink(missing_ok=True)
2024-02-09 22:05:06 +00:00
2024-05-15 11:47:05 +00:00
def test_perfinjector_bubble_sort_parametrized_loop_results() -> None:
computed_fn_opt = False
2024-02-09 22:05:06 +00:00
code = """from code_to_optimize.bubble_sort import sorter
import pytest
@pytest.mark.parametrize(
"input, expected_output",
[
([5, 4, 3, 2, 1, 0], [0, 1, 2, 3, 4, 5]),
([5.0, 4.0, 3.0, 2.0, 1.0, 0.0], [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]),
(list(reversed(range(50))), list(range(50))),
],
)
def test_sort_parametrized_loop(input, expected_output):
2024-02-09 22:05:06 +00:00
for i in range(2):
output = sorter(input)
assert output == expected_output
"""
2024-10-30 03:02:39 +00:00
expected = (
"""import gc
2024-02-09 22:05:06 +00:00
import os
import sqlite3
2024-05-23 02:05:22 +00:00
import time
2024-04-18 01:57:43 +00:00
import dill as pickle
2024-05-23 02:05:22 +00:00
import pytest
2024-05-31 22:38:34 +00:00
2024-05-23 02:05:22 +00:00
from code_to_optimize.bubble_sort import sorter
2024-02-09 22:05:06 +00:00
"""
2024-10-30 03:02:39 +00:00
+ codeflash_wrap_string
+ """
2024-02-09 22:05:06 +00:00
@pytest.mark.parametrize('input, expected_output', [([5, 4, 3, 2, 1, 0], [0, 1, 2, 3, 4, 5]), ([5.0, 4.0, 3.0, 2.0, 1.0, 0.0], [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]), (list(reversed(range(50))), list(range(50)))])
def test_sort_parametrized_loop(input, expected_output):
2024-10-03 19:06:48 +00:00
codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
codeflash_iteration = os.environ['CODEFLASH_TEST_ITERATION']
2024-02-09 22:05:06 +00:00
codeflash_con = sqlite3.connect(f'{tmp_dir_path}_{{codeflash_iteration}}.sqlite')
codeflash_cur = codeflash_con.cursor()
codeflash_cur.execute('CREATE TABLE IF NOT EXISTS test_results (test_module_path TEXT, test_class_name TEXT, test_function_name TEXT, function_getting_tested TEXT, loop_index INTEGER, iteration_id TEXT, runtime INTEGER, return_value BLOB, verification_type TEXT)')
2024-02-09 22:05:06 +00:00
for i in range(2):
output = codeflash_wrap(sorter, '{module_path}', None, 'test_sort_parametrized_loop', 'sorter', '0_0', codeflash_loop_index, codeflash_cur, codeflash_con, input)
2024-02-09 22:05:06 +00:00
assert output == expected_output
2024-05-23 02:05:22 +00:00
codeflash_con.close()
"""
2024-10-30 03:02:39 +00:00
)
expected_perf = (
"""import gc
import os
import time
import pytest
from code_to_optimize.bubble_sort import sorter
"""
+ codeflash_wrap_perfonly_string
+ """
@pytest.mark.parametrize('input, expected_output', [([5, 4, 3, 2, 1, 0], [0, 1, 2, 3, 4, 5]), ([5.0, 4.0, 3.0, 2.0, 1.0, 0.0], [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]), (list(reversed(range(50))), list(range(50)))])
def test_sort_parametrized_loop(input, expected_output):
codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
for i in range(2):
output = codeflash_wrap(sorter, '{module_path}', None, 'test_sort_parametrized_loop', 'sorter', '0_0', codeflash_loop_index, input)
assert output == expected_output
"""
)
code_path = (Path(__file__).parent.resolve() / "../code_to_optimize/bubble_sort.py").resolve()
2024-02-10 00:46:38 +00:00
test_path = (
2024-10-13 00:07:42 +00:00
Path(__file__).parent.resolve()
/ "../code_to_optimize/tests/pytest/test_perfinjector_bubble_sort_parametrized_loop_results_temp.py"
2024-10-10 05:10:44 +00:00
).resolve()
test_path_behavior = (
Path(__file__).parent.resolve()
/ "../code_to_optimize/tests/pytest/test_perfinjector_bubble_sort_parametrized_loop_results_temp.py"
).resolve()
test_path_perf = (
Path(__file__).parent.resolve()
/ "../code_to_optimize/tests/pytest/test_perfinjector_bubble_sort_parametrized_loop_results_temp_perf.py"
).resolve()
try:
with open(test_path, "w") as f:
f.write(code)
2024-02-10 00:46:38 +00:00
2024-10-13 00:07:42 +00:00
tests_root = (Path(__file__).parent.resolve() / "../code_to_optimize/tests/pytest/").resolve()
project_root_path = (Path(__file__).parent.resolve() / "../").resolve()
original_cwd = Path.cwd()
run_cwd = Path(__file__).parent.parent.resolve()
func = FunctionToOptimize(function_name="sorter", parents=[], file_path=code_path)
2024-10-13 00:07:42 +00:00
os.chdir(run_cwd)
success, new_test = inject_profiling_into_existing_test(
2024-12-30 03:11:20 +00:00
test_path, [CodePosition(15, 17)], func, project_root_path, "pytest", mode=TestingMode.BEHAVIOR
)
assert success
success, new_test_perf = inject_profiling_into_existing_test(
2024-12-30 03:11:20 +00:00
test_path, [CodePosition(15, 17)], func, project_root_path, "pytest", mode=TestingMode.PERFORMANCE
)
os.chdir(original_cwd)
assert success
2024-10-13 00:40:07 +00:00
assert new_test is not None
2024-05-31 23:36:43 +00:00
assert new_test.replace('"', "'") == expected.format(
2024-10-10 05:10:44 +00:00
module_path="code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_parametrized_loop_results_temp",
2024-10-13 00:40:07 +00:00
tmp_dir_path=get_run_tmp_file(Path("test_return_values")),
2024-05-31 23:36:43 +00:00
).replace('"', "'")
2024-10-10 05:10:44 +00:00
# Overwrite old test with new instrumented test
with test_path_behavior.open("w") as f:
2024-10-10 05:10:44 +00:00
f.write(new_test)
assert new_test_perf.replace('"', "'") == expected_perf.format(
module_path="code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_parametrized_loop_results_temp",
tmp_dir_path=get_run_tmp_file(Path("test_return_values")),
).replace('"', "'")
# Overwrite old test with new instrumented test
with test_path_perf.open("w") as f:
f.write(new_test_perf)
2024-10-10 05:10:44 +00:00
test_env = os.environ.copy()
test_env["CODEFLASH_TEST_ITERATION"] = "0"
test_type = TestType.EXISTING_UNIT_TEST
test_files = TestFiles(
test_files=[
TestFile(
instrumented_behavior_file_path=test_path_behavior,
test_type=test_type,
original_file_path=test_path,
benchmarking_file_path=test_path_perf,
tests_in_file=[
TestsInFile(
test_file=test_path,
test_class=None,
test_function="test_sort_parametrized_loop",
test_type=TestType.EXISTING_UNIT_TEST,
)
],
)
]
2024-10-10 05:10:44 +00:00
)
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_optimizer = FunctionOptimizer(function_to_optimize=func, test_cfg=test_config)
test_results, coverage_data = func_optimizer.run_and_parse_tests(
2024-12-30 03:11:20 +00:00
testing_type=TestingMode.BEHAVIOR,
2024-10-10 05:10:44 +00:00
test_env=test_env,
test_files=test_files,
optimization_iteration=0,
pytest_min_loops=1,
pytest_max_loops=1,
testing_time=0.1,
)
assert test_results[0].id.function_getting_tested == "sorter"
assert test_results[0].id.iteration_id == "0_0_0"
assert test_results[0].id.test_class_name is None
assert test_results[0].id.test_function_name == "test_sort_parametrized_loop"
assert (
test_results[0].id.test_module_path
== "code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_parametrized_loop_results_temp"
)
assert test_results[0].runtime > 0
assert test_results[0].did_pass
assert test_results[0].return_value == ([0, 1, 2, 3, 4, 5],)
2025-06-03 08:13:38 +00:00
out_str = """codeflash stdout: Sorting list
result: [0, 1, 2, 3, 4, 5]
"""
assert test_results[0].stdout == out_str
2024-10-10 05:10:44 +00:00
assert test_results[1].id.function_getting_tested == "sorter"
assert test_results[1].id.iteration_id == "0_0_1"
assert test_results[1].id.test_class_name is None
assert test_results[1].id.test_function_name == "test_sort_parametrized_loop"
assert (
test_results[1].id.test_module_path
== "code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_parametrized_loop_results_temp"
)
assert test_results[1].runtime > 0
assert test_results[1].did_pass
2025-06-03 08:13:38 +00:00
assert test_results[1].stdout == out_str
2024-10-10 05:10:44 +00:00
assert test_results[2].id.function_getting_tested == "sorter"
assert test_results[2].id.iteration_id == "0_0_2"
assert test_results[2].id.test_class_name is None
assert test_results[2].id.test_function_name == "test_sort_parametrized_loop"
assert (
test_results[2].id.test_module_path
== "code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_parametrized_loop_results_temp"
)
assert test_results[2].runtime > 0
assert test_results[2].did_pass
2025-06-03 08:13:38 +00:00
out_str = """codeflash stdout: Sorting list
result: [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
"""
assert test_results[2].stdout == out_str
2024-10-10 05:10:44 +00:00
assert test_results[3].id.function_getting_tested == "sorter"
assert test_results[3].id.iteration_id == "0_0_3"
assert test_results[3].id.test_class_name is None
assert test_results[3].id.test_function_name == "test_sort_parametrized_loop"
assert (
test_results[3].id.test_module_path
== "code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_parametrized_loop_results_temp"
)
assert test_results[3].runtime > 0
assert test_results[3].did_pass
2025-06-03 08:13:38 +00:00
assert test_results[3].stdout == out_str
2024-10-10 05:10:44 +00:00
assert test_results[4].id.function_getting_tested == "sorter"
assert test_results[4].id.iteration_id == "0_0_4"
assert test_results[4].id.test_class_name is None
assert test_results[4].id.test_function_name == "test_sort_parametrized_loop"
assert (
test_results[4].id.test_module_path
== "code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_parametrized_loop_results_temp"
)
assert test_results[4].runtime > 0
assert test_results[4].did_pass
2025-06-03 08:13:38 +00:00
out_str = """codeflash stdout: Sorting list
result: [0, 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]
"""
assert test_results[4].stdout == out_str
2024-10-10 05:10:44 +00:00
assert test_results[5].id.function_getting_tested == "sorter"
assert test_results[5].id.iteration_id == "0_0_5"
assert test_results[5].id.test_class_name is None
assert test_results[5].id.test_function_name == "test_sort_parametrized_loop"
assert (
test_results[5].id.test_module_path
== "code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_parametrized_loop_results_temp"
)
assert test_results[5].runtime > 0
assert test_results[5].did_pass
2025-06-03 08:13:38 +00:00
assert test_results[5].stdout == out_str
test_results, _ = func_optimizer.run_and_parse_tests(
2024-12-30 03:11:20 +00:00
testing_type=TestingMode.PERFORMANCE,
test_env=test_env,
test_files=test_files,
optimization_iteration=0,
pytest_min_loops=1,
pytest_max_loops=1,
testing_time=0.1,
)
assert test_results[0].id.function_getting_tested == "sorter"
assert test_results[0].id.iteration_id == "0_0_0"
assert test_results[0].id.test_class_name is None
assert test_results[0].id.test_function_name == "test_sort_parametrized_loop"
assert (
test_results[0].id.test_module_path
== "code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_parametrized_loop_results_temp"
)
assert test_results[0].runtime > 0
assert test_results[0].did_pass
assert test_results[0].return_value is None
assert test_results[1].id.function_getting_tested == "sorter"
assert test_results[1].id.iteration_id == "0_0_1"
assert test_results[1].id.test_class_name is None
assert test_results[1].id.test_function_name == "test_sort_parametrized_loop"
assert (
test_results[1].id.test_module_path
== "code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_parametrized_loop_results_temp"
)
assert test_results[1].runtime > 0
assert test_results[1].did_pass
assert test_results[1].return_value is None
assert test_results[2].id.function_getting_tested == "sorter"
assert test_results[2].id.iteration_id == "0_0_2"
assert test_results[2].id.test_class_name is None
assert test_results[2].id.test_function_name == "test_sort_parametrized_loop"
assert (
test_results[2].id.test_module_path
== "code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_parametrized_loop_results_temp"
)
assert test_results[2].runtime > 0
assert test_results[2].did_pass
assert test_results[2].return_value is None
assert test_results[3].id.function_getting_tested == "sorter"
assert test_results[3].id.iteration_id == "0_0_3"
assert test_results[3].id.test_class_name is None
assert test_results[3].id.test_function_name == "test_sort_parametrized_loop"
assert (
test_results[3].id.test_module_path
== "code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_parametrized_loop_results_temp"
)
assert test_results[3].runtime > 0
assert test_results[3].did_pass
assert test_results[3].return_value is None
assert test_results[4].id.function_getting_tested == "sorter"
assert test_results[4].id.iteration_id == "0_0_4"
assert test_results[4].id.test_class_name is None
assert test_results[4].id.test_function_name == "test_sort_parametrized_loop"
assert (
test_results[4].id.test_module_path
== "code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_parametrized_loop_results_temp"
)
assert test_results[4].runtime > 0
assert test_results[4].did_pass
assert test_results[4].return_value is None
assert test_results[5].id.function_getting_tested == "sorter"
assert test_results[5].id.iteration_id == "0_0_5"
assert test_results[5].id.test_class_name is None
assert test_results[5].id.test_function_name == "test_sort_parametrized_loop"
assert (
test_results[5].id.test_module_path
== "code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_parametrized_loop_results_temp"
)
assert test_results[5].runtime > 0
assert test_results[5].did_pass
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
computed_fn_opt = True
2025-06-03 08:13:38 +00:00
line_profiler_output_file = add_decorator_imports(func_optimizer.function_to_optimize, code_context)
line_profile_results, _ = func_optimizer.run_and_parse_tests(
testing_type=TestingMode.LINE_PROFILE,
test_env=test_env,
test_files=test_files,
optimization_iteration=0,
pytest_min_loops=1,
pytest_max_loops=1,
testing_time=0.1,
2025-06-03 08:13:38 +00:00
line_profiler_output_file=line_profiler_output_file,
)
tmp_lpr = list(line_profile_results["timings"].keys())
2025-06-03 08:13:38 +00:00
assert len(tmp_lpr) == 1 and line_profile_results["timings"][tmp_lpr[0]][0][1] == 6
finally:
if computed_fn_opt:
func_optimizer.write_code_and_helpers(
2025-06-03 08:13:38 +00:00
func_optimizer.function_to_optimize_source_code,
original_helper_code,
func_optimizer.function_to_optimize.file_path,
)
2024-10-13 00:07:42 +00:00
test_path.unlink(missing_ok=True)
test_path_behavior.unlink(missing_ok=True)
test_path_perf.unlink(missing_ok=True)
2024-02-09 22:05:06 +00:00
2024-05-15 11:47:05 +00:00
def test_perfinjector_bubble_sort_loop_results() -> None:
computed_fn_opt = False
2024-02-09 22:05:06 +00:00
code = """from code_to_optimize.bubble_sort import sorter
def test_sort():
inputs = [[5, 4, 3, 2, 1, 0], [5.0, 4.0, 3.0, 2.0, 1.0, 0.0], list(reversed(range(50)))]
expected_outputs = [[0, 1, 2, 3, 4, 5], [0.0, 1.0, 2.0, 3.0, 4.0, 5.0], list(range(50))]
2024-05-15 11:47:05 +00:00
for i in range(3):
2024-02-10 00:53:05 +00:00
input = inputs[i]
expected_output = expected_outputs[i]
2024-02-09 22:05:06 +00:00
output = sorter(input)
assert output == expected_output"""
2024-10-30 03:02:39 +00:00
expected = (
"""import gc
2024-02-09 22:05:06 +00:00
import os
import sqlite3
2024-05-23 02:05:22 +00:00
import time
2024-04-18 01:57:43 +00:00
import dill as pickle
2024-05-31 22:38:34 +00:00
2024-05-23 02:05:22 +00:00
from code_to_optimize.bubble_sort import sorter
2024-02-09 22:05:06 +00:00
"""
2024-10-30 03:02:39 +00:00
+ codeflash_wrap_string
+ """
def test_sort():
2024-10-03 19:06:48 +00:00
codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
codeflash_iteration = os.environ['CODEFLASH_TEST_ITERATION']
2024-02-09 22:05:06 +00:00
codeflash_con = sqlite3.connect(f'{tmp_dir_path}_{{codeflash_iteration}}.sqlite')
codeflash_cur = codeflash_con.cursor()
codeflash_cur.execute('CREATE TABLE IF NOT EXISTS test_results (test_module_path TEXT, test_class_name TEXT, test_function_name TEXT, function_getting_tested TEXT, loop_index INTEGER, iteration_id TEXT, runtime INTEGER, return_value BLOB, verification_type TEXT)')
2024-02-09 22:05:06 +00:00
inputs = [[5, 4, 3, 2, 1, 0], [5.0, 4.0, 3.0, 2.0, 1.0, 0.0], list(reversed(range(50)))]
expected_outputs = [[0, 1, 2, 3, 4, 5], [0.0, 1.0, 2.0, 3.0, 4.0, 5.0], list(range(50))]
2024-02-10 00:53:05 +00:00
for i in range(3):
input = inputs[i]
expected_output = expected_outputs[i]
output = codeflash_wrap(sorter, '{module_path}', None, 'test_sort', 'sorter', '2_2', codeflash_loop_index, codeflash_cur, codeflash_con, input)
2024-02-09 22:05:06 +00:00
assert output == expected_output
2024-05-23 02:05:22 +00:00
codeflash_con.close()
"""
2024-10-30 03:02:39 +00:00
)
2024-02-09 22:05:06 +00:00
expected_perf = (
"""import gc
import os
import time
from code_to_optimize.bubble_sort import sorter
"""
+ codeflash_wrap_perfonly_string
+ """
def test_sort():
codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
inputs = [[5, 4, 3, 2, 1, 0], [5.0, 4.0, 3.0, 2.0, 1.0, 0.0], list(reversed(range(50)))]
expected_outputs = [[0, 1, 2, 3, 4, 5], [0.0, 1.0, 2.0, 3.0, 4.0, 5.0], list(range(50))]
for i in range(3):
input = inputs[i]
expected_output = expected_outputs[i]
output = codeflash_wrap(sorter, '{module_path}', None, 'test_sort', 'sorter', '2_2', codeflash_loop_index, input)
assert output == expected_output
"""
)
code_path = (Path(__file__).parent.resolve() / "../code_to_optimize/bubble_sort.py").resolve()
2024-02-09 22:05:06 +00:00
test_path = (
2024-10-13 00:07:42 +00:00
Path(__file__).parent.resolve()
/ "../code_to_optimize/tests/pytest/test_perfinjector_bubble_sort_loop_results_temp.py"
2024-10-10 05:10:44 +00:00
).resolve()
test_path_behavior = (
Path(__file__).parent.resolve()
/ "../code_to_optimize/tests/pytest/test_perfinjector_bubble_sort_loop_results_temp_behavior.py"
).resolve()
test_path_perf = (
Path(__file__).parent.resolve()
/ "../code_to_optimize/tests/pytest/test_perfinjector_bubble_sort_loop_results_temp_perf.py"
).resolve()
try:
2024-10-13 00:07:42 +00:00
with test_path.open("w") as f:
f.write(code)
2024-02-09 22:05:06 +00:00
2024-10-13 00:07:42 +00:00
tests_root = (Path(__file__).parent.resolve() / "../code_to_optimize/tests/pytest/").resolve()
project_root_path = (Path(__file__).parent.resolve() / "../").resolve()
run_cwd = Path(__file__).parent.parent.resolve()
original_cwd = Path.cwd()
2024-02-10 00:46:38 +00:00
func = FunctionToOptimize(function_name="sorter", parents=[], file_path=code_path)
os.chdir(str(run_cwd))
success, new_test_behavior = inject_profiling_into_existing_test(
2024-12-30 03:11:20 +00:00
test_path, [CodePosition(11, 17)], func, project_root_path, "pytest", mode=TestingMode.BEHAVIOR
)
assert success
success, new_test_perf = inject_profiling_into_existing_test(
2024-12-30 03:11:20 +00:00
test_path, [CodePosition(11, 17)], func, project_root_path, "pytest", mode=TestingMode.PERFORMANCE
)
os.chdir(original_cwd)
assert success
assert new_test_behavior is not None
assert new_test_behavior.replace('"', "'") == expected.format(
module_path="code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_loop_results_temp",
tmp_dir_path=get_run_tmp_file(Path("test_return_values")),
).replace('"', "'")
assert new_test_perf.replace('"', "'") == expected_perf.format(
2024-10-10 05:10:44 +00:00
module_path="code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_loop_results_temp",
2024-10-13 00:40:07 +00:00
tmp_dir_path=get_run_tmp_file(Path("test_return_values")),
2024-05-31 23:36:43 +00:00
).replace('"', "'")
2024-10-10 05:10:44 +00:00
# Overwrite old test with new instrumented test
with test_path_behavior.open("w") as f:
f.write(new_test_behavior)
with test_path_perf.open("w") as f:
f.write(new_test_perf)
2024-10-10 05:10:44 +00:00
test_env = os.environ.copy()
test_env["CODEFLASH_TEST_ITERATION"] = "0"
test_type = TestType.EXISTING_UNIT_TEST
test_files = TestFiles(
test_files=[
TestFile(
instrumented_behavior_file_path=test_path_behavior,
test_type=test_type,
original_file_path=test_path,
benchmarking_file_path=test_path_perf,
tests_in_file=[
TestsInFile(
test_file=test_path,
test_class=None,
test_function="test_sort",
test_type=TestType.EXISTING_UNIT_TEST,
)
],
)
]
2024-10-10 05:10:44 +00:00
)
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",
2024-10-10 05:10:44 +00:00
)
func_optimizer = FunctionOptimizer(function_to_optimize=func, test_cfg=test_config)
test_results, coverage_data = func_optimizer.run_and_parse_tests(
2024-12-30 03:11:20 +00:00
testing_type=TestingMode.BEHAVIOR,
2024-10-10 05:10:44 +00:00
test_env=test_env,
test_files=test_files,
optimization_iteration=0,
pytest_min_loops=1,
pytest_max_loops=1,
testing_time=0.1,
)
assert test_results[0].id.function_getting_tested == "sorter"
assert test_results[0].id.iteration_id == "2_2_0"
assert test_results[0].id.test_class_name is None
assert test_results[0].id.test_function_name == "test_sort"
assert (
test_results[0].id.test_module_path
== "code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_loop_results_temp"
)
assert test_results[0].runtime > 0
assert test_results[0].did_pass
assert test_results[0].return_value == ([0, 1, 2, 3, 4, 5],)
assert test_results[1].id.function_getting_tested == "sorter"
assert test_results[1].id.iteration_id == "2_2_1"
assert test_results[1].id.test_class_name is None
assert test_results[1].id.test_function_name == "test_sort"
assert (
test_results[1].id.test_module_path
== "code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_loop_results_temp"
)
assert test_results[1].runtime > 0
assert test_results[1].did_pass
assert test_results[2].id.function_getting_tested == "sorter"
assert test_results[2].id.iteration_id == "2_2_2"
assert test_results[2].id.test_class_name is None
assert test_results[2].id.test_function_name == "test_sort"
assert (
test_results[2].id.test_module_path
== "code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_loop_results_temp"
)
assert test_results[2].runtime > 0
assert test_results[2].did_pass
test_results, coverage_data = func_optimizer.run_and_parse_tests(
2024-12-30 03:11:20 +00:00
testing_type=TestingMode.PERFORMANCE,
test_env=test_env,
test_files=test_files,
optimization_iteration=0,
pytest_min_loops=1,
pytest_max_loops=1,
testing_time=0.1,
)
assert test_results[0].id.function_getting_tested == "sorter"
assert test_results[0].id.iteration_id == "2_2_0"
assert test_results[0].id.test_class_name is None
assert test_results[0].id.test_function_name == "test_sort"
assert (
test_results[0].id.test_module_path
== "code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_loop_results_temp"
)
assert test_results[0].runtime > 0
assert test_results[0].did_pass
assert test_results[0].return_value is None
out_str = """codeflash stdout: Sorting list
result: [0, 1, 2, 3, 4, 5]
2025-06-03 08:13:38 +00:00
"""
2025-06-03 08:13:38 +00:00
assert test_results[0].stdout == out_str
2024-10-10 05:10:44 +00:00
assert test_results[1].id.function_getting_tested == "sorter"
assert test_results[1].id.iteration_id == "2_2_1"
assert test_results[1].id.test_class_name is None
assert test_results[1].id.test_function_name == "test_sort"
assert (
test_results[1].id.test_module_path
== "code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_loop_results_temp"
)
assert test_results[1].runtime > 0
assert test_results[1].did_pass
2025-06-03 08:13:38 +00:00
out_str2 = """codeflash stdout: Sorting list
result: [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
"""
assert test_results[1].stdout == out_str2
2024-10-10 05:10:44 +00:00
assert test_results[2].id.function_getting_tested == "sorter"
assert test_results[2].id.iteration_id == "2_2_2"
assert test_results[2].id.test_class_name is None
assert test_results[2].id.test_function_name == "test_sort"
assert (
test_results[2].id.test_module_path
== "code_to_optimize.tests.pytest.test_perfinjector_bubble_sort_loop_results_temp"
)
assert test_results[2].runtime > 0
assert test_results[2].did_pass
2025-06-03 08:13:38 +00:00
out_str3 = """codeflash stdout: Sorting list
result: [0, 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]
"""
assert test_results[2].stdout == out_str3
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
computed_fn_opt = True
2025-06-03 08:13:38 +00:00
line_profiler_output_file = add_decorator_imports(func_optimizer.function_to_optimize, code_context)
line_profile_results, _ = func_optimizer.run_and_parse_tests(
testing_type=TestingMode.LINE_PROFILE,
test_env=test_env,
test_files=test_files,
optimization_iteration=0,
pytest_min_loops=1,
pytest_max_loops=1,
testing_time=0.1,
2025-06-03 08:13:38 +00:00
line_profiler_output_file=line_profiler_output_file,
)
tmp_lpr = list(line_profile_results["timings"].keys())
2025-06-03 08:13:38 +00:00
assert len(tmp_lpr) == 1 and line_profile_results["timings"][tmp_lpr[0]][0][1] == 3
finally:
if computed_fn_opt is True:
func_optimizer.write_code_and_helpers(
2025-06-03 08:13:38 +00:00
func_optimizer.function_to_optimize_source_code,
original_helper_code,
func_optimizer.function_to_optimize.file_path,
)
2024-10-13 00:07:42 +00:00
test_path.unlink(missing_ok=True)
test_path_perf.unlink(missing_ok=True)
test_path_behavior.unlink(missing_ok=True)
2024-05-15 11:47:05 +00:00
def test_perfinjector_bubble_sort_unittest_results() -> None:
code = """import unittest
from code_to_optimize.bubble_sort import sorter
class TestPigLatin(unittest.TestCase):
def test_sort(self):
input = [5, 4, 3, 2, 1, 0]
output = sorter(input)
self.assertEqual(output, [0, 1, 2, 3, 4, 5])
input = [5.0, 4.0, 3.0, 2.0, 1.0, 0.0]
output = sorter(input)
self.assertEqual(output, [0.0, 1.0, 2.0, 3.0, 4.0, 5.0])
input = list(reversed(range(50)))
output = sorter(input)
self.assertEqual(output, list(range(50)))
"""
2024-10-30 03:02:39 +00:00
expected = (
"""import gc
import os
import sqlite3
2024-05-23 02:05:22 +00:00
import time
import unittest
2024-04-18 01:57:43 +00:00
import dill as pickle
2024-06-05 20:58:51 +00:00
import timeout_decorator
2024-06-05 21:04:10 +00:00
2024-05-23 02:05:22 +00:00
from code_to_optimize.bubble_sort import sorter
"""
2024-10-30 03:02:39 +00:00
+ codeflash_wrap_string
+ """
class TestPigLatin(unittest.TestCase):
2024-06-05 20:58:51 +00:00
@timeout_decorator.timeout(15)
def test_sort(self):
2024-10-03 19:06:48 +00:00
codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
codeflash_iteration = os.environ['CODEFLASH_TEST_ITERATION']
codeflash_con = sqlite3.connect(f'{tmp_dir_path}_{{codeflash_iteration}}.sqlite')
codeflash_cur = codeflash_con.cursor()
codeflash_cur.execute('CREATE TABLE IF NOT EXISTS test_results (test_module_path TEXT, test_class_name TEXT, test_function_name TEXT, function_getting_tested TEXT, loop_index INTEGER, iteration_id TEXT, runtime INTEGER, return_value BLOB, verification_type TEXT)')
input = [5, 4, 3, 2, 1, 0]
output = codeflash_wrap(sorter, '{module_path}', 'TestPigLatin', 'test_sort', 'sorter', '1', codeflash_loop_index, codeflash_cur, codeflash_con, input)
self.assertEqual(output, [0, 1, 2, 3, 4, 5])
input = [5.0, 4.0, 3.0, 2.0, 1.0, 0.0]
output = codeflash_wrap(sorter, '{module_path}', 'TestPigLatin', 'test_sort', 'sorter', '4', codeflash_loop_index, codeflash_cur, codeflash_con, input)
self.assertEqual(output, [0.0, 1.0, 2.0, 3.0, 4.0, 5.0])
input = list(reversed(range(50)))
output = codeflash_wrap(sorter, '{module_path}', 'TestPigLatin', 'test_sort', 'sorter', '7', codeflash_loop_index, codeflash_cur, codeflash_con, input)
self.assertEqual(output, list(range(50)))
2024-05-23 02:05:22 +00:00
codeflash_con.close()
"""
2024-10-30 03:02:39 +00:00
)
expected_perf = (
"""import gc
import os
import time
import unittest
import timeout_decorator
from code_to_optimize.bubble_sort import sorter
"""
+ codeflash_wrap_perfonly_string
+ """
class TestPigLatin(unittest.TestCase):
@timeout_decorator.timeout(15)
def test_sort(self):
codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
input = [5, 4, 3, 2, 1, 0]
output = codeflash_wrap(sorter, '{module_path}', 'TestPigLatin', 'test_sort', 'sorter', '1', codeflash_loop_index, input)
self.assertEqual(output, [0, 1, 2, 3, 4, 5])
input = [5.0, 4.0, 3.0, 2.0, 1.0, 0.0]
output = codeflash_wrap(sorter, '{module_path}', 'TestPigLatin', 'test_sort', 'sorter', '4', codeflash_loop_index, input)
self.assertEqual(output, [0.0, 1.0, 2.0, 3.0, 4.0, 5.0])
input = list(reversed(range(50)))
output = codeflash_wrap(sorter, '{module_path}', 'TestPigLatin', 'test_sort', 'sorter', '7', codeflash_loop_index, input)
self.assertEqual(output, list(range(50)))
"""
)
code_path = (Path(__file__).parent.resolve() / "../code_to_optimize/bubble_sort.py").resolve()
test_path = (
2024-10-13 00:07:42 +00:00
Path(__file__).parent.resolve()
/ "../code_to_optimize/tests/unittest/test_perfinjector_bubble_sort_unittest_results_temp.py"
2024-10-10 05:10:44 +00:00
).resolve()
test_path_behavior = (
Path(__file__).parent.resolve()
/ "../code_to_optimize/tests/unittest/test_perfinjector_bubble_sort_unittest_results_temp_behavior.py"
).resolve()
test_path_perf = (
Path(__file__).parent.resolve()
/ "../code_to_optimize/tests/unittest/test_perfinjector_bubble_sort_unittest_results_temp_perf.py"
).resolve()
try:
2024-10-13 00:07:42 +00:00
with test_path.open("w") as f:
f.write(code)
2024-10-13 00:07:42 +00:00
tests_root = (Path(__file__).parent.resolve() / "../code_to_optimize/tests/unittest/").resolve()
project_root_path = (Path(__file__).parent.resolve() / "../").resolve()
run_cwd = Path(__file__).parent.parent.resolve()
original_cwd = Path.cwd()
func = FunctionToOptimize(function_name="sorter", parents=[], file_path=code_path)
2024-10-13 00:07:42 +00:00
os.chdir(run_cwd)
success, new_test_behavior = inject_profiling_into_existing_test(
test_path,
[CodePosition(9, 17), CodePosition(13, 17), CodePosition(17, 17)],
func,
project_root_path,
"unittest",
2024-12-30 03:11:20 +00:00
mode=TestingMode.BEHAVIOR,
)
assert success
success, new_test_perf = inject_profiling_into_existing_test(
test_path,
[CodePosition(9, 17), CodePosition(13, 17), CodePosition(17, 17)],
func,
project_root_path,
"unittest",
2024-12-30 03:11:20 +00:00
mode=TestingMode.PERFORMANCE,
)
os.chdir(original_cwd)
assert success
assert new_test_behavior is not None
assert new_test_behavior.replace('"', "'") == expected.format(
module_path="code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_results_temp",
tmp_dir_path=get_run_tmp_file(Path("test_return_values")),
).replace('"', "'")
assert new_test_perf.replace('"', "'") == expected_perf.format(
2024-10-10 05:10:44 +00:00
module_path="code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_results_temp",
2024-10-13 00:40:07 +00:00
tmp_dir_path=get_run_tmp_file(Path("test_return_values")),
2024-05-31 23:36:43 +00:00
).replace('"', "'")
#
2024-10-10 05:10:44 +00:00
# Overwrite old test with new instrumented test
with test_path_behavior.open("w") as f:
f.write(new_test_behavior)
with test_path_perf.open("w") as f:
f.write(new_test_perf)
2024-10-10 05:10:44 +00:00
test_env = os.environ.copy()
test_env["CODEFLASH_TEST_ITERATION"] = "0"
test_env["CODEFLASH_LOOP_INDEX"] = "1"
test_type = TestType.EXISTING_UNIT_TEST
test_files = TestFiles(
test_files=[
TestFile(
instrumented_behavior_file_path=test_path_behavior,
test_type=test_type,
original_file_path=test_path,
benchmarking_file_path=test_path_perf,
tests_in_file=[
TestsInFile(
test_file=test_path,
test_class="TestPigLatin",
test_function="test_sort",
test_type=TestType.EXISTING_UNIT_TEST,
)
],
)
]
2024-10-10 05:10:44 +00:00
)
test_config = TestConfig(
tests_root=tests_root,
tests_project_rootdir=project_root_path,
project_root_path=project_root_path,
test_framework="unittest",
pytest_cmd="pytest",
)
func_optimizer = FunctionOptimizer(function_to_optimize=func, test_cfg=test_config)
test_results, coverage_data = func_optimizer.run_and_parse_tests(
2024-12-30 03:11:20 +00:00
testing_type=TestingMode.BEHAVIOR,
2024-10-10 05:10:44 +00:00
test_env=test_env,
test_files=test_files,
optimization_iteration=0,
pytest_min_loops=1,
pytest_max_loops=1,
testing_time=0.1,
)
assert test_results[0].id.function_getting_tested == "sorter"
assert test_results[0].id.iteration_id == "1_0"
assert test_results[0].id.test_class_name == "TestPigLatin"
assert test_results[0].id.test_function_name == "test_sort"
assert (
test_results[0].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_results_temp"
)
assert test_results[0].runtime > 0
assert test_results[0].did_pass
assert test_results[0].return_value == ([0, 1, 2, 3, 4, 5],)
2025-06-03 08:13:38 +00:00
out_str = """codeflash stdout: Sorting list
result: [0, 1, 2, 3, 4, 5]
"""
assert test_results[0].stdout == out_str
2024-10-10 05:10:44 +00:00
assert test_results[1].id.function_getting_tested == "sorter"
assert test_results[1].id.iteration_id == "4_0"
assert test_results[1].id.test_class_name == "TestPigLatin"
assert test_results[1].id.test_function_name == "test_sort"
assert (
test_results[1].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_results_temp"
)
assert test_results[1].runtime > 0
assert test_results[1].did_pass
2025-06-03 08:13:38 +00:00
out_str = """codeflash stdout: Sorting list
result: [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
"""
assert test_results[1].stdout == out_str
2024-10-10 05:10:44 +00:00
assert test_results[2].id.function_getting_tested == "sorter"
assert test_results[2].id.iteration_id == "7_0"
assert test_results[2].id.test_class_name == "TestPigLatin"
assert test_results[2].id.test_function_name == "test_sort"
assert (
test_results[2].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_results_temp"
)
assert test_results[2].runtime > 0
assert test_results[2].did_pass
test_results, coverage_data = func_optimizer.run_and_parse_tests(
2024-12-30 03:11:20 +00:00
testing_type=TestingMode.PERFORMANCE,
test_env=test_env,
test_files=test_files,
optimization_iteration=0,
pytest_min_loops=1,
pytest_max_loops=1,
testing_time=0.1,
)
assert test_results[0].id.function_getting_tested == "sorter"
assert test_results[0].id.iteration_id == "1_0"
assert test_results[0].id.test_class_name == "TestPigLatin"
assert test_results[0].id.test_function_name == "test_sort"
assert (
test_results[0].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_results_temp"
)
assert test_results[0].runtime > 0
assert test_results[0].did_pass
assert test_results[0].return_value is None
assert test_results[1].id.function_getting_tested == "sorter"
assert test_results[1].id.iteration_id == "4_0"
assert test_results[1].id.test_class_name == "TestPigLatin"
assert test_results[1].id.test_function_name == "test_sort"
assert (
test_results[1].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_results_temp"
)
assert test_results[1].runtime > 0
assert test_results[1].did_pass
2024-10-10 05:10:44 +00:00
assert test_results[2].id.function_getting_tested == "sorter"
assert test_results[2].id.iteration_id == "7_0"
assert test_results[2].id.test_class_name == "TestPigLatin"
assert test_results[2].id.test_function_name == "test_sort"
assert (
test_results[2].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_results_temp"
)
assert test_results[2].runtime > 0
assert test_results[2].did_pass
2025-06-03 08:13:38 +00:00
out_str = """codeflash stdout: Sorting list
result: [0, 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]
"""
assert test_results[2].stdout == out_str
finally:
2024-10-13 00:07:42 +00:00
test_path.unlink(missing_ok=True)
test_path_behavior.unlink(missing_ok=True)
test_path_perf.unlink(missing_ok=True)
2024-05-15 11:47:05 +00:00
def test_perfinjector_bubble_sort_unittest_parametrized_results() -> None:
code = """import unittest
from parameterized import parameterized
from code_to_optimize.bubble_sort import sorter
class TestPigLatin(unittest.TestCase):
@parameterized.expand(
[
([5, 4, 3, 2, 1, 0], [0, 1, 2, 3, 4, 5]),
([5.0, 4.0, 3.0, 2.0, 1.0, 0.0], [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]),
(list(reversed(range(50))), list(range(50))),
]
)
def test_sort(self, input, expected_output):
output = sorter(input)
self.assertEqual(output, expected_output)
"""
expected_behavior = (
2024-10-30 03:02:39 +00:00
"""import gc
import os
import sqlite3
2024-05-23 02:39:58 +00:00
import time
import unittest
2024-04-18 01:57:43 +00:00
import dill as pickle
2024-06-05 20:58:51 +00:00
import timeout_decorator
2024-05-23 02:39:58 +00:00
from parameterized import parameterized
2024-05-23 03:17:49 +00:00
from code_to_optimize.bubble_sort import sorter
"""
2024-10-30 03:02:39 +00:00
+ codeflash_wrap_string
+ """
class TestPigLatin(unittest.TestCase):
@parameterized.expand([([5, 4, 3, 2, 1, 0], [0, 1, 2, 3, 4, 5]), ([5.0, 4.0, 3.0, 2.0, 1.0, 0.0], [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]), (list(reversed(range(50))), list(range(50)))])
2024-06-05 20:58:51 +00:00
@timeout_decorator.timeout(15)
def test_sort(self, input, expected_output):
2024-10-03 19:06:48 +00:00
codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
codeflash_iteration = os.environ['CODEFLASH_TEST_ITERATION']
codeflash_con = sqlite3.connect(f'{tmp_dir_path}_{{codeflash_iteration}}.sqlite')
codeflash_cur = codeflash_con.cursor()
codeflash_cur.execute('CREATE TABLE IF NOT EXISTS test_results (test_module_path TEXT, test_class_name TEXT, test_function_name TEXT, function_getting_tested TEXT, loop_index INTEGER, iteration_id TEXT, runtime INTEGER, return_value BLOB, verification_type TEXT)')
output = codeflash_wrap(sorter, '{module_path}', 'TestPigLatin', 'test_sort', 'sorter', '0', codeflash_loop_index, codeflash_cur, codeflash_con, input)
self.assertEqual(output, expected_output)
2024-05-23 02:39:58 +00:00
codeflash_con.close()
"""
2024-10-30 03:02:39 +00:00
)
expected_perf = (
"""import gc
import os
import time
import unittest
import timeout_decorator
from parameterized import parameterized
from code_to_optimize.bubble_sort import sorter
"""
+ codeflash_wrap_perfonly_string
+ """
class TestPigLatin(unittest.TestCase):
@parameterized.expand([([5, 4, 3, 2, 1, 0], [0, 1, 2, 3, 4, 5]), ([5.0, 4.0, 3.0, 2.0, 1.0, 0.0], [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]), (list(reversed(range(50))), list(range(50)))])
@timeout_decorator.timeout(15)
def test_sort(self, input, expected_output):
codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
output = codeflash_wrap(sorter, '{module_path}', 'TestPigLatin', 'test_sort', 'sorter', '0', codeflash_loop_index, input)
self.assertEqual(output, expected_output)
"""
)
code_path = (Path(__file__).parent.resolve() / "../code_to_optimize/bubble_sort.py").resolve()
test_path = (
2024-10-13 00:07:42 +00:00
Path(__file__).parent.resolve()
/ "../code_to_optimize/tests/unittest/test_perfinjector_bubble_sort_unittest_parametrized_results_temp.py"
2024-10-10 05:10:44 +00:00
).resolve()
test_path_behavior = (
Path(__file__).parent.resolve()
/ "../code_to_optimize/tests/unittest/test_perfinjector_bubble_sort_unittest_parametrized_results_temp_behavior.py"
).resolve()
test_path_perf = (
Path(__file__).parent.resolve()
/ "../code_to_optimize/tests/unittest/test_perfinjector_bubble_sort_unittest_parametrized_results_temp_perf.py"
).resolve()
try:
2024-10-13 00:07:42 +00:00
with test_path.open("w") as f:
f.write(code)
2024-10-13 00:07:42 +00:00
tests_root = (Path(__file__).parent.resolve() / "../code_to_optimize/tests/unittest/").resolve()
project_root_path = (Path(__file__).parent.resolve() / "../").resolve()
run_cwd = Path(__file__).parent.parent.resolve()
original_cwd = Path.cwd()
func = FunctionToOptimize(function_name="sorter", parents=[], file_path=code_path)
2024-10-13 00:07:42 +00:00
os.chdir(run_cwd)
success, new_test_behavior = inject_profiling_into_existing_test(
2024-12-30 03:11:20 +00:00
test_path, [CodePosition(16, 17)], func, project_root_path, "unittest", mode=TestingMode.BEHAVIOR
)
assert success
success, new_test_perf = inject_profiling_into_existing_test(
2024-12-30 03:11:20 +00:00
test_path, [CodePosition(16, 17)], func, project_root_path, "unittest", mode=TestingMode.PERFORMANCE
)
os.chdir(original_cwd)
assert success
assert new_test_behavior is not None
assert new_test_behavior.replace('"', "'") == expected_behavior.format(
2024-10-10 05:10:44 +00:00
module_path="code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_parametrized_results_temp",
2024-10-13 00:40:07 +00:00
tmp_dir_path=get_run_tmp_file(Path("test_return_values")),
2024-05-31 23:36:43 +00:00
).replace('"', "'")
assert new_test_perf is not None
assert new_test_perf.replace('"', "'") == expected_perf.format(
module_path="code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_parametrized_results_temp",
tmp_dir_path=get_run_tmp_file(Path("test_return_values")),
).replace('"', "'")
#
# Overwrite old test with new instrumented test
with test_path_behavior.open("w") as f:
f.write(new_test_behavior)
with test_path_perf.open("w") as f:
f.write(new_test_perf)
2024-10-10 05:10:44 +00:00
test_env = os.environ.copy()
test_env["CODEFLASH_TEST_ITERATION"] = "0"
test_env["CODEFLASH_LOOP_INDEX"] = "1"
test_type = TestType.EXISTING_UNIT_TEST
test_files = TestFiles(
test_files=[
TestFile(
instrumented_behavior_file_path=test_path_behavior,
test_type=test_type,
original_file_path=test_path,
benchmarking_file_path=test_path_perf,
tests_in_file=[
TestsInFile(
test_file=test_path,
test_class="TestPigLatin",
test_function="test_sort",
test_type=TestType.EXISTING_UNIT_TEST,
)
],
)
]
2024-10-10 05:10:44 +00:00
)
test_config = TestConfig(
tests_root=tests_root,
tests_project_rootdir=project_root_path,
project_root_path=project_root_path,
test_framework="unittest",
pytest_cmd="pytest",
)
func_optimizer = FunctionOptimizer(function_to_optimize=func, test_cfg=test_config)
test_results, coverage_data = func_optimizer.run_and_parse_tests(
2024-12-30 03:11:20 +00:00
testing_type=TestingMode.BEHAVIOR,
test_env=test_env,
test_files=test_files,
optimization_iteration=0,
pytest_min_loops=1,
pytest_max_loops=1,
testing_time=0.1,
)
assert test_results[0].id.function_getting_tested == "sorter"
assert test_results[0].id.iteration_id == "0_0"
assert test_results[0].id.test_class_name == "TestPigLatin"
assert test_results[0].id.test_function_name == "test_sort"
assert (
test_results[0].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_parametrized_results_temp"
)
assert test_results[0].runtime > 0
assert test_results[0].did_pass
assert test_results[0].return_value == ([0, 1, 2, 3, 4, 5],)
2025-06-03 08:13:38 +00:00
out_str = """codeflash stdout: Sorting list
result: [0, 1, 2, 3, 4, 5]
"""
assert test_results[0].stdout == out_str
assert test_results[1].id.function_getting_tested == "sorter"
assert test_results[1].id.iteration_id == "0_1"
assert test_results[1].id.test_class_name == "TestPigLatin"
assert test_results[1].id.test_function_name == "test_sort"
assert (
test_results[1].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_parametrized_results_temp"
)
assert test_results[1].runtime > 0
assert test_results[1].did_pass
2025-06-03 08:13:38 +00:00
out_str = """codeflash stdout: Sorting list
result: [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
"""
assert test_results[1].stdout == out_str
assert test_results[2].id.function_getting_tested == "sorter"
assert test_results[2].id.iteration_id == "0_2"
assert test_results[2].id.test_class_name == "TestPigLatin"
assert test_results[2].id.test_function_name == "test_sort"
assert (
test_results[2].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_parametrized_results_temp"
)
assert test_results[2].runtime > 0
assert test_results[2].did_pass
2025-06-03 08:13:38 +00:00
out_str = """codeflash stdout: Sorting list
result: [0, 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]
"""
assert test_results[2].stdout == out_str
test_results, coverage_data = func_optimizer.run_and_parse_tests(
2024-12-30 03:11:20 +00:00
testing_type=TestingMode.PERFORMANCE,
2024-10-10 05:10:44 +00:00
test_env=test_env,
test_files=test_files,
optimization_iteration=0,
pytest_min_loops=1,
pytest_max_loops=1,
testing_time=0.1,
)
assert test_results[0].id.function_getting_tested == "sorter"
assert test_results[0].id.iteration_id == "0_0"
assert test_results[0].id.test_class_name == "TestPigLatin"
assert test_results[0].id.test_function_name == "test_sort"
assert (
test_results[0].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_parametrized_results_temp"
)
assert test_results[0].runtime > 0
assert test_results[0].did_pass
assert test_results[0].return_value is None
2024-10-10 05:10:44 +00:00
assert test_results[1].id.function_getting_tested == "sorter"
assert test_results[1].id.iteration_id == "0_1"
assert test_results[1].id.test_class_name == "TestPigLatin"
assert test_results[1].id.test_function_name == "test_sort"
assert (
test_results[1].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_parametrized_results_temp"
)
assert test_results[1].runtime > 0
assert test_results[1].did_pass
assert test_results[2].id.function_getting_tested == "sorter"
assert test_results[2].id.iteration_id == "0_2"
assert test_results[2].id.test_class_name == "TestPigLatin"
assert test_results[2].id.test_function_name == "test_sort"
assert (
test_results[2].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_parametrized_results_temp"
)
assert test_results[2].runtime > 0
assert test_results[2].did_pass
finally:
2024-10-13 00:07:42 +00:00
test_path.unlink(missing_ok=True)
test_path_perf.unlink(missing_ok=True)
test_path_behavior.unlink(missing_ok=True)
2024-05-15 11:47:05 +00:00
def test_perfinjector_bubble_sort_unittest_loop_results() -> None:
code = """import unittest
from code_to_optimize.bubble_sort import sorter
class TestPigLatin(unittest.TestCase):
def test_sort(self):
inputs = [[5, 4, 3, 2, 1, 0], [5.0, 4.0, 3.0, 2.0, 1.0, 0.0], list(reversed(range(50)))]
expected_outputs = [[0, 1, 2, 3, 4, 5], [0.0, 1.0, 2.0, 3.0, 4.0, 5.0], list(range(50))]
2024-05-15 11:47:05 +00:00
for i in range(3):
input = inputs[i]
expected_output = expected_outputs[i]
output = sorter(input)
self.assertEqual(output, expected_output)"""
expected_behavior = (
2024-10-30 03:02:39 +00:00
"""import gc
import os
import sqlite3
2024-05-23 02:39:58 +00:00
import time
import unittest
2024-04-18 01:57:43 +00:00
import dill as pickle
2024-06-05 20:58:51 +00:00
import timeout_decorator
2024-05-23 02:39:58 +00:00
from code_to_optimize.bubble_sort import sorter
"""
2024-10-30 03:02:39 +00:00
+ codeflash_wrap_string
+ """
class TestPigLatin(unittest.TestCase):
2024-06-05 20:58:51 +00:00
@timeout_decorator.timeout(15)
def test_sort(self):
2024-10-03 19:06:48 +00:00
codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
codeflash_iteration = os.environ['CODEFLASH_TEST_ITERATION']
codeflash_con = sqlite3.connect(f'{tmp_dir_path}_{{codeflash_iteration}}.sqlite')
codeflash_cur = codeflash_con.cursor()
codeflash_cur.execute('CREATE TABLE IF NOT EXISTS test_results (test_module_path TEXT, test_class_name TEXT, test_function_name TEXT, function_getting_tested TEXT, loop_index INTEGER, iteration_id TEXT, runtime INTEGER, return_value BLOB, verification_type TEXT)')
inputs = [[5, 4, 3, 2, 1, 0], [5.0, 4.0, 3.0, 2.0, 1.0, 0.0], list(reversed(range(50)))]
expected_outputs = [[0, 1, 2, 3, 4, 5], [0.0, 1.0, 2.0, 3.0, 4.0, 5.0], list(range(50))]
for i in range(3):
input = inputs[i]
expected_output = expected_outputs[i]
output = codeflash_wrap(sorter, '{module_path}', 'TestPigLatin', 'test_sort', 'sorter', '2_2', codeflash_loop_index, codeflash_cur, codeflash_con, input)
self.assertEqual(output, expected_output)
2024-05-23 02:39:58 +00:00
codeflash_con.close()
"""
2024-10-30 03:02:39 +00:00
)
expected_perf = (
"""import gc
import os
import time
import unittest
import timeout_decorator
from code_to_optimize.bubble_sort import sorter
"""
+ codeflash_wrap_perfonly_string
+ """
class TestPigLatin(unittest.TestCase):
@timeout_decorator.timeout(15)
def test_sort(self):
codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
inputs = [[5, 4, 3, 2, 1, 0], [5.0, 4.0, 3.0, 2.0, 1.0, 0.0], list(reversed(range(50)))]
expected_outputs = [[0, 1, 2, 3, 4, 5], [0.0, 1.0, 2.0, 3.0, 4.0, 5.0], list(range(50))]
for i in range(3):
input = inputs[i]
expected_output = expected_outputs[i]
output = codeflash_wrap(sorter, '{module_path}', 'TestPigLatin', 'test_sort', 'sorter', '2_2', codeflash_loop_index, input)
self.assertEqual(output, expected_output)
"""
)
code_path = (Path(__file__).parent.resolve() / "../code_to_optimize/bubble_sort.py").resolve()
test_path = (
2024-10-13 00:07:42 +00:00
Path(__file__).parent.resolve()
/ "../code_to_optimize/tests/unittest/test_perfinjector_bubble_sort_unittest_loop_results_temp.py"
2024-10-10 05:10:44 +00:00
).resolve()
test_path_behavior = (
Path(__file__).parent.resolve()
/ "../code_to_optimize/tests/unittest/test_perfinjector_bubble_sort_unittest_loop_results_temp_behavior.py"
).resolve()
test_path_perf = (
Path(__file__).parent.resolve()
/ "../code_to_optimize/tests/unittest/test_perfinjector_bubble_sort_unittest_loop_results_temp_perf.py"
).resolve()
try:
2024-10-13 00:07:42 +00:00
with test_path.open("w") as f:
f.write(code)
2024-10-13 00:07:42 +00:00
tests_root = (Path(__file__).parent.resolve() / "../code_to_optimize/tests/unittest/").resolve()
project_root_path = (Path(__file__).parent.resolve() / "../").resolve()
run_cwd = Path(__file__).parent.parent.resolve()
original_cwd = Path.cwd()
func = FunctionToOptimize(function_name="sorter", parents=[], file_path=code_path)
2024-10-13 00:07:42 +00:00
os.chdir(run_cwd)
success, new_test_behavior = inject_profiling_into_existing_test(
2024-12-30 03:11:20 +00:00
test_path, [CodePosition(14, 21)], func, project_root_path, "unittest", mode=TestingMode.BEHAVIOR
)
assert success
success, new_test_perf = inject_profiling_into_existing_test(
2024-12-30 03:11:20 +00:00
test_path, [CodePosition(14, 21)], func, project_root_path, "unittest", mode=TestingMode.PERFORMANCE
)
os.chdir(original_cwd)
assert success
assert new_test_behavior is not None
assert new_test_behavior.replace('"', "'") == expected_behavior.format(
module_path="code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_loop_results_temp",
tmp_dir_path=get_run_tmp_file(Path("test_return_values")),
).replace('"', "'")
assert new_test_perf.replace('"', "'") == expected_perf.format(
2024-10-10 05:10:44 +00:00
module_path="code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_loop_results_temp",
2024-10-13 00:40:07 +00:00
tmp_dir_path=get_run_tmp_file(Path("test_return_values")),
2024-05-31 23:36:43 +00:00
).replace('"', "'")
#
# # Overwrite old test with new instrumented test
with test_path_behavior.open("w") as f:
f.write(new_test_behavior)
with test_path_perf.open("w") as f:
f.write(new_test_perf)
2024-10-10 05:10:44 +00:00
test_env = os.environ.copy()
test_env["CODEFLASH_TEST_ITERATION"] = "0"
test_env["CODEFLASH_LOOP_INDEX"] = "1"
test_type = TestType.EXISTING_UNIT_TEST
test_files = TestFiles(
test_files=[
TestFile(
instrumented_behavior_file_path=test_path_behavior,
test_type=test_type,
original_file_path=test_path,
benchmarking_file_path=test_path_perf,
tests_in_file=[
TestsInFile(
test_file=test_path,
test_class="TestPigLatin",
test_function="test_sort",
test_type=TestType.EXISTING_UNIT_TEST,
)
],
)
]
2024-10-10 05:10:44 +00:00
)
test_config = TestConfig(
tests_root=tests_root,
tests_project_rootdir=project_root_path,
project_root_path=project_root_path,
test_framework="unittest",
pytest_cmd="pytest",
2024-10-10 05:10:44 +00:00
)
func_optimizer = FunctionOptimizer(function_to_optimize=func, test_cfg=test_config)
test_results, coverage_data = func_optimizer.run_and_parse_tests(
2024-10-10 05:10:44 +00:00
test_env=test_env,
2024-12-30 03:11:20 +00:00
testing_type=TestingMode.BEHAVIOR,
test_files=test_files,
optimization_iteration=0,
pytest_min_loops=1,
pytest_max_loops=1,
testing_time=0.1,
)
assert test_results[0].id.function_getting_tested == "sorter"
assert test_results[0].id.iteration_id == "2_2_0"
assert test_results[0].id.test_class_name == "TestPigLatin"
assert test_results[0].id.test_function_name == "test_sort"
assert (
test_results[0].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_loop_results_temp"
)
assert test_results[0].runtime > 0
assert test_results[0].did_pass
assert test_results[0].return_value == ([0, 1, 2, 3, 4, 5],)
2025-06-03 08:13:38 +00:00
out_str = """codeflash stdout: Sorting list
result: [0, 1, 2, 3, 4, 5]
"""
assert test_results[0].stdout == out_str
assert test_results[1].id.function_getting_tested == "sorter"
assert test_results[1].id.iteration_id == "2_2_1"
assert test_results[1].id.test_class_name == "TestPigLatin"
assert test_results[1].id.test_function_name == "test_sort"
assert (
test_results[1].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_loop_results_temp"
)
assert test_results[1].runtime > 0
assert test_results[1].did_pass
2025-06-03 08:13:38 +00:00
out_str = """codeflash stdout: Sorting list
result: [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
"""
assert test_results[1].stdout == out_str
assert test_results[2].id.function_getting_tested == "sorter"
assert test_results[2].id.iteration_id == "2_2_2"
assert test_results[2].id.test_class_name == "TestPigLatin"
assert test_results[2].id.test_function_name == "test_sort"
assert (
test_results[2].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_loop_results_temp"
)
assert test_results[2].runtime > 0
assert test_results[2].did_pass
2025-06-03 08:13:38 +00:00
out_str = """codeflash stdout: Sorting list
result: [0, 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]
"""
assert test_results[2].stdout == out_str
test_results, coverage_data = func_optimizer.run_and_parse_tests(
test_env=test_env,
2024-12-30 03:11:20 +00:00
testing_type=TestingMode.PERFORMANCE,
2024-10-10 05:10:44 +00:00
test_files=test_files,
optimization_iteration=0,
pytest_min_loops=1,
pytest_max_loops=1,
testing_time=0.1,
)
assert test_results[0].id.function_getting_tested == "sorter"
assert test_results[0].id.iteration_id == "2_2_0"
assert test_results[0].id.test_class_name == "TestPigLatin"
assert test_results[0].id.test_function_name == "test_sort"
assert (
test_results[0].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_loop_results_temp"
)
assert test_results[0].runtime > 0
assert test_results[0].did_pass
assert test_results[0].return_value is None
2024-10-10 05:10:44 +00:00
assert test_results[1].id.function_getting_tested == "sorter"
assert test_results[1].id.iteration_id == "2_2_1"
assert test_results[1].id.test_class_name == "TestPigLatin"
assert test_results[1].id.test_function_name == "test_sort"
assert (
test_results[1].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_loop_results_temp"
)
assert test_results[1].runtime > 0
assert test_results[1].did_pass
assert test_results[2].id.function_getting_tested == "sorter"
assert test_results[2].id.iteration_id == "2_2_2"
assert test_results[2].id.test_class_name == "TestPigLatin"
assert test_results[2].id.test_function_name == "test_sort"
assert (
test_results[2].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_loop_results_temp"
)
assert test_results[2].runtime > 0
assert test_results[2].did_pass
finally:
test_path.unlink(missing_ok=True)
test_path_behavior.unlink(missing_ok=True)
test_path_perf.unlink(missing_ok=True)
2024-05-15 11:47:05 +00:00
def test_perfinjector_bubble_sort_unittest_parametrized_loop_results() -> None:
code = """import unittest
from parameterized import parameterized
from code_to_optimize.bubble_sort import sorter
class TestPigLatin(unittest.TestCase):
@parameterized.expand(
[
([5, 4, 3, 2, 1, 0], [0, 1, 2, 3, 4, 5]),
([5.0, 4.0, 3.0, 2.0, 1.0, 0.0], [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]),
(list(reversed(range(50))), list(range(50))),
]
)
def test_sort(self, input, expected_output):
for i in range(2):
output = sorter(input)
self.assertEqual(output, expected_output)
"""
expected_behavior = (
2024-10-30 03:02:39 +00:00
"""import gc
import os
import sqlite3
2024-05-23 02:39:58 +00:00
import time
import unittest
2024-04-18 01:57:43 +00:00
import dill as pickle
2024-06-05 20:58:51 +00:00
import timeout_decorator
2024-05-23 02:39:58 +00:00
from parameterized import parameterized
2024-05-23 03:17:49 +00:00
from code_to_optimize.bubble_sort import sorter
"""
2024-10-30 03:02:39 +00:00
+ codeflash_wrap_string
+ """
class TestPigLatin(unittest.TestCase):
@parameterized.expand([([5, 4, 3, 2, 1, 0], [0, 1, 2, 3, 4, 5]), ([5.0, 4.0, 3.0, 2.0, 1.0, 0.0], [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]), (list(reversed(range(50))), list(range(50)))])
2024-06-05 20:58:51 +00:00
@timeout_decorator.timeout(15)
def test_sort(self, input, expected_output):
2024-10-03 19:06:48 +00:00
codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
codeflash_iteration = os.environ['CODEFLASH_TEST_ITERATION']
codeflash_con = sqlite3.connect(f'{tmp_dir_path}_{{codeflash_iteration}}.sqlite')
codeflash_cur = codeflash_con.cursor()
codeflash_cur.execute('CREATE TABLE IF NOT EXISTS test_results (test_module_path TEXT, test_class_name TEXT, test_function_name TEXT, function_getting_tested TEXT, loop_index INTEGER, iteration_id TEXT, runtime INTEGER, return_value BLOB, verification_type TEXT)')
for i in range(2):
2024-09-30 23:05:17 +00:00
output = codeflash_wrap(sorter, '{module_path}', 'TestPigLatin', 'test_sort', 'sorter', '0_0', codeflash_loop_index, codeflash_cur, codeflash_con, input)
self.assertEqual(output, expected_output)
2024-05-23 02:39:58 +00:00
codeflash_con.close()
"""
2024-10-30 03:02:39 +00:00
)
expected_perf = (
"""import gc
import os
import time
import unittest
import timeout_decorator
from parameterized import parameterized
from code_to_optimize.bubble_sort import sorter
"""
+ codeflash_wrap_perfonly_string
+ """
class TestPigLatin(unittest.TestCase):
@parameterized.expand([([5, 4, 3, 2, 1, 0], [0, 1, 2, 3, 4, 5]), ([5.0, 4.0, 3.0, 2.0, 1.0, 0.0], [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]), (list(reversed(range(50))), list(range(50)))])
@timeout_decorator.timeout(15)
def test_sort(self, input, expected_output):
codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
for i in range(2):
output = codeflash_wrap(sorter, '{module_path}', 'TestPigLatin', 'test_sort', 'sorter', '0_0', codeflash_loop_index, input)
self.assertEqual(output, expected_output)
"""
)
code_path = (Path(__file__).parent.resolve() / "../code_to_optimize/bubble_sort.py").resolve()
test_path = (
2024-10-13 00:07:42 +00:00
Path(__file__).parent.resolve()
/ "../code_to_optimize/tests/unittest/test_perfinjector_bubble_sort_unittest_parametrized_loop_results_temp.py"
2024-10-10 05:10:44 +00:00
).resolve()
test_path_behavior = (
Path(__file__).parent.resolve()
/ "../code_to_optimize/tests/unittest/test_perfinjector_bubble_sort_unittest_parametrized_loop_results_temp_behavior.py"
).resolve()
test_path_perf = (
Path(__file__).parent.resolve()
/ "../code_to_optimize/tests/unittest/test_perfinjector_bubble_sort_unittest_parametrized_loop_results_temp_perf.py"
).resolve()
try:
2024-10-13 00:07:42 +00:00
with test_path.open("w") as _f:
_f.write(code)
tests_root = (Path(__file__).parent.resolve() / "../code_to_optimize/tests/unittest/").resolve()
project_root_path = (Path(__file__).parent.resolve() / "../").resolve()
run_cwd = Path(__file__).parent.parent.resolve()
original_cwd = Path.cwd()
f = FunctionToOptimize(function_name="sorter", file_path=code_path, parents=[])
2024-10-13 00:07:42 +00:00
os.chdir(run_cwd)
success, new_test_behavior = inject_profiling_into_existing_test(
2024-12-30 03:11:20 +00:00
test_path, [CodePosition(17, 21)], f, project_root_path, "unittest", mode=TestingMode.BEHAVIOR
)
success, new_test_perf = inject_profiling_into_existing_test(
2024-12-30 03:11:20 +00:00
test_path, [CodePosition(17, 21)], f, project_root_path, "unittest", mode=TestingMode.PERFORMANCE
)
os.chdir(original_cwd)
assert success
assert new_test_behavior is not None
assert new_test_behavior.replace('"', "'") == expected_behavior.format(
module_path="code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_parametrized_loop_results_temp",
tmp_dir_path=get_run_tmp_file(Path("test_return_values")),
).replace('"', "'")
assert new_test_perf.replace('"', "'") == expected_perf.format(
2024-10-10 05:10:44 +00:00
module_path="code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_parametrized_loop_results_temp",
2024-10-13 00:40:07 +00:00
tmp_dir_path=get_run_tmp_file(Path("test_return_values")),
2024-05-31 23:36:43 +00:00
).replace('"', "'")
#
2024-10-10 05:10:44 +00:00
# Overwrite old test with new instrumented test
with test_path_behavior.open("w") as _f:
_f.write(new_test_behavior)
with test_path_perf.open("w") as _f:
_f.write(new_test_perf)
2024-10-10 05:10:44 +00:00
test_env = os.environ.copy()
test_env["CODEFLASH_TEST_ITERATION"] = "0"
test_env["CODEFLASH_LOOP_INDEX"] = "1"
test_type = TestType.EXISTING_UNIT_TEST
test_files = TestFiles(
test_files=[
TestFile(
instrumented_behavior_file_path=test_path_behavior,
test_type=test_type,
original_file_path=test_path,
benchmarking_file_path=test_path_perf,
tests_in_file=[
TestsInFile(
test_file=test_path,
test_class="TestPigLatin",
test_function="test_sort",
test_type=TestType.EXISTING_UNIT_TEST,
)
],
)
]
2024-10-10 05:10:44 +00:00
)
test_config = TestConfig(
tests_root=tests_root,
tests_project_rootdir=project_root_path,
project_root_path=project_root_path,
test_framework="unittest",
pytest_cmd="pytest",
)
func_optimizer = FunctionOptimizer(function_to_optimize=f, test_cfg=test_config)
test_results, coverage_data = func_optimizer.run_and_parse_tests(
2024-12-30 03:11:20 +00:00
testing_type=TestingMode.BEHAVIOR,
test_env=test_env,
test_files=test_files,
optimization_iteration=0,
pytest_min_loops=1,
pytest_max_loops=1,
testing_time=0.1,
)
assert test_results[0].id.function_getting_tested == "sorter"
assert test_results[0].id.iteration_id == "0_0_0"
assert test_results[0].id.test_class_name == "TestPigLatin"
assert test_results[0].id.test_function_name == "test_sort"
assert (
test_results[0].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_parametrized_loop_results_temp"
)
assert test_results[0].runtime > 0
assert test_results[0].did_pass
assert test_results[0].return_value == ([0, 1, 2, 3, 4, 5],)
2025-06-03 08:13:38 +00:00
out_str = """codeflash stdout: Sorting list
result: [0, 1, 2, 3, 4, 5]
"""
assert test_results[0].stdout == out_str
assert test_results[1].id.function_getting_tested == "sorter"
assert test_results[1].id.iteration_id == "0_0_1"
assert test_results[1].id.test_class_name == "TestPigLatin"
assert test_results[1].id.test_function_name == "test_sort"
assert (
test_results[1].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_parametrized_loop_results_temp"
)
assert test_results[1].runtime > 0
assert test_results[1].did_pass
2025-06-03 08:13:38 +00:00
out_str = """codeflash stdout: Sorting list
result: [0, 1, 2, 3, 4, 5]
"""
assert test_results[1].stdout == out_str
assert test_results[2].id.function_getting_tested == "sorter"
assert test_results[2].id.iteration_id == "0_0_2"
assert test_results[2].id.test_class_name == "TestPigLatin"
assert test_results[2].id.test_function_name == "test_sort"
assert (
test_results[2].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_parametrized_loop_results_temp"
)
assert test_results[2].runtime > 0
assert test_results[2].did_pass
2025-06-03 08:13:38 +00:00
out_str = """codeflash stdout: Sorting list
result: [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
"""
assert test_results[2].stdout == out_str
assert test_results[3].id.function_getting_tested == "sorter"
assert test_results[3].id.iteration_id == "0_0_3"
assert test_results[3].id.test_class_name == "TestPigLatin"
assert test_results[3].id.test_function_name == "test_sort"
assert (
test_results[3].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_parametrized_loop_results_temp"
)
assert test_results[3].runtime > 0
assert test_results[3].did_pass
assert test_results[4].id.function_getting_tested == "sorter"
assert test_results[4].id.iteration_id == "0_0_4"
assert test_results[4].id.test_class_name == "TestPigLatin"
assert test_results[4].id.test_function_name == "test_sort"
assert (
test_results[4].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_parametrized_loop_results_temp"
)
assert test_results[4].runtime > 0
assert test_results[4].did_pass
assert test_results[5].id.function_getting_tested == "sorter"
assert test_results[5].id.iteration_id == "0_0_5"
assert test_results[5].id.test_class_name == "TestPigLatin"
assert test_results[5].id.test_function_name == "test_sort"
assert (
test_results[5].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_parametrized_loop_results_temp"
)
assert test_results[5].runtime > 0
assert test_results[5].did_pass
test_results, coverage_data = func_optimizer.run_and_parse_tests(
2024-12-30 03:11:20 +00:00
testing_type=TestingMode.PERFORMANCE,
2024-10-10 05:10:44 +00:00
test_env=test_env,
test_files=test_files,
optimization_iteration=0,
pytest_min_loops=1,
pytest_max_loops=1,
testing_time=0.1,
)
assert test_results[0].id.function_getting_tested == "sorter"
assert test_results[0].id.iteration_id == "0_0_0"
assert test_results[0].id.test_class_name == "TestPigLatin"
assert test_results[0].id.test_function_name == "test_sort"
assert (
test_results[0].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_parametrized_loop_results_temp"
)
assert test_results[0].runtime > 0
assert test_results[0].did_pass
assert test_results[0].return_value is None
2024-10-10 05:10:44 +00:00
assert test_results[1].id.function_getting_tested == "sorter"
assert test_results[1].id.iteration_id == "0_0_1"
assert test_results[1].id.test_class_name == "TestPigLatin"
assert test_results[1].id.test_function_name == "test_sort"
assert (
test_results[1].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_parametrized_loop_results_temp"
)
assert test_results[1].runtime > 0
assert test_results[1].did_pass
assert test_results[2].id.function_getting_tested == "sorter"
assert test_results[2].id.iteration_id == "0_0_2"
assert test_results[2].id.test_class_name == "TestPigLatin"
assert test_results[2].id.test_function_name == "test_sort"
assert (
test_results[2].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_parametrized_loop_results_temp"
)
assert test_results[2].runtime > 0
assert test_results[2].did_pass
assert test_results[3].id.function_getting_tested == "sorter"
assert test_results[3].id.iteration_id == "0_0_3"
assert test_results[3].id.test_class_name == "TestPigLatin"
assert test_results[3].id.test_function_name == "test_sort"
assert (
test_results[3].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_parametrized_loop_results_temp"
)
assert test_results[3].runtime > 0
assert test_results[3].did_pass
assert test_results[4].id.function_getting_tested == "sorter"
assert test_results[4].id.iteration_id == "0_0_4"
assert test_results[4].id.test_class_name == "TestPigLatin"
assert test_results[4].id.test_function_name == "test_sort"
assert (
test_results[4].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_parametrized_loop_results_temp"
)
assert test_results[4].runtime > 0
assert test_results[4].did_pass
assert test_results[5].id.function_getting_tested == "sorter"
assert test_results[5].id.iteration_id == "0_0_5"
assert test_results[5].id.test_class_name == "TestPigLatin"
assert test_results[5].id.test_function_name == "test_sort"
assert (
test_results[5].id.test_module_path
== "code_to_optimize.tests.unittest.test_perfinjector_bubble_sort_unittest_parametrized_loop_results_temp"
)
assert test_results[5].runtime > 0
assert test_results[5].did_pass
finally:
2024-10-13 00:07:42 +00:00
test_path.unlink(missing_ok=True)
test_path_behavior.unlink(missing_ok=True)
test_path_perf.unlink(missing_ok=True)
2024-03-08 20:15:05 +00:00
2024-05-15 11:47:05 +00:00
def test_class_method_imported_as() -> None:
code = """import functionA
import moduleB as module_B
from module import functionB as function_B
import class_name_B
from nuitka.nodes.ImportNodes import ExpressionBuiltinImport as nuitka_nodes_ImportNodes_ExpressionBuiltinImport
"""
f = FunctionToOptimize(function_name="functionA", file_path=Path("module.py"), parents=[])
tree = ast.parse(code)
visitor = FunctionImportedAsVisitor(f)
visitor.visit(tree)
assert visitor.imported_as.function_name == "functionA"
f = FunctionToOptimize(function_name="functionB", file_path=Path("module.py"), parents=[])
visitor = FunctionImportedAsVisitor(f)
visitor.visit(tree)
assert visitor.imported_as.function_name == "function_B"
f = FunctionToOptimize(
function_name="method_name",
2024-10-13 00:07:42 +00:00
file_path=Path("module.py"),
parents=[FunctionParent("ExpressionBuiltinImport", "ClassDef")],
)
visitor = FunctionImportedAsVisitor(f)
visitor.visit(tree)
assert visitor.imported_as.qualified_name == "nuitka_nodes_ImportNodes_ExpressionBuiltinImport.method_name"
f = FunctionToOptimize(function_name="class_name_B", file_path=Path("module.py"), parents=[])
visitor = FunctionImportedAsVisitor(f)
visitor.visit(tree)
assert visitor.imported_as.qualified_name == "class_name_B"
2024-05-03 20:30:02 +00:00
2024-05-15 11:47:05 +00:00
def test_class_function_instrumentation() -> None:
2024-05-03 20:30:02 +00:00
code = """from module import class_name as class_name_A
def test_class_name_A_function_name():
ret = class_name_A.function_name(**args)
"""
2024-10-30 03:02:39 +00:00
expected = (
"""import gc
2024-05-03 20:30:02 +00:00
import os
import sqlite3
2024-05-23 02:39:58 +00:00
import time
2024-05-03 20:30:02 +00:00
import dill as pickle
2024-05-23 02:39:58 +00:00
from module import class_name as class_name_A
2024-05-03 20:30:02 +00:00
"""
2024-10-30 03:02:39 +00:00
+ codeflash_wrap_string
+ """
2024-09-30 23:05:17 +00:00
def test_class_name_A_function_name():
2024-10-03 19:06:48 +00:00
codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
codeflash_iteration = os.environ['CODEFLASH_TEST_ITERATION']
2024-05-03 20:30:02 +00:00
codeflash_con = sqlite3.connect(f'{tmp_dir_path}_{{codeflash_iteration}}.sqlite')
codeflash_cur = codeflash_con.cursor()
codeflash_cur.execute('CREATE TABLE IF NOT EXISTS test_results (test_module_path TEXT, test_class_name TEXT, test_function_name TEXT, function_getting_tested TEXT, loop_index INTEGER, iteration_id TEXT, runtime INTEGER, return_value BLOB, verification_type TEXT)')
2024-09-30 23:05:17 +00:00
ret = codeflash_wrap(class_name_A.function_name, '{module_path}', None, 'test_class_name_A_function_name', 'class_name_A.function_name', '0', codeflash_loop_index, codeflash_cur, codeflash_con, **args)
2024-05-23 02:39:58 +00:00
codeflash_con.close()
"""
2024-10-30 03:02:39 +00:00
)
2024-05-03 20:30:02 +00:00
test_path = (
Path(__file__).parent.resolve() / "../code_to_optimize/tests/pytest/test_class_function_instrumentation_temp.py"
2024-05-03 20:30:02 +00:00
)
try:
with open(test_path, "w") as f:
f.write(code)
2024-05-03 20:30:02 +00:00
2024-10-13 00:07:42 +00:00
project_root_path = Path(__file__).parent.resolve() / "../code_to_optimize/"
run_cwd = Path(__file__).parent.parent.resolve()
original_cwd = Path.cwd()
func = FunctionToOptimize(
function_name="function_name",
2024-10-13 00:07:42 +00:00
file_path=project_root_path / "module.py",
parents=[FunctionParent("class_name", "ClassDef")],
2024-06-05 20:58:51 +00:00
)
os.chdir(str(run_cwd))
success, new_test = inject_profiling_into_existing_test(
test_path, [CodePosition(4, 23)], func, project_root_path, "pytest"
)
os.chdir(original_cwd)
finally:
2024-10-13 00:07:42 +00:00
test_path.unlink(missing_ok=True)
2024-05-03 20:30:02 +00:00
assert success
2024-10-13 00:40:07 +00:00
assert new_test is not None
2024-05-31 23:36:43 +00:00
assert new_test.replace('"', "'") == expected.format(
2024-10-13 00:40:07 +00:00
tmp_dir_path=get_run_tmp_file(Path("test_return_values")),
2024-05-03 20:30:02 +00:00
module_path="tests.pytest.test_class_function_instrumentation_temp",
2024-05-31 23:36:43 +00:00
).replace('"', "'")
2024-05-15 11:47:05 +00:00
def test_wrong_function_instrumentation() -> None:
code = """from codeflash.result.common_tags import find_common_tags
def test_common_tags_1():
articles_1 = [1, 2, 3]
assert find_common_tags(articles_1) == set(1, 2)
articles_2 = [1, 2]
assert find_common_tags(articles_2) == set(1)
"""
2024-10-30 03:02:39 +00:00
expected = (
"""import gc
2024-05-15 11:47:05 +00:00
import os
import sqlite3
2024-05-23 02:39:58 +00:00
import time
2024-05-15 11:47:05 +00:00
import dill as pickle
2024-05-31 22:38:34 +00:00
2024-05-23 02:39:58 +00:00
from codeflash.result.common_tags import find_common_tags
2024-05-15 11:47:05 +00:00
"""
2024-10-30 03:02:39 +00:00
+ codeflash_wrap_string
+ """
2024-09-30 23:05:17 +00:00
def test_common_tags_1():
2024-10-03 19:06:48 +00:00
codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
codeflash_iteration = os.environ['CODEFLASH_TEST_ITERATION']
2024-05-15 11:47:05 +00:00
codeflash_con = sqlite3.connect(f'{tmp_dir_path}_{{codeflash_iteration}}.sqlite')
codeflash_cur = codeflash_con.cursor()
codeflash_cur.execute('CREATE TABLE IF NOT EXISTS test_results (test_module_path TEXT, test_class_name TEXT, test_function_name TEXT, function_getting_tested TEXT, loop_index INTEGER, iteration_id TEXT, runtime INTEGER, return_value BLOB, verification_type TEXT)')
2024-05-15 11:47:05 +00:00
articles_1 = [1, 2, 3]
assert codeflash_wrap(find_common_tags, '{module_path}', None, 'test_common_tags_1', 'find_common_tags', '1', codeflash_loop_index, codeflash_cur, codeflash_con, articles_1) == set(1, 2)
2024-05-15 11:47:05 +00:00
articles_2 = [1, 2]
assert codeflash_wrap(find_common_tags, '{module_path}', None, 'test_common_tags_1', 'find_common_tags', '3', codeflash_loop_index, codeflash_cur, codeflash_con, articles_2) == set(1)
2024-05-23 02:39:58 +00:00
codeflash_con.close()
"""
2024-10-30 03:02:39 +00:00
)
2024-05-15 11:47:05 +00:00
test_path = (
Path(__file__).parent.resolve() / "../code_to_optimize/tests/pytest/test_wrong_function_instrumentation_temp.py"
2024-05-15 11:47:05 +00:00
)
try:
2024-10-13 00:07:42 +00:00
with test_path.open("w") as f:
f.write(code)
2024-05-15 11:47:05 +00:00
2024-10-13 00:07:42 +00:00
tests_root = Path(__file__).parent.resolve() / "../code_to_optimize/tests/pytest/"
project_root_path = Path(__file__).parent.resolve() / "../code_to_optimize/"
run_cwd = Path(__file__).parent.parent.resolve()
original_cwd = Path.cwd()
func = FunctionToOptimize(
function_name="find_common_tags", file_path=project_root_path / "module.py", parents=[]
2024-06-05 20:58:51 +00:00
)
2024-05-15 11:47:05 +00:00
os.chdir(str(run_cwd))
success, new_test = inject_profiling_into_existing_test(
test_path, [CodePosition(7, 11), CodePosition(11, 11)], func, project_root_path, "pytest"
)
os.chdir(original_cwd)
assert success
2024-10-13 00:40:07 +00:00
assert new_test is not None
2024-05-31 23:36:43 +00:00
assert new_test.replace('"', "'") == expected.format(
module_path="tests.pytest.test_wrong_function_instrumentation_temp",
2024-10-13 00:40:07 +00:00
tmp_dir_path=get_run_tmp_file(Path("test_return_values")),
2024-05-31 23:36:43 +00:00
).replace('"', "'")
finally:
2024-10-13 00:07:42 +00:00
test_path.unlink(missing_ok=True)
2024-07-10 21:21:25 +00:00
def test_conditional_instrumentation() -> None:
code = """from code_to_optimize.bubble_sort import sorter
def test_sort():
input = [5, 4, 3, 2, 1, 0]
if len(input) > 0:
assert sorter(input) == [0, 1, 2, 3, 4, 5]"""
2024-10-30 03:02:39 +00:00
expected = (
"""import gc
2024-07-10 21:21:25 +00:00
import os
import sqlite3
import time
import dill as pickle
from code_to_optimize.bubble_sort import sorter
"""
2024-10-30 03:02:39 +00:00
+ codeflash_wrap_string
+ """
2024-09-30 23:05:17 +00:00
def test_sort():
2024-10-03 19:06:48 +00:00
codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
codeflash_iteration = os.environ['CODEFLASH_TEST_ITERATION']
2024-07-10 21:21:25 +00:00
codeflash_con = sqlite3.connect(f'{tmp_dir_path}_{{codeflash_iteration}}.sqlite')
codeflash_cur = codeflash_con.cursor()
codeflash_cur.execute('CREATE TABLE IF NOT EXISTS test_results (test_module_path TEXT, test_class_name TEXT, test_function_name TEXT, function_getting_tested TEXT, loop_index INTEGER, iteration_id TEXT, runtime INTEGER, return_value BLOB, verification_type TEXT)')
2024-07-10 21:21:25 +00:00
input = [5, 4, 3, 2, 1, 0]
if len(input) > 0:
assert codeflash_wrap(sorter, '{module_path}', None, 'test_sort', 'sorter', '1_0', codeflash_loop_index, codeflash_cur, codeflash_con, input) == [0, 1, 2, 3, 4, 5]
2024-07-10 21:21:25 +00:00
codeflash_con.close()
"""
2024-10-30 03:02:39 +00:00
)
2024-07-10 21:21:25 +00:00
test_path = (
Path(__file__).parent.resolve() / "../code_to_optimize/tests/pytest/test_conditional_instrumentation_temp.py"
2024-07-10 21:21:25 +00:00
)
try:
with open(test_path, "w") as f:
f.write(code)
2024-10-13 00:07:42 +00:00
tests_root = Path(__file__).parent.resolve() / "../code_to_optimize/tests/pytest/"
project_root_path = Path(__file__).parent.resolve() / "../code_to_optimize/"
run_cwd = Path(__file__).parent.parent.resolve()
original_cwd = Path.cwd()
func = FunctionToOptimize(function_name="sorter", file_path=project_root_path / "module.py", parents=[])
2024-07-10 21:21:25 +00:00
os.chdir(str(run_cwd))
2024-07-10 21:21:25 +00:00
success, new_test = inject_profiling_into_existing_test(
test_path, [CodePosition(7, 15)], func, project_root_path, "pytest"
2024-07-10 21:21:25 +00:00
)
os.chdir(original_cwd)
2024-07-10 21:21:25 +00:00
assert success
2024-10-13 00:40:07 +00:00
assert new_test is not None
2024-07-10 21:21:25 +00:00
assert new_test.replace('"', "'") == expected.format(
module_path="tests.pytest.test_conditional_instrumentation_temp",
2024-10-13 00:40:07 +00:00
tmp_dir_path=get_run_tmp_file(Path("test_return_values")),
2024-07-10 21:21:25 +00:00
).replace('"', "'")
finally:
2024-10-13 00:07:42 +00:00
test_path.unlink(missing_ok=True)
def test_static_method_instrumentation():
code = """from code_to_optimize.bubble_sort import BubbleSorter
def test_sort():
input = [5, 4, 3, 2, 1, 0]
output = BubbleSorter.sorter(input)
assert output == [0, 1, 2, 3, 4, 5]
input = [5.0, 4.0, 3.0, 2.0, 1.0, 0.0]
output = BubbleSorter.sorter(input)
assert output == [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]"""
2024-10-30 03:02:39 +00:00
expected = (
"""import gc
import os
import sqlite3
import time
import dill as pickle
from code_to_optimize.bubble_sort import BubbleSorter
"""
2024-10-30 03:02:39 +00:00
+ codeflash_wrap_string
+ """
2024-09-30 23:05:17 +00:00
def test_sort():
2024-10-03 19:06:48 +00:00
codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
codeflash_iteration = os.environ['CODEFLASH_TEST_ITERATION']
codeflash_con = sqlite3.connect(f'{tmp_dir_path}_{{codeflash_iteration}}.sqlite')
codeflash_cur = codeflash_con.cursor()
codeflash_cur.execute('CREATE TABLE IF NOT EXISTS test_results (test_module_path TEXT, test_class_name TEXT, test_function_name TEXT, function_getting_tested TEXT, loop_index INTEGER, iteration_id TEXT, runtime INTEGER, return_value BLOB, verification_type TEXT)')
input = [5, 4, 3, 2, 1, 0]
output = codeflash_wrap(BubbleSorter.sorter, 'tests.pytest.test_perfinjector_bubble_sort_results_temp', None, 'test_sort', 'BubbleSorter.sorter', '1', codeflash_loop_index, codeflash_cur, codeflash_con, input)
assert output == [0, 1, 2, 3, 4, 5]
input = [5.0, 4.0, 3.0, 2.0, 1.0, 0.0]
output = codeflash_wrap(BubbleSorter.sorter, '{module_path}', None, 'test_sort', 'BubbleSorter.sorter', '4', codeflash_loop_index, codeflash_cur, codeflash_con, input)
assert output == [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
codeflash_con.close()
"""
2024-10-30 03:02:39 +00:00
)
function_to_optimize = FunctionToOptimize(
function_name="sorter",
2024-10-13 00:07:42 +00:00
file_path=Path("/Users/renaud/repos/codeflash/cli/code_to_optimize/bubble_sort.py"),
parents=[FunctionParent("BubbleSorter", "ClassDef")],
starting_line=None,
ending_line=None,
)
test_path = (
2024-10-13 00:07:42 +00:00
Path(__file__).parent.resolve()
/ "../code_to_optimize/tests/pytest/test_perfinjector_bubble_sort_results_temp.py"
)
try:
2024-10-13 00:07:42 +00:00
with test_path.open("w") as f:
f.write(code)
2024-10-13 00:07:42 +00:00
tests_root = Path(__file__).parent.resolve() / "../code_to_optimize/tests/pytest/"
project_root_path = Path(__file__).parent.resolve() / "../code_to_optimize/"
run_cwd = Path(__file__).parent.parent.resolve()
original_cwd = Path.cwd()
2024-10-13 00:07:42 +00:00
os.chdir(run_cwd)
success, new_test = inject_profiling_into_existing_test(
test_path, [CodePosition(6, 26), CodePosition(10, 26)], function_to_optimize, project_root_path, "pytest"
)
os.chdir(original_cwd)
assert success
2024-10-13 00:40:07 +00:00
formatted_expected = expected.format(
module_path="tests.pytest.test_perfinjector_bubble_sort_results_temp",
2024-10-13 00:40:07 +00:00
tmp_dir_path=str(get_run_tmp_file(Path("test_return_values"))),
)
assert new_test is not None
assert new_test.replace('"', "'") == formatted_expected.replace('"', "'")
finally:
2024-10-13 00:07:42 +00:00
test_path.unlink(missing_ok=True)
def test_class_method_instrumentation() -> None:
code = """from codeflash.optimization.optimizer import Optimizer
def test_code_replacement10() -> None:
get_code_output = '''random code'''
file_path = Path(__file__).resolve()
opt = Optimizer(
Namespace(
project_root=str(file_path.parent.resolve()),
disable_telemetry=True,
tests_root="tests",
test_framework="pytest",
pytest_cmd="pytest",
experiment_id=None,
),
)
func_top_optimize = FunctionToOptimize(
function_name="main_method",
file_path=str(file_path),
parents=[FunctionParent("MainClass", "ClassDef")],
)
with open(file_path) as f:
original_code = f.read()
code_context = opt.get_code_optimization_context(
function_to_optimize=func_top_optimize,
project_root=str(file_path.parent),
original_source_code=original_code,
).unwrap()
assert code_context.testgen_context_code == get_code_output
code_context = opt.get_code_optimization_context(
function_to_optimize=func_top_optimize,
project_root=str(file_path.parent),
original_source_code=original_code,
)
assert code_context.testgen_context_code == get_code_output
"""
2025-06-03 08:13:38 +00:00
expected = (
"""import gc
import os
import sqlite3
import time
import dill as pickle
from codeflash.optimization.optimizer import Optimizer
"""
2025-06-03 08:13:38 +00:00
+ codeflash_wrap_string
+ """
2024-09-30 23:05:17 +00:00
def test_code_replacement10() -> None:
2024-10-03 19:06:48 +00:00
codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
codeflash_iteration = os.environ['CODEFLASH_TEST_ITERATION']
codeflash_con = sqlite3.connect(f'{tmp_dir_path}_{{codeflash_iteration}}.sqlite')
codeflash_cur = codeflash_con.cursor()
codeflash_cur.execute('CREATE TABLE IF NOT EXISTS test_results (test_module_path TEXT, test_class_name TEXT, test_function_name TEXT, function_getting_tested TEXT, loop_index INTEGER, iteration_id TEXT, runtime INTEGER, return_value BLOB, verification_type TEXT)')
get_code_output = 'random code'
file_path = Path(__file__).resolve()
opt = Optimizer(Namespace(project_root=str(file_path.parent.resolve()), disable_telemetry=True, tests_root='tests', test_framework='pytest', pytest_cmd='pytest', experiment_id=None))
func_top_optimize = FunctionToOptimize(function_name='main_method', file_path=str(file_path), parents=[FunctionParent('MainClass', 'ClassDef')])
with open(file_path) as f:
original_code = f.read()
code_context = codeflash_wrap(opt.get_code_optimization_context, '{module_path}', None, 'test_code_replacement10', 'Optimizer.get_code_optimization_context', '4_1', codeflash_loop_index, codeflash_cur, codeflash_con, function_to_optimize=func_top_optimize, project_root=str(file_path.parent), original_source_code=original_code).unwrap()
assert code_context.testgen_context_code == get_code_output
code_context = codeflash_wrap(opt.get_code_optimization_context, '{module_path}', None, 'test_code_replacement10', 'Optimizer.get_code_optimization_context', '4_3', codeflash_loop_index, codeflash_cur, codeflash_con, function_to_optimize=func_top_optimize, project_root=str(file_path.parent), original_source_code=original_code)
assert code_context.testgen_context_code == get_code_output
codeflash_con.close()
"""
2025-06-03 08:13:38 +00:00
)
with tempfile.NamedTemporaryFile(mode="w") as f:
f.write(code)
f.flush()
func = FunctionToOptimize(
function_name="get_code_optimization_context",
parents=[FunctionParent("Optimizer", "ClassDef")],
file_path=Path(f.name),
)
2024-10-13 00:07:42 +00:00
original_cwd = Path.cwd()
run_cwd = Path(__file__).parent.parent.resolve()
os.chdir(run_cwd)
success, new_test = inject_profiling_into_existing_test(
Path(f.name), [CodePosition(22, 28), CodePosition(28, 28)], func, Path(f.name).parent, "pytest"
)
os.chdir(original_cwd)
assert success
2025-06-03 08:13:38 +00:00
assert new_test.replace('"', "'") == expected.replace('"', "'").format(
module_path=Path(f.name).name, tmp_dir_path=get_run_tmp_file(Path("test_return_values"))
)
2024-10-10 23:40:20 +00:00
def test_time_correction_instrumentation() -> None:
2024-10-23 21:38:23 +00:00
code = """from code_to_optimize.sleeptime import accurate_sleepfunc
2024-10-17 14:26:55 +00:00
import pytest
@pytest.mark.parametrize("n, expected_total_sleep_time", [
2024-10-23 21:38:23 +00:00
(0.01, 0.010),
(0.02, 0.020),
2024-10-17 14:26:55 +00:00
])
def test_sleepfunc_sequence_short(n, expected_total_sleep_time):
2024-10-23 21:38:23 +00:00
output = accurate_sleepfunc(n)
2024-10-18 22:43:26 +00:00
assert output == expected_total_sleep_time
2024-10-17 14:26:55 +00:00
"""
2024-10-30 03:02:39 +00:00
expected = (
"""import gc
import os
import time
2024-10-17 14:58:51 +00:00
import pytest
2024-10-23 21:38:23 +00:00
from code_to_optimize.sleeptime import accurate_sleepfunc
2024-10-10 23:40:20 +00:00
"""
+ codeflash_wrap_perfonly_string
2024-10-30 03:02:39 +00:00
+ """
2024-10-24 01:55:24 +00:00
@pytest.mark.parametrize('n, expected_total_sleep_time', [(0.01, 0.01), (0.02, 0.02)])
2024-10-17 14:26:55 +00:00
def test_sleepfunc_sequence_short(n, expected_total_sleep_time):
codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
output = codeflash_wrap(accurate_sleepfunc, '{module_path}', None, 'test_sleepfunc_sequence_short', 'accurate_sleepfunc', '0', codeflash_loop_index, n)
2024-10-18 22:43:26 +00:00
assert output == expected_total_sleep_time
"""
2024-10-30 03:02:39 +00:00
)
code_path = (Path(__file__).parent.resolve() / "../code_to_optimize/sleeptime.py").resolve()
test_path = (
2024-10-17 00:27:36 +00:00
Path(__file__).parent.resolve()
2024-10-17 20:47:40 +00:00
/ "../code_to_optimize/tests/pytest/test_time_correction_instrumentation_temp.py"
).resolve()
2024-10-10 23:40:20 +00:00
try:
2024-10-17 00:27:36 +00:00
with test_path.open("w") as f:
f.write(code)
2024-10-17 20:47:40 +00:00
tests_root = (Path(__file__).parent.resolve() / "../code_to_optimize/tests/pytest/").resolve()
2024-10-17 00:27:36 +00:00
project_root_path = (Path(__file__).parent.resolve() / "../").resolve()
original_cwd = Path.cwd()
2024-10-17 19:32:15 +00:00
run_cwd = Path(__file__).parent.parent.resolve()
func = FunctionToOptimize(function_name="accurate_sleepfunc", parents=[], file_path=code_path)
2024-10-17 00:27:36 +00:00
os.chdir(run_cwd)
2024-10-10 23:40:20 +00:00
success, new_test = inject_profiling_into_existing_test(
2024-12-30 03:11:20 +00:00
test_path, [CodePosition(8, 13)], func, project_root_path, "pytest", mode=TestingMode.PERFORMANCE
2024-10-10 23:40:20 +00:00
)
os.chdir(original_cwd)
test_env = os.environ.copy()
test_env["CODEFLASH_TEST_ITERATION"] = "0"
2024-10-17 06:10:02 +00:00
test_env["CODEFLASH_LOOP_INDEX"] = "1"
test_type = TestType.EXISTING_UNIT_TEST
2024-10-18 18:22:12 +00:00
assert success, "Test instrumentation failed"
2024-10-17 00:27:36 +00:00
assert new_test is not None
assert new_test.replace('"', "'") == expected.format(
2024-10-17 20:47:40 +00:00
module_path="code_to_optimize.tests.pytest.test_time_correction_instrumentation_temp",
2024-10-17 00:27:36 +00:00
tmp_dir_path=get_run_tmp_file(Path("test_return_values")),
).replace('"', "'")
# Overwrite old test with new instrumented test
2024-10-17 00:27:36 +00:00
with test_path.open("w") as f:
f.write(new_test)
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",
2024-10-10 23:40:20 +00:00
)
func_optimizer = FunctionOptimizer(function_to_optimize=func, test_cfg=test_config)
test_files = TestFiles(
test_files=[
TestFile(
instrumented_behavior_file_path=test_path,
test_type=test_type,
original_file_path=test_path,
benchmarking_file_path=test_path,
)
]
)
test_results, coverage_data = func_optimizer.run_and_parse_tests(
2024-12-30 03:11:20 +00:00
testing_type=TestingMode.PERFORMANCE,
test_env=test_env,
test_files=test_files,
optimization_iteration=0,
2024-10-24 01:55:24 +00:00
pytest_min_loops=2,
pytest_max_loops=2,
testing_time=0.1,
)
2024-10-17 14:26:55 +00:00
2024-10-23 21:38:23 +00:00
assert test_results[0].id.function_getting_tested == "accurate_sleepfunc"
2024-10-17 10:10:29 +00:00
assert test_results[0].id.iteration_id == "0_0"
assert test_results[0].id.test_class_name is None
assert test_results[0].id.test_function_name == "test_sleepfunc_sequence_short"
assert (
2024-10-17 10:10:29 +00:00
test_results[0].id.test_module_path
2024-10-17 20:47:40 +00:00
== "code_to_optimize.tests.pytest.test_time_correction_instrumentation_temp"
)
2024-10-18 22:43:26 +00:00
2024-10-24 01:55:24 +00:00
assert len(test_results) == 4
2024-10-23 21:38:23 +00:00
for i, test_result in enumerate(test_results):
assert test_result.did_pass
2024-10-24 01:55:24 +00:00
assert math.isclose(test_result.runtime, ((i % 2) + 1) * 100_000_000, rel_tol=0.01)
2024-10-10 23:40:20 +00:00
finally:
2024-10-17 00:27:36 +00:00
test_path.unlink(missing_ok=True)
def test_time_correction_instrumentation_unittest() -> None:
code = """import unittest
from parameterized import parameterized
2024-10-23 21:38:23 +00:00
from code_to_optimize.sleeptime import accurate_sleepfunc
class TestPigLatin(unittest.TestCase):
@parameterized.expand([
2024-10-23 21:38:23 +00:00
(0.01, 0.010),
(0.02, 0.020),
])
def test_sleepfunc_sequence_short(self, n, expected_total_sleep_time):
2024-10-23 21:38:23 +00:00
output = accurate_sleepfunc(n)
"""
2024-10-30 03:02:39 +00:00
expected = (
"""import gc
import os
import time
import unittest
import timeout_decorator
from parameterized import parameterized
2024-10-23 21:38:23 +00:00
from code_to_optimize.sleeptime import accurate_sleepfunc
"""
+ codeflash_wrap_perfonly_string
2024-10-30 03:02:39 +00:00
+ """
class TestPigLatin(unittest.TestCase):
2024-10-23 21:38:23 +00:00
@parameterized.expand([(0.01, 0.01), (0.02, 0.02)])
@timeout_decorator.timeout(15)
def test_sleepfunc_sequence_short(self, n, expected_total_sleep_time):
codeflash_loop_index = int(os.environ['CODEFLASH_LOOP_INDEX'])
output = codeflash_wrap(accurate_sleepfunc, '{module_path}', 'TestPigLatin', 'test_sleepfunc_sequence_short', 'accurate_sleepfunc', '0', codeflash_loop_index, n)
"""
2024-10-30 03:02:39 +00:00
)
code_path = (Path(__file__).parent.resolve() / "../code_to_optimize/sleeptime.py").resolve()
test_path = (
Path(__file__).parent.resolve()
/ "../code_to_optimize/tests/unittest/test_time_correction_instrumentation_unittest_temp.py"
).resolve()
try:
with test_path.open("w") as f:
f.write(code)
tests_root = (Path(__file__).parent.resolve() / "../code_to_optimize/tests/unittest/").resolve()
project_root_path = (Path(__file__).parent.resolve() / "../").resolve()
original_cwd = Path.cwd()
run_cwd = Path(__file__).parent.parent.resolve()
func = FunctionToOptimize(function_name="accurate_sleepfunc", parents=[], file_path=code_path)
os.chdir(run_cwd)
success, new_test = inject_profiling_into_existing_test(
2024-12-30 03:11:20 +00:00
test_path, [CodePosition(12, 17)], func, project_root_path, "unittest", mode=TestingMode.PERFORMANCE
)
os.chdir(original_cwd)
test_env = os.environ.copy()
test_env["CODEFLASH_TEST_ITERATION"] = "0"
test_env["CODEFLASH_LOOP_INDEX"] = "1"
test_type = TestType.EXISTING_UNIT_TEST
assert success, "Test instrumentation failed"
assert new_test is not None
assert new_test.replace('"', "'") == expected.format(
module_path="code_to_optimize.tests.unittest.test_time_correction_instrumentation_unittest_temp",
tmp_dir_path=get_run_tmp_file(Path("test_return_values")),
).replace('"', "'")
# Overwrite old test with new instrumented test
with test_path.open("w") as f:
f.write(new_test)
test_files = TestFiles(
test_files=[
TestFile(
instrumented_behavior_file_path=test_path,
test_type=test_type,
original_file_path=test_path,
benchmarking_file_path=test_path,
tests_in_file=[
TestsInFile(
test_file=test_path,
test_class="TestPigLatin",
test_function="test_sleepfunc_sequence_short",
test_type=TestType.EXISTING_UNIT_TEST,
)
],
)
]
)
test_config = TestConfig(
tests_root=tests_root,
tests_project_rootdir=project_root_path,
project_root_path=project_root_path,
test_framework="unittest",
pytest_cmd="pytest",
)
func_optimizer = FunctionOptimizer(function_to_optimize=func, test_cfg=test_config)
test_results, coverage_data = func_optimizer.run_and_parse_tests(
2024-12-30 03:11:20 +00:00
testing_type=TestingMode.PERFORMANCE,
test_env=test_env,
test_files=test_files,
optimization_iteration=0,
testing_time=0.1,
)
2024-10-23 21:38:23 +00:00
assert test_results[0].id.function_getting_tested == "accurate_sleepfunc"
assert test_results[0].id.iteration_id == "0_0"
assert test_results[0].id.test_class_name == "TestPigLatin"
assert test_results[0].id.test_function_name == "test_sleepfunc_sequence_short"
assert (
test_results[0].id.test_module_path
== "code_to_optimize.tests.unittest.test_time_correction_instrumentation_unittest_temp"
)
2024-10-23 21:38:23 +00:00
assert len(test_results) == 2
for i, test_result in enumerate(test_results):
2024-10-23 21:38:23 +00:00
assert test_result.did_pass
assert math.isclose(test_result.runtime, ((i % 2) + 1) * 100_000_000, rel_tol=0.01)
finally:
test_path.unlink(missing_ok=True)