Repository navigation
fix: resolve compute_sha256 signature mismatch in test_util.py - #28
Conversation
WalkthroughThis PR updates test invocations of Changes
Estimated code review effort🎯 2 (Simple) | ⏱️ ~5 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Tip Try Coding Plans. Let us write the prompt for your AI agent so you can ship faster (with fewer bugs). Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@test_manifest_demo.py`:
- Around line 6-37: Convert this module-level demo into a proper pytest test by
wrapping the logic in a function named like
test_generate_manifest_using_temp_files and using pytest's tmp_path (or tempfile
fixture) instead of creating module-level NamedTemporaryFile; call
generate_manifest(raw_path, processed_path) inside the test, assert expected
keys/values in the loaded manifest instead of printing, and ensure manifest_path
is defined before the try/finally (or remove finally and rely on tmp_path for
cleanup) so the cleanup cannot reference an undefined variable; reference
generate_manifest and manifest_path to locate the code to change.
| # Create test files | ||
| with tempfile.NamedTemporaryFile(mode='w', suffix='.xml', delete=False) as f: | ||
| f.write('<test>data</test>') | ||
| raw_path = f.name | ||
|
|
||
| with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f: | ||
| f.write('{"processed": "data"}') | ||
| processed_path = f.name | ||
|
|
||
| try: | ||
| generate_manifest(raw_path, processed_path) | ||
|
|
||
| # Read and display manifest | ||
| manifest_path = Path.cwd() / 'data' / 'dataset_manifest.json' | ||
| with open(manifest_path) as f: | ||
| manifest = json.load(f) | ||
|
|
||
| print('🎯 COMPLETE MANIFEST STRUCTURE:') | ||
| print('=' * 50) | ||
| for key, value in manifest.items(): | ||
| if key == 'environment': | ||
| print(f'✅ {key}: {{9 environment fields captured}}') | ||
| elif key == 'environment_hash': | ||
| print(f'✅ {key}: {value[:16]}...') | ||
| else: | ||
| print(f'✅ {key}: {value}') | ||
|
|
||
| finally: | ||
| # Cleanup | ||
| Path(raw_path).unlink(missing_ok=True) | ||
| Path(processed_path).unlink(missing_ok=True) | ||
| Path(manifest_path).unlink(missing_ok=True) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
fd test_manifest_demo.py --exec cat -n {}Repository: AOSSIE-Org/OpenVerifiableLLM
Length of output: 1484
🏁 Script executed:
#!/bin/bash
set -euo pipefail
fd test_manifest_demo.py --exec sh -c '
file="$1"
echo "== Inspecting $file =="
echo "-- pytest-discoverable tests --"
rg -n "^(def test_|class Test)" "$file" || echo "No pytest test function/class found"
echo "-- top-level executable blocks --"
python - "$file" <<'"'"'PY'"'"'
import ast, sys, pathlib
p = pathlib.Path(sys.argv[1])
tree = ast.parse(p.read_text(encoding="utf-8"))
blocks = [n for n in tree.body if isinstance(n, (ast.With, ast.Try, ast.For, ast.While, ast.If))]
print([(type(n).__name__, n.lineno) for n in blocks])
PY
' sh {}Repository: AOSSIE-Org/OpenVerifiableLLM
Length of output: 255
🏁 Script executed:
fd test_manifest_demo.py --exec python - {} <<'VERIFY_PY'
import ast, sys, pathlib
file_path = sys.argv[1]
content = pathlib.Path(file_path).read_text(encoding="utf-8")
tree = ast.parse(content)
print(f"=== Analysis of {file_path} ===\n")
# Check for imports
imports = [n for n in ast.walk(tree) if isinstance(n, (ast.Import, ast.ImportFrom))]
print(f"Imports found: {len(imports)}")
for imp in imports:
if isinstance(imp, ast.Import):
for name in imp.names:
print(f" - import {name.name}")
elif isinstance(imp, ast.ImportFrom):
module = imp.module or ""
for name in imp.names:
print(f" - from {module} import {name.name}")
# Check for test functions
test_funcs = [n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name.startswith('test_')]
print(f"\nTest functions: {len(test_funcs)}")
for func in test_funcs:
print(f" - {func.name}() at line {func.lineno}")
# Check for top-level blocks
blocks = [n for n in tree.body if isinstance(n, (ast.With, ast.Try, ast.For, ast.While, ast.If))]
print(f"\nTop-level executable blocks: {len(blocks)}")
for block in blocks:
print(f" - {type(block).__name__} at line {block.lineno}")
# Check for unbound variable risk in finally
try_stmts = [n for n in tree.body if isinstance(n, ast.Try)]
print(f"\nTry blocks: {len(try_stmts)}")
for try_stmt in try_stmts:
print(f" Try block at line {try_stmt.lineno}")
# Find assigned variables in try body
assigned_in_try = set()
for node in ast.walk(ast.Module(body=try_stmt.body)):
if isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name):
assigned_in_try.add(target.id)
print(f" Variables assigned in try: {assigned_in_try}")
# Find variables used in finally
used_in_finally = set()
for node in ast.walk(ast.Module(body=try_stmt.finalbody)):
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load):
used_in_finally.add(node.id)
print(f" Variables used in finally: {used_in_finally}")
unbound = used_in_finally - assigned_in_try
if unbound:
print(f" ⚠️ Potentially unbound in finally: {unbound}")
VERIFY_PYRepository: AOSSIE-Org/OpenVerifiableLLM
Length of output: 54
Convert this module-level demo script into a pytest test function.
This file executes at import time (lines 7, 11, 15) with no def test_* function and only print statements instead of assertions. Additionally, manifest_path (line 37) is assigned only inside the try block (line 19); if generate_manifest() raises an exception before that, the finally block will encounter an undefined variable.
✅ Proposed refactor
-import tempfile
import json
-from pathlib import Path
from openverifiablellm.utils import generate_manifest
-# Create test files
-with tempfile.NamedTemporaryFile(mode='w', suffix='.xml', delete=False) as f:
- f.write('<test>data</test>')
- raw_path = f.name
-
-with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
- f.write('{"processed": "data"}')
- processed_path = f.name
-
-try:
- generate_manifest(raw_path, processed_path)
-
- # Read and display manifest
- manifest_path = Path.cwd() / 'data' / 'dataset_manifest.json'
- with open(manifest_path) as f:
- manifest = json.load(f)
-
- print('🎯 COMPLETE MANIFEST STRUCTURE:')
- print('=' * 50)
- for key, value in manifest.items():
- if key == 'environment':
- print(f'✅ {key}: {{9 environment fields captured}}')
- elif key == 'environment_hash':
- print(f'✅ {key}: {value[:16]}...')
- else:
- print(f'✅ {key}: {value}')
-
-finally:
- # Cleanup
- Path(raw_path).unlink(missing_ok=True)
- Path(processed_path).unlink(missing_ok=True)
- Path(manifest_path).unlink(missing_ok=True)
+def test_generate_manifest_demo(tmp_path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+
+ raw_path = tmp_path / "raw.xml"
+ processed_path = tmp_path / "processed.json"
+ raw_path.write_text("<test>data</test>", encoding="utf-8")
+ processed_path.write_text('{"processed": "data"}', encoding="utf-8")
+
+ generate_manifest(raw_path, processed_path)
+
+ manifest_path = tmp_path / "data" / "dataset_manifest.json"
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
+
+ assert manifest_path.exists()
+ assert "raw_sha256" in manifest
+ assert "processed_sha256" in manifest
+ assert "raw_merkle_root" in manifest
+ assert "processed_merkle_root" in manifest
+ assert "chunk_size_bytes" in manifest🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@test_manifest_demo.py` around lines 6 - 37, Convert this module-level demo
into a proper pytest test by wrapping the logic in a function named like
test_generate_manifest_using_temp_files and using pytest's tmp_path (or tempfile
fixture) instead of creating module-level NamedTemporaryFile; call
generate_manifest(raw_path, processed_path) inside the test, assert expected
keys/values in the loaded manifest instead of printing, and ensure manifest_path
is defined before the try/finally (or remove finally and rely on tmp_path for
cleanup) so the cleanup cannot reference an undefined variable; reference
generate_manifest and manifest_path to locate the code to change.
8c8eacd to
3b253f1
Compare
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
tests/test_util.py (1)
70-100: 🧹 Nitpick | 🔵 TrivialAdd regression tests for the
compute_sha256contract.Please add explicit tests for (1) positional-argument rejection and (2) the “exactly one of
data/file_path” rule, so this contract is protected going forward.Proposed test additions
# --------------- compute_sha256 ------------------------------------ @@ def test_file_not_found(): with pytest.raises(FileNotFoundError): - # FIX: use file_path= keyword argument utils.compute_sha256(file_path="non_existent_file.txt") + +def test_compute_sha256_rejects_positional_argument(tmp_path): + file = tmp_path / "sample.txt" + file.write_text("abc", encoding="utf-8") + with pytest.raises(TypeError): + utils.compute_sha256(str(file)) + +def test_compute_sha256_requires_exactly_one_input(tmp_path): + file = tmp_path / "sample.txt" + file.write_text("abc", encoding="utf-8") + with pytest.raises(ValueError): + utils.compute_sha256() + with pytest.raises(ValueError): + utils.compute_sha256(data=b"abc", file_path=file)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tests/test_util.py` around lines 70 - 100, Add regression tests for compute_sha256 to enforce its API: (1) assert that calling compute_sha256 with a positional argument raises a TypeError (so positional-argument usage is rejected), and (2) assert that passing both data and file_path together raises a ValueError (or the specific exception the function uses) to enforce the “exactly one of data/file_path” rule; update tests in test_correct_sha256_output/test_different_content_different_hash/test_file_not_found area to include two new test functions that call compute_sha256 (referencing the compute_sha256 symbol) and check these two failure modes explicitly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Outside diff comments:
In `@tests/test_util.py`:
- Around line 70-100: Add regression tests for compute_sha256 to enforce its
API: (1) assert that calling compute_sha256 with a positional argument raises a
TypeError (so positional-argument usage is rejected), and (2) assert that
passing both data and file_path together raises a ValueError (or the specific
exception the function uses) to enforce the “exactly one of data/file_path”
rule; update tests in
test_correct_sha256_output/test_different_content_different_hash/test_file_not_found
area to include two new test functions that call compute_sha256 (referencing the
compute_sha256 symbol) and check these two failure modes explicitly.
Addressed Issues:
Fixes #21
Summary
Fixes #[issue number] — Three tests in tests/test_util.py were failing with TypeError because utils.compute_sha256() is defined with keyword-only arguments (*) but the tests were calling it with positional arguments.
Root Cause
compute_sha256() in utils.py is defined as:
pythondef compute_sha256(*, data=None, file_path=None) -> str:
The * enforces keyword-only arguments, but the tests were calling it positionally:
Fix
Updated all 3 failing calls to use the file_path= keyword argument:
Test Results
Before fix:
After fix:
Why This is the Efficient Fix
The fix is on the test side, not the source code side — and that's intentional.
Checklist
We encourage contributors to use AI tools responsibly when creating Pull Requests. While AI can be a valuable aid, it is essential to ensure that your contributions meet the task requirements, build successfully, include relevant tests, and pass all linters. Submissions that do not meet these standards may be closed without warning to maintain the quality and integrity of the project. Please take the time to understand the changes you are proposing and their impact.
Summary by CodeRabbit