Skip to content

Commit ff8d477

Browse files
committed
few manual fixes
1 parent 44b71e7 commit ff8d477

File tree

4 files changed

+45
-36
lines changed

4 files changed

+45
-36
lines changed

codeflash/verification/pytest_plugin.py

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -97,10 +97,10 @@ def pytest_addoption(parser: Parser) -> None:
9797
@pytest.hookimpl(trylast=True)
9898
def pytest_configure(config: Config) -> None:
9999
config.addinivalue_line("markers", "loops(n): run the given test function `n` times.")
100-
config.pluginmanager.register(PyTest_Loops(config), PyTest_Loops.name)
100+
config.pluginmanager.register(PytestLoops(config), PytestLoops.name)
101101

102102

103-
class PyTest_Loops:
103+
class PytestLoops:
104104
name: str = "pytest-loops"
105105

106106
def __init__(self, config: Config) -> None:
@@ -113,9 +113,8 @@ def __init__(self, config: Config) -> None:
113113
def pytest_runtestloop(self, session: Session) -> bool:
114114
"""Reimplement the test loop but loop for the user defined amount of time."""
115115
if session.testsfailed and not session.config.option.continue_on_collection_errors:
116-
raise session.Interrupted(
117-
"%d error%s during collection" % (session.testsfailed, "s" if session.testsfailed != 1 else "")
118-
)
116+
msg = "{} error{} during collection".format(session.testsfailed, "s" if session.testsfailed != 1 else "")
117+
raise session.Interrupted(msg)
119118

120119
if session.config.option.collectonly:
121120
return True
@@ -130,11 +129,11 @@ def pytest_runtestloop(self, session: Session) -> bool:
130129
total_time = self._get_total_time(session)
131130

132131
for index, item in enumerate(session.items):
133-
item: pytest.Item = item
134-
item._report_sections.clear() # clear reports for new test
132+
item: pytest.Item = item # noqa: PLW0127, PLW2901
133+
item._report_sections.clear() # clear reports for new test # noqa: SLF001
135134

136135
if total_time > SHORTEST_AMOUNT_OF_TIME:
137-
item._nodeid = self._set_nodeid(item._nodeid, count)
136+
item._nodeid = self._set_nodeid(item._nodeid, count) # noqa: SLF001
138137

139138
next_item: pytest.Item = session.items[index + 1] if index + 1 < len(session.items) else None
140139

@@ -234,7 +233,8 @@ def _get_total_time(self, session: Session) -> float:
234233
seconds = session.config.option.codeflash_seconds
235234
total_time = hours_in_seconds + minutes_in_seconds + seconds
236235
if total_time < SHORTEST_AMOUNT_OF_TIME:
237-
raise InvalidTimeParameterError(f"Total time cannot be less than: {SHORTEST_AMOUNT_OF_TIME}!")
236+
msg = f"Total time cannot be less than: {SHORTEST_AMOUNT_OF_TIME}!"
237+
raise InvalidTimeParameterError(msg)
238238
return total_time
239239

240240
def _timed_out(self, session: Session, start_time: float, count: int) -> bool:
@@ -262,11 +262,10 @@ def __pytest_loop_step_number(self, request: pytest.FixtureRequest) -> int:
262262
return request.param
263263
except AttributeError:
264264
if issubclass(request.cls, TestCase):
265-
warnings.warn("Repeating unittest class tests not supported")
265+
warnings.warn("Repeating unittest class tests not supported", stacklevel=2)
266266
else:
267-
raise UnexpectedError(
268-
"This call couldn't work with pytest-loops. Please consider raising an issue with your usage."
269-
)
267+
msg = "This call couldn't work with pytest-loops. Please consider raising an issue with your usage."
268+
raise UnexpectedError(msg) from None
270269
return count
271270

272271
@pytest.hookimpl(trylast=True)

codeflash/verification/test_results.py

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
from __future__ import annotations
22

33
import sys
4-
from collections.abc import Iterator
54
from enum import Enum
65
from pathlib import Path
7-
from typing import Optional, cast
6+
from typing import TYPE_CHECKING, Optional, cast
87

