Skip to content

Commit 1f7e8ce

Browse files
style: Fix ruff formatting issues in test files
- Add blank lines after docstrings in all test files - Break long lines to comply with line length limits - Reformat multi-line assert statements - Reformat long conditional expressions - Remove trailing blank lines All formatting issues resolved to pass ruff format checks.
1 parent ef72f87 commit 1f7e8ce

10 files changed

Lines changed: 75 additions & 63 deletions

tests/knowledge-tuning/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1 @@
11
"""Push tests for knowledge-tuning directory."""
2-

tests/knowledge-tuning/conftest.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Pytest configuration and fixtures for knowledge-tuning tests."""
2+
23
import json
34
from pathlib import Path
45

@@ -54,4 +55,3 @@ def load_notebook(path: Path) -> dict:
5455
def notebook_loader():
5556
"""Return a function to load notebook files."""
5657
return load_notebook
57-
Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1 @@
11
"""Mock utilities for knowledge-tuning tests."""
2-

tests/knowledge-tuning/mocks/transformers_mock.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Mock classes for HuggingFace transformers."""
2+
23
from unittest.mock import MagicMock
34

45

@@ -69,4 +70,3 @@ def create_mock_torch():
6970
mock_torch.cuda.is_available = MagicMock(return_value=False)
7071
mock_torch.no_grad = MagicMock()
7172
return mock_torch
72-

tests/knowledge-tuning/run_push_tests.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#!/usr/bin/env python3
22
"""Runner script for push tests targeting knowledge-tuning directory."""
3+
34
import sys
45
from pathlib import Path
56

@@ -24,9 +25,12 @@
2425
str(test_path),
2526
"-v",
2627
"--tb=short",
27-
"-n", "auto", # Use pytest-xdist for parallel execution (auto-detect workers)
28-
"--junit-xml", str(results_dir / "junit.xml"), # JUnit XML for CI integration
29-
"--html", str(results_dir / "report.html"), # HTML report
28+
"-n",
29+
"auto", # Use pytest-xdist for parallel execution (auto-detect workers)
30+
"--junit-xml",
31+
str(results_dir / "junit.xml"), # JUnit XML for CI integration
32+
"--html",
33+
str(results_dir / "report.html"), # HTML report
3034
"--self-contained-html", # Include CSS/JS in HTML file
3135
# Ensure tests run quickly - timeout handled by GitHub Actions workflow
3236
])
@@ -36,4 +40,3 @@
3640
print(f" - HTML Report: {results_dir / 'report.html'}")
3741

3842
sys.exit(exit_code)
39-

tests/knowledge-tuning/test_environment.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Tests for environment and dependency validation."""
2+
23
import pytest
34

45
# Try to import tomllib (Python 3.11+) or fall back to tomli
@@ -89,7 +90,6 @@ def test_no_obviously_deprecated_patterns(self, pyproject_files):
8990
requires_python = project.get("requires-python", "")
9091

9192
for pattern in deprecated_patterns:
92-
assert (
93-
pattern.lower() not in requires_python.lower()
94-
), f"pyproject.toml {pyproject_path} contains deprecated pattern: {pattern}"
95-
93+
assert pattern.lower() not in requires_python.lower(), (
94+
f"pyproject.toml {pyproject_path} contains deprecated pattern: {pattern}"
95+
)

tests/knowledge-tuning/test_notebook_imports.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Tests for notebook import validation."""
2+
23
import ast
34
import json
45
import tokenize
@@ -112,9 +113,10 @@ def test_no_obvious_import_errors(self, notebook_files):
112113
for _line_num, line in enumerate(lines, 1):
113114
stripped = line.strip()
114115
# Check for incomplete imports
115-
if stripped.startswith("import ") and not stripped.endswith(
116-
(";", "\\")
117-
):
116+
if stripped.startswith("import ") and not stripped.endswith((
117+
";",
118+
"\\",
119+
)):
118120
# Check if it's actually complete by trying to parse
119121
try:
120122
ast.parse(stripped)
@@ -169,7 +171,9 @@ def test_code_cells_are_tokenizable(self, notebook_files):
169171

