Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion scrap_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import requests


# Contract: download(url, filename) streams HTTP response in 8192-byte chunks, skips empty chunks, writes binary to filename, prints status, returns None; catches RequestException only (not filesystem errors).
def download(url, filename):
try:
with requests.get(url, stream=True, timeout=10) as response:
Expand Down
225 changes: 225 additions & 0 deletions tests/test_scrap_file.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
"""Boundary and contract tests for download() in scrap_file.py (Issue #7 / R25-T052)."""

import importlib
import sys
from pathlib import Path
from unittest.mock import MagicMock, patch

import pytest
import requests

REPO_ROOT = Path(__file__).resolve().parent.parent
SCRIPT_PATH = REPO_ROOT / "scrap_file.py"
EXAMPLE_URL = "https://avatars0.githubusercontent.com/u/29729380?s=400&v=4"


def _make_mock_response(chunks: list[bytes], status_error: Exception | None = None) -> MagicMock:
"""Create a context-managed mock requests.Response."""
response = MagicMock()
response.__enter__.return_value = response
response.__exit__.return_value = False
if status_error is not None:
response.raise_for_status.side_effect = status_error
else:
response.raise_for_status.return_value = None
response.iter_content.return_value = iter(chunks)
return response


@pytest.fixture
def scrap_file_module(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
"""Safely import scrap_file with mocked requests.get and an isolated working directory."""
monkeypatch.chdir(tmp_path)
if str(REPO_ROOT) not in sys.path:
sys.path.insert(0, str(REPO_ROOT))

init_response = _make_mock_response([b"init"])
with patch("requests.get", return_value=init_response):
sys.modules.pop("scrap_file", None)
module = importlib.import_module("scrap_file")
return module


def test_source_lines_establishing_boundaries() -> None:
"""Verify exact source line numbers in scrap_file.py establishing each boundary precondition."""
lines = SCRIPT_PATH.read_text(encoding="utf-8").splitlines()
assert lines[8].strip() == "def download(url, filename):"
assert lines[10].strip() == "with requests.get(url, stream=True, timeout=10) as response:"
assert "response.raise_for_status()" in lines[11]
assert lines[13].strip() == 'with open(filename, "wb") as file:'
assert lines[14].strip() == "for chunk in response.iter_content(chunk_size=8192):"
assert lines[15].strip() == "if chunk:"
assert lines[16].strip() == "file.write(chunk)"
assert lines[18].strip() == 'print(f"Successfully downloaded: {filename}")'
assert lines[20].strip() == "except requests.exceptions.RequestException as e:"
assert lines[21].strip() == 'print(f"Download failed: {e}")'
assert lines[25].strip() == f'url = "{EXAMPLE_URL}"'
assert lines[26].strip() == 'download(url, "avatar.jpg")'


def test_module_level_example_call_safe_import(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
) -> None:
"""Lines 26-27: module-level example call runs safely when requests.get and cwd are isolated."""
monkeypatch.chdir(tmp_path)
if str(REPO_ROOT) not in sys.path:
sys.path.insert(0, str(REPO_ROOT))

mock_response = _make_mock_response([b"avatar-bytes"])
with patch("requests.get", return_value=mock_response) as mock_get:
sys.modules.pop("scrap_file", None)
importlib.import_module("scrap_file")

captured = capsys.readouterr()
mock_get.assert_called_once_with(EXAMPLE_URL, stream=True, timeout=10)
mock_response.raise_for_status.assert_called_once_with()
mock_response.iter_content.assert_called_once_with(chunk_size=8192)
assert (tmp_path / "avatar.jpg").read_bytes() == b"avatar-bytes"
assert not (REPO_ROOT / "avatar.jpg").exists()
assert captured.out == "Successfully downloaded: avatar.jpg\n"


def test_smallest_successful_transfer_empty_chunks(
scrap_file_module,
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
"""Lines 11-19: empty chunk stream creates a 0-byte file, prints success, and returns None."""
mock_response = _make_mock_response([])
with patch("requests.get", return_value=mock_response) as mock_get:
result = scrap_file_module.download("https://example.com/empty.bin", "empty.bin")

captured = capsys.readouterr()
mock_get.assert_called_once_with("https://example.com/empty.bin", stream=True, timeout=10)
mock_response.raise_for_status.assert_called_once_with()
mock_response.iter_content.assert_called_once_with(chunk_size=8192)
assert result is None
assert (tmp_path / "empty.bin").read_bytes() == b""
assert captured.out == "Successfully downloaded: empty.bin\n"


def test_smallest_non_empty_transfer(
scrap_file_module,
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
"""Lines 11-19: single 1-byte chunk writes exact byte, prints success, and returns None."""
mock_response = _make_mock_response([b"A"])
with patch("requests.get", return_value=mock_response) as mock_get:
result = scrap_file_module.download("https://example.com/one.bin", "one.bin")

captured = capsys.readouterr()
mock_get.assert_called_once_with("https://example.com/one.bin", stream=True, timeout=10)
mock_response.raise_for_status.assert_called_once_with()
mock_response.iter_content.assert_called_once_with(chunk_size=8192)
assert result is None
assert (tmp_path / "one.bin").read_bytes() == b"A"
assert captured.out == "Successfully downloaded: one.bin\n"


def test_ordinary_multi_chunk_download(
scrap_file_module,
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
"""Lines 11-19: multi-chunk stream writes concatenated bytes in order and returns None."""
mock_response = _make_mock_response([b"hello ", b"world"])
with patch("requests.get", return_value=mock_response) as mock_get:
result = scrap_file_module.download("https://example.com/data.txt", "data.txt")

captured = capsys.readouterr()
mock_get.assert_called_once_with("https://example.com/data.txt", stream=True, timeout=10)
mock_response.raise_for_status.assert_called_once_with()
mock_response.iter_content.assert_called_once_with(chunk_size=8192)
assert result is None
assert (tmp_path / "data.txt").read_bytes() == b"hello world"
assert captured.out == "Successfully downloaded: data.txt\n"


def test_empty_chunk_filtering(
scrap_file_module,
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
"""Lines 15-17: `if chunk:` filters out empty chunks while writing non-empty chunks."""
mock_response = _make_mock_response([b"", b"abc", b""])
with patch("requests.get", return_value=mock_response) as mock_get:
result = scrap_file_module.download("https://example.com/filtered.bin", "filtered.bin")

captured = capsys.readouterr()
mock_get.assert_called_once_with("https://example.com/filtered.bin", stream=True, timeout=10)
mock_response.iter_content.assert_called_once_with(chunk_size=8192)
assert result is None
assert (tmp_path / "filtered.bin").read_bytes() == b"abc"
assert captured.out == "Successfully downloaded: filtered.bin\n"


def test_overwrite_existing_file(
scrap_file_module,
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
"""Line 14: `open(filename, 'wb')` truncates and overwrites existing destination file."""
target = tmp_path / "overwrite.bin"
target.write_bytes(b"old")

mock_response = _make_mock_response([b"new"])
with patch("requests.get", return_value=mock_response) as mock_get:
result = scrap_file_module.download("https://example.com/overwrite.bin", "overwrite.bin")

captured = capsys.readouterr()
mock_get.assert_called_once_with("https://example.com/overwrite.bin", stream=True, timeout=10)
mock_response.iter_content.assert_called_once_with(chunk_size=8192)
assert result is None
assert target.read_bytes() == b"new"
assert captured.out == "Successfully downloaded: overwrite.bin\n"


def test_http_error_does_not_open_destination_file(
scrap_file_module,
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
"""Lines 12, 21-22: HTTPError from raise_for_status() is caught before open() and prints failure."""
mock_response = _make_mock_response(
[b"should-not-write"],
status_error=requests.exceptions.HTTPError("404 Client Error"),
)
with (
patch("requests.get", return_value=mock_response) as mock_get,
patch("builtins.open") as mock_open_call,
):
result = scrap_file_module.download("https://example.com/missing.bin", "missing.bin")

captured = capsys.readouterr()
mock_get.assert_called_once_with("https://example.com/missing.bin", stream=True, timeout=10)
mock_response.raise_for_status.assert_called_once_with()
mock_open_call.assert_not_called()
assert not (tmp_path / "missing.bin").exists()
assert result is None
assert captured.out == "Download failed: 404 Client Error\n"


def test_timeout_error_does_not_open_destination_file(
scrap_file_module,
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
"""Lines 11, 21-22: Timeout from requests.get() is caught before open() and prints failure."""
with (
patch(
"requests.get",
side_effect=requests.exceptions.Timeout("Request timed out"),
) as mock_get,
patch("builtins.open") as mock_open_call,
):
result = scrap_file_module.download("https://example.com/slow.bin", "slow.bin")

captured = capsys.readouterr()
mock_get.assert_called_once_with("https://example.com/slow.bin", stream=True, timeout=10)
mock_open_call.assert_not_called()
assert not (tmp_path / "slow.bin").exists()
assert result is None
assert captured.out == "Download failed: Request timed out\n"
68 changes: 68 additions & 0 deletions work/R25-T052/check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
"""Focused test runner for GitHub Issue #7 (R25-T052)."""

import importlib.util
import re
import shutil
import subprocess
import sys
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parent.parent.parent
TEST_FILE = REPO_ROOT / "tests" / "test_scrap_file.py"


def build_pytest_command() -> list[str]:
"""Build the focused pytest command using the repository's documented flags."""
pytest_args = ["--tb=short", "-v", str(TEST_FILE)]
if importlib.util.find_spec("pytest") is not None and importlib.util.find_spec("requests") is not None:
return [sys.executable, "-m", "pytest", *pytest_args]

uv_path = shutil.which("uv")
if uv_path is not None:
return [
uv_path,
"run",
"--with",
"pytest",
"--with",
"requests",
"pytest",
*pytest_args,
]

raise RuntimeError("Neither pytest+requests nor uv is available to run tests.")


def main() -> int:
"""Run only the R25-T052 boundary tests and propagate pytest exit status."""
cmd = build_pytest_command()
print(f"Running command: {' '.join(cmd)}")

result = subprocess.run(
cmd,
cwd=REPO_ROOT,
capture_output=True,
text=True,
check=False,
)

if result.stdout:
print(result.stdout, end="")
if result.stderr:
print(result.stderr, file=sys.stderr, end="")

collected_match = re.search(r"collected\s+(\d+)\s+items?", result.stdout)
summary_match = re.search(r"=+\s+(.+?)\s+in\s+[\d.]+s\s+=+", result.stdout)

test_count = collected_match.group(1) if collected_match else "unknown"
summary = summary_match.group(1) if summary_match else f"exit code {result.returncode}"
print(f"Reported test count: {test_count} | Result: {summary}")

if test_count == "unknown" or int(test_count) == 0:
return 1

return result.returncode


if __name__ == "__main__":
sys.exit(main())
25 changes: 25 additions & 0 deletions work/R25-T052/expected_vs_actual.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Expected vs. Actual Evidence — GitHub Issue #7 (R25-T052)

**Target:** `scrap_file.py` (`download(url, filename)`, Lines 9–27)
**Test Suite:** `tests/test_scrap_file.py`
**Command Executed:** `python3 work/R25-T052/check.py`
**Underlying Pytest Command:** `/Users/prateeksingh/.local/bin/uv run --with pytest --with requests pytest --tb=short -v /Users/prateeksingh/Python-1/tests/test_scrap_file.py`

## Summary

- **Collected:** 9 test items
- **Result:** 9 passed in 0.28s (exit code `0`)

## Expected vs. Actual Matrix

| Test Case | Source Line(s) | Literal Input | Independent Expected Output / Behavior | Actual Observed Output / Behavior | Status |
| :--- | :--- | :--- | :--- | :--- | :--- |
| `test_source_lines_establishing_boundaries` | L9–L27 | `scrap_file.py` | Exact lines for signature, `requests.get(..., stream=True, timeout=10)`, `raise_for_status()`, `open(..., "wb")`, `iter_content(chunk_size=8192)`, `if chunk:`, prints, `except RequestException`, and example call. | All 12 line assertions matched. | PASSED |
| `test_module_level_example_call_safe_import` | L26–L27 | `url="https://avatars0.githubusercontent.com/u/29729380?s=400&v=4"`, `filename="avatar.jpg"`, chunks `[b"avatar-bytes"]` | `requests.get` called once with `stream=True, timeout=10`; `tmp_path/avatar.jpg == b"avatar-bytes"`; repo root `avatar.jpg` absent; `stdout == "Successfully downloaded: avatar.jpg\n"`. | Matched; no live network or repo write occurred. | PASSED |
| `test_smallest_successful_transfer_empty_chunks` | L11–L19 | `url="https://example.com/empty.bin"`, `filename="empty.bin"`, chunks `[]` | Return `None`; `empty.bin == b""`; `stdout == "Successfully downloaded: empty.bin\n"`. | Return `None`; `b""` written; exact stdout matched. | PASSED |
| `test_smallest_non_empty_transfer` | L11–L19 | `url="https://example.com/one.bin"`, `filename="one.bin"`, chunks `[b"A"]` | Return `None`; `one.bin == b"A"`; `stdout == "Successfully downloaded: one.bin\n"`. | Return `None`; `b"A"` written; exact stdout matched. | PASSED |
| `test_ordinary_multi_chunk_download` | L11–L19 | `url="https://example.com/data.txt"`, `filename="data.txt"`, chunks `[b"hello ", b"world"]` | Return `None`; `data.txt == b"hello world"`; `stdout == "Successfully downloaded: data.txt\n"`. | Return `None`; `b"hello world"` written; exact stdout matched. | PASSED |
| `test_empty_chunk_filtering` | L15–L17 | `url="https://example.com/filtered.bin"`, `filename="filtered.bin"`, chunks `[b"", b"abc", b""]` | Return `None`; `filtered.bin == b"abc"`; `stdout == "Successfully downloaded: filtered.bin\n"`. | Return `None`; `b"abc"` written; empty chunks skipped. | PASSED |
| `test_overwrite_existing_file` | L14 | Existing `overwrite.bin == b"old"`, chunks `[b"new"]` | Return `None`; `overwrite.bin == b"new"`; `stdout == "Successfully downloaded: overwrite.bin\n"`. | Return `None`; `b"new"` overwrote `b"old"`; exact stdout matched. | PASSED |
| `test_http_error_does_not_open_destination_file` | L12, L21–L22 | `url="https://example.com/missing.bin"`, `filename="missing.bin"`, `HTTPError("404 Client Error")` | Return `None`; `open()` not called; file not created; `stdout == "Download failed: 404 Client Error\n"`. | Return `None`; `open()` not called; exact failure stdout matched. | PASSED |
| `test_timeout_error_does_not_open_destination_file` | L11, L21–L22 | `url="https://example.com/slow.bin"`, `filename="slow.bin"`, `Timeout("Request timed out")` | Return `None`; `open()` not called; file not created; `stdout == "Download failed: Request timed out\n"`. | Return `None`; `open()` not called; exact failure stdout matched. | PASSED |
62 changes: 62 additions & 0 deletions work/R25-T052/inputs.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
{
"issue": "GitHub Issue #7 (R25-T052)",
"target_file": "scrap_file.py",
"function": "download(url, filename)",
"source_lines": {
"signature": 9,
"requests_get": 11,
"raise_for_status": 12,
"open_wb": 14,
"iter_content": 15,
"chunk_filter": 16,
"file_write": 17,
"success_print": 19,
"request_exception_handler": 21,
"failure_print": 22,
"example_url": 26,
"example_call": 27
},
"test_inputs": {
"module_level_example": {
"url": "https://avatars0.githubusercontent.com/u/29729380?s=400&v=4",
"filename": "avatar.jpg",
"chunks_utf8_or_hex": "avatar-bytes"
},
"smallest_successful_transfer": {
"url": "https://example.com/empty.bin",
"filename": "empty.bin",
"chunks": []
},
"smallest_non_empty_transfer": {
"url": "https://example.com/one.bin",
"filename": "one.bin",
"chunks": ["A"]
},
"ordinary_multi_chunk": {
"url": "https://example.com/data.txt",
"filename": "data.txt",
"chunks": ["hello ", "world"]
},
"empty_chunk_filtering": {
"url": "https://example.com/filtered.bin",
"filename": "filtered.bin",
"chunks": ["", "abc", ""]
},
"overwrite_existing_file": {
"url": "https://example.com/overwrite.bin",
"filename": "overwrite.bin",
"initial_contents": "old",
"chunks": ["new"]
},
"http_error": {
"url": "https://example.com/missing.bin",
"filename": "missing.bin",
"exception": "HTTPError('404 Client Error')"
},
"timeout_error": {
"url": "https://example.com/slow.bin",
"filename": "slow.bin",
"exception": "Timeout('Request timed out')"
}
}
}
Loading