|
| 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" |
0 commit comments