Skip to content

fix: resolve compute_sha256 signature mismatch in test_util.py - #28

Merged
Archit381 merged 1 commit into
AOSSIE-Org:mainfrom
Arpitsh7:fix/compute-sha256-signature-mismatch
Mar 5, 2026
Merged

Archit381 merged 1 commit into
AOSSIE-Org:mainfrom
Arpitsh7:fix/compute-sha256-signature-mismatch

Conversation

@Arpitsh7

@Arpitsh7 Arpitsh7 commented Mar 2, 2026 •

Copy link
Copy Markdown
Contributor

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:

FAILED tests/test_util.py::test_correct_sha256_output
FAILED tests/test_util.py::test_different_content_different_hash
FAILED tests/test_util.py::test_file_not_found
3 failed, 20 passed

After fix:

23 passed

Why This is the Efficient Fix

The fix is on the test side, not the source code side — and that's intentional.

  • compute_sha256() in utils.py is correctly designed with * keyword-only arguments because:
  • It prevents accidentally passing data when you meant file_path or vice versa
  • It makes the call explicit and readable — you always know what you're passing

Checklist

  • My code follows the project's code style and conventions
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings or errors
  • I have joined the Discord server and I will share a link to this PR with the project maintainers there
  • I have read the Contributing Guidelines

⚠️ AI Notice - Important!

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

  • Tests
    • Updated test suite to use keyword arguments for better code clarity and maintainability.

@coderabbitai

coderabbitai Bot commented Mar 2, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

This PR updates test invocations of compute_sha256 to use the explicit keyword argument file_path= instead of positional argument syntax. All function calls are refactored consistently; no logic changes or runtime behavior modifications are introduced.

Changes

Cohort / File(s) Summary
Test Argument Refactoring
tests/test_util.py
Updated all compute_sha256 function calls to use keyword argument syntax (file_path=...) instead of positional arguments. Includes minor whitespace adjustments.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~5 minutes

Possibly related PRs

Suggested labels

Python Lang

Suggested reviewers

  • Archit381

Poem

🐰 A test refactor, simple and clean,
Keywords now explicit, perfectly seen,
No logic changed, just calls made bright,
Arguments named—everything right!
file_path= now leads the way,
Better clarity saves the day! ✨

🚥 Pre-merge checks | ✅ 2
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: fixing a compute_sha256 signature mismatch in tests by updating function calls to use keyword arguments.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

Try Coding Plans. Let us write the prompt for your AI agent so you can ship faster (with fewer bugs).
Share your feedback on Discord.


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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions github-actions Bot added size/M and removed size/M labels Mar 2, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3b253f1 and 8c8eacd.

📒 Files selected for processing (2)
  • test_manifest_demo.py
  • tests/test_util.py

Comment thread test_manifest_demo.py Outdated
Comment on lines +6 to +37
# 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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 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_PY

Repository: 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.

@Arpitsh7 Arpitsh7 closed this Mar 2, 2026
@Arpitsh7
Arpitsh7 force-pushed the fix/compute-sha256-signature-mismatch branch from 8c8eacd to 3b253f1 Compare March 2, 2026 20:02
@github-actions github-actions Bot added size/XS and removed size/M labels Mar 2, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 | 🔵 Trivial

Add regression tests for the compute_sha256 contract.

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.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8c8eacd and 9f7fa00.

📒 Files selected for processing (1)
  • tests/test_util.py

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] test_util.py fails due to signature mismatch

2 participants