170172
# Skip shell commands and magic commands
171173
lines = source_str.split("\n")
172-
if lines and (lines[0].strip().startswith("!") or lines[0].strip().startswith("%")):
174+
if lines and (
175+
lines[0].strip().startswith("!") or lines[0].strip().startswith("%")
176+
):
173177
continue
174178

175179
try:
@@ -179,4 +183,3 @@ def test_code_cells_are_tokenizable(self, notebook_files):
179183
pytest.fail(
180184
f"Notebook {notebook_path} cell {i} has tokenization error: {e}"
181185
)
182-

tests/knowledge-tuning/test_notebook_structure.py

Lines changed: 24 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Tests for notebook structure validation."""
2+
23
import json
34

45
import nbformat
@@ -16,9 +17,9 @@ def test_no_execution_counts(self, notebook_files):
1617

1718
for cell in nb.get("cells", []):
1819
execution_count = cell.get("execution_count")
19-
assert (
20-
execution_count is None
21-
), f"Notebook {notebook_path} has execution_count {execution_count} in cell"
20+
assert execution_count is None, (
21+
f"Notebook {notebook_path} has execution_count {execution_count} in cell"
22+
)
2223

2324
def test_no_stored_outputs(self, notebook_files):
2425
"""Test that notebooks have no stored outputs."""
@@ -28,9 +29,9 @@ def test_no_stored_outputs(self, notebook_files):
2829

2930
for i, cell in enumerate(nb.get("cells", [])):
3031
outputs = cell.get("outputs", [])
31-
assert (
32-
len(outputs) == 0
33-
), f"Notebook {notebook_path} has {len(outputs)} outputs in cell {i}"
32+
assert len(outputs) == 0, (
33+
f"Notebook {notebook_path} has {len(outputs)} outputs in cell {i}"
34+
)
3435

3536
def test_kernelspec_consistency(self, notebook_files):
3637
"""Test that all notebooks have consistent kernelspec.name."""
@@ -51,9 +52,9 @@ def test_kernelspec_consistency(self, notebook_files):
5152
# Get the first kernelspec name as the reference
5253
first_name = kernelspecs[0][1]
5354
for notebook_path, name in kernelspecs:
54-
assert (
55-
name == first_name
56-
), f"Notebook {notebook_path} has kernelspec.name '{name}', expected '{first_name}'"
55+
assert name == first_name, (
56+
f"Notebook {notebook_path} has kernelspec.name '{name}', expected '{first_name}'"
57+
)
5758

5859
def test_language_info_version_consistency(self, notebook_files):
5960
"""Test that all notebooks have consistent language_info.version."""
@@ -74,9 +75,9 @@ def test_language_info_version_consistency(self, notebook_files):
7475
# Get the first version as the reference
7576
first_version = versions[0][1]
7677
for notebook_path, version in versions:
77-
assert (
78-
version == first_version
79-
), f"Notebook {notebook_path} has language_info.version '{version}', expected '{first_version}'"
78+
assert version == first_version, (
79+
f"Notebook {notebook_path} has language_info.version '{version}', expected '{first_version}'"
80+
)
8081

8182
def test_no_environment_specific_metadata(self, notebook_files):
8283
"""Test that notebooks don't contain environment-specific metadata."""
@@ -130,9 +131,9 @@ def test_standardized_metadata_schema(self, notebook_files):
130131
first_core = first_metadata_keys & core_keys
131132
current_core = metadata_keys & core_keys
132133

133-
assert (
134-
first_core == current_core
135-
), f"Notebook {notebook_path} has different core metadata keys. Expected {first_core}, got {current_core}"
134+
assert first_core == current_core, (
135+
f"Notebook {notebook_path} has different core metadata keys. Expected {first_core}, got {current_core}"
136+
)
136137

