Skip to content

Commit ee2d914

Browse files
Merge pull request #3243 from itspratik-13/R25-T052-clean
test: define download boundary contract (R25-T052)
2 parents be476aa + abbfad8 commit ee2d914

6 files changed

Lines changed: 390 additions & 1 deletion

File tree

‎scrap_file.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
import requests
77

8-
8+
# 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).
99
def download(url, filename):
1010
try:
1111
with requests.get(url, stream=True, timeout=10) as response:

‎tests/test_scrap_file.py‎

Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
1+
"""Boundary and contract tests for download() in scrap_file.py (Issue #7 / R25-T052)."""
2+
3+
import importlib
4+
import sys
5+
from pathlib import Path
6+
from unittest.mock import MagicMock, patch
7+
8+
import pytest
9+
import requests
10+
11+
REPO_ROOT = Path(__file__).resolve().parent.parent
12+
SCRIPT_PATH = REPO_ROOT / "scrap_file.py"
13+
EXAMPLE_URL = "https://avatars0.githubusercontent.com/u/29729380?s=400&v=4"
14+
15+
16+
def _make_mock_response(chunks: list[bytes], status_error: Exception | None = None) -> MagicMock:
17+
"""Create a context-managed mock requests.Response."""
18+
response = MagicMock()
19+
response.__enter__.return_value = response
20+
response.__exit__.return_value = False
21+
if status_error is not None:
22+
response.raise_for_status.side_effect = status_error
23+
else:
24+
response.raise_for_status.return_value = None
25+
response.iter_content.return_value = iter(chunks)
26+
return response
27+
28+
29+
@pytest.fixture
30+
def scrap_file_module(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
31+
"""Safely import scrap_file with mocked requests.get and an isolated working directory."""
32+
monkeypatch.chdir(tmp_path)
33+
if str(REPO_ROOT) not in sys.path:
34+
sys.path.insert(0, str(REPO_ROOT))
35+
36+
init_response = _make_mock_response([b"init"])
37+
with patch("requests.get", return_value=init_response):
38+
sys.modules.pop("scrap_file", None)
39+
module = importlib.import_module("scrap_file")
40+
return module
41+
42+
43+
def test_source_lines_establishing_boundaries() -> None:
44+
"""Verify exact source line numbers in scrap_file.py establishing each boundary precondition."""
45+
lines = SCRIPT_PATH.read_text(encoding="utf-8").splitlines()
46+
assert lines[8].strip() == "def download(url, filename):"
47+
assert lines[10].strip() == "with requests.get(url, stream=True, timeout=10) as response:"
48+
assert "response.raise_for_status()" in lines[11]
49+
assert lines[13].strip() == 'with open(filename, "wb") as file:'
50+
assert lines[14].strip() == "for chunk in response.iter_content(chunk_size=8192):"
51+
assert lines[15].strip() == "if chunk:"
52+
assert lines[16].strip() == "file.write(chunk)"
53+
assert lines[18].strip() == 'print(f"Successfully downloaded: {filename}")'
54+
assert lines[20].strip() == "except requests.exceptions.RequestException as e:"
55+
assert lines[21].strip() == 'print(f"Download failed: {e}")'
56+
assert lines[25].strip() == f'url = "{EXAMPLE_URL}"'
57+
assert lines[26].strip() == 'download(url, "avatar.jpg")'
58+
59+
60+
def test_module_level_example_call_safe_import(
61+
tmp_path: Path,
62+
monkeypatch: pytest.MonkeyPatch,
63+
capsys: pytest.CaptureFixture[str],
64+
) -> None:
65+
"""Lines 26-27: module-level example call runs safely when requests.get and cwd are isolated."""
66+
monkeypatch.chdir(tmp_path)
67+
if str(REPO_ROOT) not in sys.path:
68+
sys.path.insert(0, str(REPO_ROOT))
69+
70+
mock_response = _make_mock_response([b"avatar-bytes"])
71+
with patch("requests.get", return_value=mock_response) as mock_get:
72+
sys.modules.pop("scrap_file", None)
73+
importlib.import_module("scrap_file")
74+
75+
captured = capsys.readouterr()
76+
mock_get.assert_called_once_with(EXAMPLE_URL, stream=True, timeout=10)
77+
mock_response.raise_for_status.assert_called_once_with()
78+
mock_response.iter_content.assert_called_once_with(chunk_size=8192)
79+
assert (tmp_path / "avatar.jpg").read_bytes() == b"avatar-bytes"
80+
assert not (REPO_ROOT / "avatar.jpg").exists()
81+
assert captured.out == "Successfully downloaded: avatar.jpg\n"
82+
83+
84+
def test_smallest_successful_transfer_empty_chunks(
85+
scrap_file_module,
86+
tmp_path: Path,
87+
capsys: pytest.CaptureFixture[str],
88+
) -> None:
89+
"""Lines 11-19: empty chunk stream creates a 0-byte file, prints success, and returns None."""
90+
mock_response = _make_mock_response([])
91+
with patch("requests.get", return_value=mock_response) as mock_get:
92+
result = scrap_file_module.download("https://example.com/empty.bin", "empty.bin")
93+
94+
captured = capsys.readouterr()
95+
mock_get.assert_called_once_with("https://example.com/empty.bin", stream=True, timeout=10)
96+
mock_response.raise_for_status.assert_called_once_with()
97+
mock_response.iter_content.assert_called_once_with(chunk_size=8192)
98+
assert result is None
99+
assert (tmp_path / "empty.bin").read_bytes() == b""
100+
assert captured.out == "Successfully downloaded: empty.bin\n"
101+
102+
103+
def test_smallest_non_empty_transfer(
104+
scrap_file_module,
105+
tmp_path: Path,
106+
capsys: pytest.CaptureFixture[str],
107+
) -> None:
108+
"""Lines 11-19: single 1-byte chunk writes exact byte, prints success, and returns None."""
109+
mock_response = _make_mock_response([b"A"])
110+
with patch("requests.get", return_value=mock_response) as mock_get:
111+
result = scrap_file_module.download("https://example.com/one.bin", "one.bin")
112+
113+
captured = capsys.readouterr()
114+
mock_get.assert_called_once_with("https://example.com/one.bin", stream=True, timeout=10)
115+
mock_response.raise_for_status.assert_called_once_with()
116+
mock_response.iter_content.assert_called_once_with(chunk_size=8192)
117+
assert result is None
118+
assert (tmp_path / "one.bin").read_bytes() == b"A"
119+
assert captured.out == "Successfully downloaded: one.bin\n"
120+
121+
122+
def test_ordinary_multi_chunk_download(
123+
scrap_file_module,
124+
tmp_path: Path,
125+
capsys: pytest.CaptureFixture[str],
126+
) -> None:
127+
"""Lines 11-19: multi-chunk stream writes concatenated bytes in order and returns None."""
128+
mock_response = _make_mock_response([b"hello ", b"world"])
129+
with patch("requests.get", return_value=mock_response) as mock_get:
130+
result = scrap_file_module.download("https://example.com/data.txt", "data.txt")
131+
132+
captured = capsys.readouterr()
133+
mock_get.assert_called_once_with("https://example.com/data.txt", stream=True, timeout=10)
134+
mock_response.raise_for_status.assert_called_once_with()
135+
mock_response.iter_content.assert_called_once_with(chunk_size=8192)
136+
assert result is None
137+
assert (tmp_path / "data.txt").read_bytes() == b"hello world"
138+
assert captured.out == "Successfully downloaded: data.txt\n"
139+
140+
141+
def test_empty_chunk_filtering(
142+
scrap_file_module,
143+
tmp_path: Path,
144+
capsys: pytest.CaptureFixture[str],
145+
) -> None:
146+
"""Lines 15-17: `if chunk:` filters out empty chunks while writing non-empty chunks."""
147+
mock_response = _make_mock_response([b"", b"abc", b""])
148+
with patch("requests.get", return_value=mock_response) as mock_get:
149+
result = scrap_file_module.download("https://example.com/filtered.bin", "filtered.bin")
150+
151+
captured = capsys.readouterr()
152+
mock_get.assert_called_once_with("https://example.com/filtered.bin", stream=True, timeout=10)
153+
mock_response.iter_content.assert_called_once_with(chunk_size=8192)
154+
assert result is None
155+
assert (tmp_path / "filtered.bin").read_bytes() == b"abc"
156+
assert captured.out == "Successfully downloaded: filtered.bin\n"
157+
158+
159+
def test_overwrite_existing_file(
160+
scrap_file_module,
161+
tmp_path: Path,
162+
capsys: pytest.CaptureFixture[str],
163+
) -> None:
164+
"""Line 14: `open(filename, 'wb')` truncates and overwrites existing destination file."""
165+
target = tmp_path / "overwrite.bin"
166+
target.write_bytes(b"old")
167+
168+
mock_response = _make_mock_response([b"new"])
169+
with patch("requests.get", return_value=mock_response) as mock_get:
170+
result = scrap_file_module.download("https://example.com/overwrite.bin", "overwrite.bin")
171+
172+
captured = capsys.readouterr()
173+
mock_get.assert_called_once_with("https://example.com/overwrite.bin", stream=True, timeout=10)
174+
mock_response.iter_content.assert_called_once_with(chunk_size=8192)
175+
assert result is None
176+
assert target.read_bytes() == b"new"
177+
assert captured.out == "Successfully downloaded: overwrite.bin\n"
178+
179+
180+
def test_http_error_does_not_open_destination_file(
181+
scrap_file_module,
182+
tmp_path: Path,
183+
capsys: pytest.CaptureFixture[str],
184+
) -> None:
185+
"""Lines 12, 21-22: HTTPError from raise_for_status() is caught before open() and prints failure."""
186+
mock_response = _make_mock_response(
187+
[b"should-not-write"],
188+
status_error=requests.exceptions.HTTPError("404 Client Error"),
189+
)
190+
with (
191+
patch("requests.get", return_value=mock_response) as mock_get,
192+
patch("builtins.open") as mock_open_call,
193+
):
194+
result = scrap_file_module.download("https://example.com/missing.bin", "missing.bin")
195+
196+
captured = capsys.readouterr()
197+
mock_get.assert_called_once_with("https://example.com/missing.bin", stream=True, timeout=10)
198+
mock_response.raise_for_status.assert_called_once_with()
199+
mock_open_call.assert_not_called()
200+
assert not (tmp_path / "missing.bin").exists()
201+
assert result is None
202+
assert captured.out == "Download failed: 404 Client Error\n"
203+
204+
205+
def test_timeout_error_does_not_open_destination_file(
206+
scrap_file_module,
207+
tmp_path: Path,
208+
capsys: pytest.CaptureFixture[str],
209+
) -> None:
210+
"""Lines 11, 21-22: Timeout from requests.get() is caught before open() and prints failure."""
211+
with (
212+
patch(
213+
"requests.get",
214+
side_effect=requests.exceptions.Timeout("Request timed out"),
215+
) as mock_get,
216+
patch("builtins.open") as mock_open_call,
217+
):
218+
result = scrap_file_module.download("https://example.com/slow.bin", "slow.bin")
219+
220+
captured = capsys.readouterr()
221+
mock_get.assert_called_once_with("https://example.com/slow.bin", stream=True, timeout=10)
222+
mock_open_call.assert_not_called()
223+
assert not (tmp_path / "slow.bin").exists()
224+
assert result is None
225+
assert captured.out == "Download failed: Request timed out\n"

‎work/R25-T052/check.py‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
"""Focused test runner for GitHub Issue #7 (R25-T052)."""
2+
3+
import importlib.util
4+
import re
5+
import shutil
6+
import subprocess
7+
import sys
8+
from pathlib import Path
9+
10+
REPO_ROOT = Path(__file__).resolve().parent.parent.parent
11+
TEST_FILE = REPO_ROOT / "tests" / "test_scrap_file.py"
12+
13+
14+
def build_pytest_command() -> list[str]:
15+
"""Build the focused pytest command using the repository's documented flags."""
16+
pytest_args = ["--tb=short", "-v", str(TEST_FILE)]
17+
if importlib.util.find_spec("pytest") is not None and importlib.util.find_spec("requests") is not None:
18+
return [sys.executable, "-m", "pytest", *pytest_args]
19+
20+
uv_path = shutil.which("uv")
21+
if uv_path is not None:
22+
return [
23+
uv_path,
24+
"run",
25+
"--with",
26+
"pytest",
27+
"--with",
28+
"requests",
29+
"pytest",
30+
*pytest_args,
31+
]
32+
33+
raise RuntimeError("Neither pytest+requests nor uv is available to run tests.")
34+
35+
36+
def main() -> int:
37+
"""Run only the R25-T052 boundary tests and propagate pytest exit status."""
38+
cmd = build_pytest_command()
39+
print(f"Running command: {' '.join(cmd)}")
40+
41+
result = subprocess.run(
42+
cmd,
43+
cwd=REPO_ROOT,
44+
capture_output=True,
45+
text=True,
46+
check=False,
47+
)
48+
49+
if result.stdout:
50+
print(result.stdout, end="")
51+
if result.stderr:
52+
print(result.stderr, file=sys.stderr, end="")
53+
54+
collected_match = re.search(r"collected\s+(\d+)\s+items?", result.stdout)
55+
summary_match = re.search(r"=+\s+(.+?)\s+in\s+[\d.]+s\s+=+", result.stdout)
56+
57+
test_count = collected_match.group(1) if collected_match else "unknown"
58+
summary = summary_match.group(1) if summary_match else f"exit code {result.returncode}"
59+
print(f"Reported test count: {test_count} | Result: {summary}")
60+
61+
if test_count == "unknown" or int(test_count) == 0:
62+
return 1
63+
64+
return result.returncode
65+
66+
67+
if __name__ == "__main__":
68+
sys.exit(main())
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Expected vs. Actual Evidence — GitHub Issue #7 (R25-T052)
2+
3+
**Target:** `scrap_file.py` (`download(url, filename)`, Lines 9–27)
4+
**Test Suite:** `tests/test_scrap_file.py`
5+
**Command Executed:** `python3 work/R25-T052/check.py`
6+
**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`
7+
8+
## Summary
9+
10+
- **Collected:** 9 test items
11+
- **Result:** 9 passed in 0.28s (exit code `0`)
12+
13+
## Expected vs. Actual Matrix
14+
15+
| Test Case | Source Line(s) | Literal Input | Independent Expected Output / Behavior | Actual Observed Output / Behavior | Status |
16+
| :--- | :--- | :--- | :--- | :--- | :--- |
17+
| `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 |
18+
| `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 |
19+
| `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 |
20+
| `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 |
21+
| `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 |
22+
| `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 |
23+
| `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 |
24+
| `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 |
25+
| `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 |

‎work/R25-T052/inputs.json‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
{
2+
"issue": "GitHub Issue #7 (R25-T052)",
3+
"target_file": "scrap_file.py",
4+
"function": "download(url, filename)",
5+
"source_lines": {
6+
"signature": 9,
7+
"requests_get": 11,
8+
"raise_for_status": 12,
9+
"open_wb": 14,
10+
"iter_content": 15,
11+
"chunk_filter": 16,
12+
"file_write": 17,
13+
"success_print": 19,
14+
"request_exception_handler": 21,
15+
"failure_print": 22,
16+
"example_url": 26,
17+
"example_call": 27
18+
},
19+
"test_inputs": {
20+
"module_level_example": {
21+
"url": "https://avatars0.githubusercontent.com/u/29729380?s=400&v=4",
22+
"filename": "avatar.jpg",
23+
"chunks_utf8_or_hex": "avatar-bytes"
24+
},
25+
"smallest_successful_transfer": {
26+
"url": "https://example.com/empty.bin",
27+
"filename": "empty.bin",
28+
"chunks": []
29+
},
30+
"smallest_non_empty_transfer": {
31+
"url": "https://example.com/one.bin",
32+
"filename": "one.bin",
33+
"chunks": ["A"]
34+
},
35+
"ordinary_multi_chunk": {
36+
"url": "https://example.com/data.txt",
37+
"filename": "data.txt",
38+
"chunks": ["hello ", "world"]
39+
},
40+
"empty_chunk_filtering": {
41+
"url": "https://example.com/filtered.bin",
42+
"filename": "filtered.bin",
43+
"chunks": ["", "abc", ""]
44+
},
45+
"overwrite_existing_file": {
46+
"url": "https://example.com/overwrite.bin",
47+
"filename": "overwrite.bin",
48+
"initial_contents": "old",
49+
"chunks": ["new"]
50+
},
51+
"http_error": {
52+
"url": "https://example.com/missing.bin",
53+
"filename": "missing.bin",
54+
"exception": "HTTPError('404 Client Error')"
55+
},
56+
"timeout_error": {
57+
"url": "https://example.com/slow.bin",
58+
"filename": "slow.bin",
59+
"exception": "Timeout('Request timed out')"
60+
}
61+
}
62+
}

0 commit comments

Comments
 (0)