98
from pydantic import BaseModel
109
from pydantic.dataclasses import dataclass
@@ -13,6 +12,9 @@
1312
from codeflash.cli_cmds.console import DEBUG_MODE, logger
1413
from codeflash.verification.comparator import comparator
1514

15+
if TYPE_CHECKING:
16+
from collections.abc import Iterator
17+
1618

1719
class VerificationType(str, Enum):
1820
FUNCTION_CALL = (
@@ -53,7 +55,11 @@ class InvocationId:
5355

5456
# test_module_path:TestSuiteClass.test_function_name:function_tested:iteration_id
5557
def id(self) -> str:
56-
return f"{self.test_module_path}:{(self.test_class_name + '.' if self.test_class_name else '')}{self.test_function_name}:{self.function_getting_tested}:{self.iteration_id}"
58+
class_prefix = f"{self.test_class_name}." if self.test_class_name else ""
59+
return (
60+
f"{self.test_module_path}:{class_prefix}{self.test_function_name}:"
61+
f"{self.function_getting_tested}:{self.iteration_id}"
62+
)
5763

5864
@staticmethod
5965
def from_str_id(string_id: str, iteration_id: Optional[str] = None) -> InvocationId:
@@ -167,9 +173,13 @@ def report_to_tree(report: dict[TestType, dict[str, int]], title: str) -> Tree:
167173
def usable_runtime_data_by_test_case(self) -> dict[InvocationId, list[int]]:
168174
for result in self.test_results:
169175
if result.did_pass and not result.runtime:
170-
logger.debug(
171-
f"Ignoring test case that passed but had no runtime -> {result.id}, Loop # {result.loop_index}, Test Type: {result.test_type}, Verification Type: {result.verification_type}"
176+
msg = (
177+
f"Ignoring test case that passed but had no runtime -> {result.id}, "
178+
f"Loop # {result.loop_index}, Test Type: {result.test_type}, "
179+
f"Verification Type: {result.verification_type}"
172180
)
181+
logger.debug(msg)
182+
173183
usable_runtimes = [
174184
(result.id, result.runtime) for result in self.test_results if result.did_pass and result.runtime
175185
]
@@ -179,16 +189,14 @@ def usable_runtime_data_by_test_case(self) -> dict[InvocationId, list[int]]:
179189
}
180190

181191
def total_passed_runtime(self) -> int:
182-
"""Calculate the sum of runtimes of all test cases that passed, where a testcase runtime
183-
is the minimum value of all looped execution runtimes.
192+
"""Calculate the sum of runtimes of all test cases that passed.
193+
194+
A testcase runtime is the minimum value of all looped execution runtimes.
184195
185196
:return: The runtime in nanoseconds.
186197
"""
187198
return sum(
188-
[
189-
min(usable_runtime_data)
190-
for invocation_id, usable_runtime_data in self.usable_runtime_data_by_test_case().items()
191-
]
199+
[min(usable_runtime_data) for _, usable_runtime_data in self.usable_runtime_data_by_test_case().items()]
192200
)
193201

194202
def __iter__(self) -> Iterator[FunctionTestInvocation]:

codeflash/verification/test_runner.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ def run_behavioral_tests(
6060
"--codeflash_loops_scope=session",
6161
"--codeflash_min_loops=1",
6262
"--codeflash_max_loops=1",
63-
f"--codeflash_seconds={pytest_target_runtime_seconds}", # TODO : This is unnecessary, update the plugin to not ask for this
63+
f"--codeflash_seconds={pytest_target_runtime_seconds}", # TODO : This is unnecessary, update the plugin to not ask for this # noqa: E501
6464
]
6565

6666
result_file_path = get_run_tmp_file(Path("pytest_results.xml"))
@@ -87,7 +87,7 @@ def run_behavioral_tests(
8787
)
8888
logger.debug(
8989
f"Result return code: {results.returncode}"
90-
f"{', Result stderr:' + str(results.stderr) if results.stderr else ''}"
90+
+ (f", Result stderr: {results.stderr}" if results.stderr else "")
9191
)
9292
else:
9393
results = execute_test_subprocess(
@@ -98,18 +98,20 @@ def run_behavioral_tests(
9898
)
9999
logger.debug(
100100
f"Result return code: {results.returncode}"
101-
f"{', Result stderr:' + str(results.stderr) if results.stderr else ''}"
101+
+ (f", Result stderr: {results.stderr}" if results.stderr else "")
102102
)
103103
elif test_framework == "unittest":
104104
if enable_coverage:
105105
msg = "Coverage is not supported yet for unittest framework"
106106
raise ValueError(msg)
107107
test_env["CODEFLASH_LOOP_INDEX"] = "1"
108108
test_files = [file.instrumented_behavior_file_path for file in test_paths.test_files]
109-
result_file_path, results = run_unittest_tests(verbose, test_files, test_env, cwd)
109+
result_file_path, results = run_unittest_tests(
110+
verbose=verbose, test_file_paths=test_files, test_env=test_env, cwd=cwd
111+
)
110112
logger.debug(
111113
f"Result return code: {results.returncode}"
112-
f"{', Result stderr:' + str(results.stderr) if results.stderr else ''}"
114+
+ (f", Result stderr: {results.stderr}" if results.stderr else "")
113115
)
114116
else:
115117
msg = f"Unsupported test framework: {test_framework}"

tests/test_lru_cache_clear.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,12 @@
44
import pytest
55
from _pytest.config import Config
66

7-
from codeflash.verification.pytest_plugin import PyTest_Loops
7+
from codeflash.verification.pytest_plugin import PytestLoops
88

99

1010
@pytest.fixture
11-
def pytest_loops_instance(pytestconfig: Config) -> PyTest_Loops:
12-
return PyTest_Loops(pytestconfig)
11+
def pytest_loops_instance(pytestconfig: Config) -> PytestLoops:
12+
return PytestLoops(pytestconfig)
1313

1414

1515
@pytest.fixture
@@ -27,7 +27,7 @@ def create_mock_module(module_name: str, source_code: str) -> types.ModuleType:
2727
return module
2828

2929

30-
def test_clear_lru_caches_function(pytest_loops_instance: PyTest_Loops, mock_item: type) -> None:
30+
def test_clear_lru_caches_function(pytest_loops_instance: PytestLoops, mock_item: type) -> None:
3131
source_code = """
3232
import functools
3333
@@ -46,7 +46,7 @@ def my_func(x):
4646
assert mock_module.my_func.cache_info().currsize == 0
4747

4848

49-
def test_clear_lru_caches_class_method(pytest_loops_instance: PyTest_Loops, mock_item: type) -> None:
49+
def test_clear_lru_caches_class_method(pytest_loops_instance: PytestLoops, mock_item: type) -> None:
5050
source_code = """
5151
import functools
5252
@@ -67,7 +67,7 @@ def my_method(self, x):
6767
assert mock_module.MyClass.my_method.cache_info().currsize == 0
6868

6969

70-
def test_clear_lru_caches_exception_handling(pytest_loops_instance: PyTest_Loops, mock_item: type) -> None:
70+
def test_clear_lru_caches_exception_handling(pytest_loops_instance: PytestLoops, mock_item: type) -> None:
7171
"""Test that exceptions during clearing are handled."""
7272

7373
class BrokenCache:
@@ -79,7 +79,7 @@ def cache_clear(self) -> NoReturn:
7979
pytest_loops_instance._clear_lru_caches(item) # noqa: SLF001
8080

8181

82-
def test_clear_lru_caches_no_cache(pytest_loops_instance: PyTest_Loops, mock_item: type) -> None:
82+
def test_clear_lru_caches_no_cache(pytest_loops_instance: PytestLoops, mock_item: type) -> None:
8383
def no_cache_func(x: int) -> int:
8484
return x
8585

0 commit comments

Comments
 (0)