137138
def test_required_sections_exist(self, notebook_files):
138139
"""Test that notebooks contain required sections."""
@@ -163,9 +164,9 @@ def test_required_sections_exist(self, notebook_files):
163164
keyword for keyword in required_keywords if keyword in content_lower
164165
]
165166
# At minimum, should have import or install/setup
166-
assert (
167-
len(found_keywords) > 0
168-
), f"Notebook {notebook_path} missing required sections (imports, setup, or install)"
167+
assert len(found_keywords) > 0, (
168+
f"Notebook {notebook_path} missing required sections (imports, setup, or install)"
169+
)
169170

170171
def test_cell_type_ordering(self, notebook_files):
171172
"""Test that notebooks have logical ordering of markdown and code cells."""
@@ -182,7 +183,9 @@ def test_cell_type_ordering(self, notebook_files):
182183
assert first_cell_type in [
183184
"markdown",
184185
"code",
185-
], f"Notebook {notebook_path} first cell has unexpected type: {first_cell_type}"
186+
], (
187+
f"Notebook {notebook_path} first cell has unexpected type: {first_cell_type}"
188+
)
186189

187190
def test_no_empty_cells(self, notebook_files):
188191
"""Test that notebooks have no empty cells."""
@@ -210,17 +213,12 @@ def test_notebooks_are_valid_json(self, notebook_files):
210213
with open(notebook_path, encoding="utf-8") as f:
211214
json.load(f)
212215
except json.JSONDecodeError as e:
213-
pytest.fail(
214-
f"Notebook {notebook_path} is not valid JSON: {e}"
215-
)
216+
pytest.fail(f"Notebook {notebook_path} is not valid JSON: {e}")
216217

217218
def test_notebooks_are_valid_nbformat(self, notebook_files):
218219
"""Test that all notebook files are valid nbformat."""
219220
for notebook_path in notebook_files:
220221
try:
221222
nbformat.read(str(notebook_path), as_version=4)
222223
except Exception as e:
223-
pytest.fail(
224-
f"Notebook {notebook_path} is not valid nbformat: {e}"
225-
)
226-
224+
pytest.fail(f"Notebook {notebook_path} is not valid nbformat: {e}")

tests/knowledge-tuning/test_utils.py

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Tests for utility functions in knowledge-tuning."""
2+
23
import json
34
import sys
45
from pathlib import Path
@@ -9,7 +10,9 @@
910

1011
# Add the knowledge-tuning utils to path
1112
repo_root = Path(__file__).parent.parent.parent
12-
utils_path = repo_root / "examples" / "knowledge-tuning" / "04_Knowledge_Mixing" / "utils"
13+
utils_path = (
14+
repo_root / "examples" / "knowledge-tuning" / "04_Knowledge_Mixing" / "utils"
15+
)
1316
sys.path.insert(0, str(utils_path))
1417

1518
from knowledge_utils import ( # noqa: E402
@@ -142,7 +145,11 @@ def test_json_schema_validation(self):
142145
# Check messages structure - extract from Polars Series
143146
messages_series = result["messages"]
144147
# Convert to list and get first item
145-
messages_list = messages_series.to_list() if isinstance(messages_series, pl.Series) else list(messages_series)
148+
messages_list = (
149+
messages_series.to_list()
150+
if isinstance(messages_series, pl.Series)
151+
else list(messages_series)
152+
)
146153
messages = messages_list[0]
147154
assert isinstance(messages, list)
148155
assert len(messages) >= 1
@@ -151,7 +158,11 @@ def test_json_schema_validation(self):
151158

152159
# Check metadata structure - extract from Polars Series
153160
metadata_series = result["metadata"]
154-
metadata_list = metadata_series.to_list() if isinstance(metadata_series, pl.Series) else list(metadata_series)
161+
metadata_list = (
162+
metadata_series.to_list()
163+
if isinstance(metadata_series, pl.Series)
164+
else list(metadata_series)
165+
)
155166
metadata = metadata_list[0]
156167
# Metadata should be a JSON string
157168
assert isinstance(metadata, str)
@@ -252,4 +263,3 @@ def test_tokenizer_mock_behavior(self):
252263
messages = [{"role": "user", "content": "test"}]
253264
template = tokenizer.apply_chat_template(messages, tokenize=False)
254265
assert isinstance(template, str)
255-

tests/knowledge-tuning/test_venv_build.py

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Tests for virtual environment build validation."""
2+
23
import subprocess
34
import sys
45

@@ -72,7 +73,9 @@ def test_no_gpu_specific_packages_in_required(self, pyproject_files):
7273
# We're looking for obvious cases like "torch[cuda]" or explicit GPU packages
7374
if any(keyword in dep_lower for keyword in gpu_specific_keywords):
7475
# Allow torch but flag explicit GPU extras
75-
if "torch" in dep_lower and ("cuda" in dep_lower or "gpu" in dep_lower):
76+
if "torch" in dep_lower and (
77+
"cuda" in dep_lower or "gpu" in dep_lower
78+
):
7679
# This is acceptable - torch with cuda extras is common
7780
pass
7881
elif any(
@@ -122,9 +125,9 @@ def test_requires_python_is_valid(self, pyproject_files):
122125
# Should contain version specifiers
123126
assert len(requires_python) > 0
124127
# Should start with comparison operator or version number
125-
assert requires_python[0] in ">=<~!0123456789" or requires_python.startswith(
126-
"python"
127-
)
128+
assert requires_python[
129+
0
130+
] in ">=<~!0123456789" or requires_python.startswith("python")
128131

129132
def test_venv_builds_cleanly(self, pyproject_files, repo_root):
130133
"""Test that virtual environment builds cleanly for each pyproject.toml."""
@@ -173,9 +176,7 @@ def test_venv_builds_cleanly(self, pyproject_files, repo_root):
173176
f"Timeout resolving dependencies for {pyproject_path} (exceeded 1 minute)"
174177
)
175178
except Exception as e:
176-
pytest.fail(
177-
f"Error resolving dependencies for {pyproject_path}: {e}"
178-
)
179+
pytest.fail(f"Error resolving dependencies for {pyproject_path}: {e}")
179180

180181
def test_dependencies_resolve_without_conflicts(self, pyproject_files, repo_root):
181182
"""Test that dependencies resolve without conflicts."""
@@ -215,13 +216,9 @@ def test_dependencies_resolve_without_conflicts(self, pyproject_files, repo_root
215216
# Other errors are handled by test_venv_builds_cleanly
216217

217218
except subprocess.TimeoutExpired:
218-
pytest.fail(
219-
f"Timeout resolving dependencies for {pyproject_path}"
220-
)
219+
pytest.fail(f"Timeout resolving dependencies for {pyproject_path}")
221220
except Exception as e:
222-
pytest.fail(
223-
f"Error checking dependencies for {pyproject_path}: {e}"
224-
)
221+
pytest.fail(f"Error checking dependencies for {pyproject_path}: {e}")
225222

226223
def test_modules_can_be_imported(self, pyproject_files, notebook_files, repo_root):
227224
"""Test that modules referenced by notebooks can be imported (syntax validation only)."""
@@ -270,12 +267,15 @@ def test_modules_can_be_imported(self, pyproject_files, notebook_files, repo_roo
270267
for pyproject_path in pyproject_files:
271268
# Just verify the pyproject.toml exists and is valid
272269
# The actual import validation is done in test_notebook_imports
273-
assert pyproject_path.exists(), f"pyproject.toml not found: {pyproject_path}"
270+
assert pyproject_path.exists(), (
271+
f"pyproject.toml not found: {pyproject_path}"
272+
)
274273

275274
# Verify dependencies are listed (basic check)
276275
with open(pyproject_path, "rb") as f:
277276
data = tomllib.load(f)
278277
project = data.get("project", {})
279278
dependencies = project.get("dependencies", [])
280-
assert isinstance(dependencies, list), f"Invalid dependencies in {pyproject_path}"
281-
279+
assert isinstance(dependencies, list), (
280+
f"Invalid dependencies in {pyproject_path}"
281+
)

0 commit comments

Comments
 (0)