|
| 1 | +import inspect |
| 2 | +from pathlib import Path |
| 3 | +from types import SimpleNamespace |
| 4 | + |
| 5 | +import pytest |
| 6 | + |
| 7 | +from telegram_mcp.tools import media |
| 8 | + |
| 9 | +_download_media = inspect.unwrap(media.download_media) |
| 10 | + |
| 11 | + |
| 12 | +async def _call_download(monkeypatch, target, client, message): |
| 13 | + monkeypatch.setattr(media, "get_client", lambda account=None: client) |
| 14 | + |
| 15 | + async def _resolve_entity(chat_id, cl): |
| 16 | + assert cl is client |
| 17 | + return "entity" |
| 18 | + |
| 19 | + async def _resolve_path(**kwargs): |
| 20 | + raw_path = kwargs["raw_path"] |
| 21 | + return (Path(raw_path).resolve() if raw_path else target), None |
| 22 | + |
| 23 | + async def _allowed_roots(ctx, tool_name): |
| 24 | + return [target.parent], None |
| 25 | + |
| 26 | + monkeypatch.setattr(media, "resolve_entity", _resolve_entity) |
| 27 | + monkeypatch.setattr(media, "_resolve_writable_file_path", _resolve_path) |
| 28 | + monkeypatch.setattr(media, "_ensure_allowed_roots", _allowed_roots) |
| 29 | + return await _download_media(123, message.id, file_path=str(target)) |
| 30 | + |
| 31 | + |
| 32 | +async def _call_default_download(monkeypatch, root, client, message): |
| 33 | + monkeypatch.setattr(media, "get_client", lambda account=None: client) |
| 34 | + |
| 35 | + async def _resolve_entity(chat_id, cl): |
| 36 | + assert cl is client |
| 37 | + return "entity" |
| 38 | + |
| 39 | + async def _resolve_path(**kwargs): |
| 40 | + raw_path = kwargs["raw_path"] |
| 41 | + if raw_path: |
| 42 | + return Path(raw_path).resolve(), None |
| 43 | + downloads = root / "downloads" |
| 44 | + downloads.mkdir(exist_ok=True) |
| 45 | + return (downloads / kwargs["default_filename"]).resolve(), None |
| 46 | + |
| 47 | + monkeypatch.setattr(media, "resolve_entity", _resolve_entity) |
| 48 | + monkeypatch.setattr(media, "_resolve_writable_file_path", _resolve_path) |
| 49 | + return await _download_media(123, message.id) |
| 50 | + |
| 51 | + |
| 52 | +def _message(size): |
| 53 | + return SimpleNamespace(id=7, media=object(), file=SimpleNamespace(size=size)) |
| 54 | + |
| 55 | + |
| 56 | +class _Client: |
| 57 | + def __init__(self, message, download): |
| 58 | + self.message = message |
| 59 | + self._download = download |
| 60 | + self.download_calls = 0 |
| 61 | + |
| 62 | + async def get_messages(self, entity, ids): |
| 63 | + assert entity == "entity" |
| 64 | + assert ids == self.message.id |
| 65 | + return self.message |
| 66 | + |
| 67 | + async def download_media(self, message, file, **kwargs): |
| 68 | + self.download_calls += 1 |
| 69 | + return await self._download(Path(file), kwargs) |
| 70 | + |
| 71 | + |
| 72 | +@pytest.mark.asyncio |
| 73 | +async def test_default_download_paths_do_not_collide_when_time_is_frozen(tmp_path, monkeypatch): |
| 74 | + message = _message(size=3) |
| 75 | + payloads = iter((b"one", b"two")) |
| 76 | + |
| 77 | + async def successful_download(file, kwargs): |
| 78 | + downloaded = Path(f"{file}.webp") |
| 79 | + downloaded.write_bytes(next(payloads)) |
| 80 | + return str(downloaded) |
| 81 | + |
| 82 | + client = _Client(message, successful_download) |
| 83 | + monkeypatch.setattr(media.time, "time", lambda: 1_700_000_000) |
| 84 | + |
| 85 | + first = await _call_default_download(monkeypatch, tmp_path, client, message) |
| 86 | + second = await _call_default_download(monkeypatch, tmp_path, client, message) |
| 87 | + |
| 88 | + prefix = "Media downloaded to " |
| 89 | + first_path = Path(first.removeprefix(prefix).removesuffix(".")) |
| 90 | + second_path = Path(second.removeprefix(prefix).removesuffix(".")) |
| 91 | + assert first_path != second_path |
| 92 | + assert first_path.read_bytes() == b"one" |
| 93 | + assert second_path.read_bytes() == b"two" |
| 94 | + |
| 95 | + |
| 96 | +@pytest.mark.asyncio |
| 97 | +async def test_download_media_rejects_declared_oversize_before_transfer(tmp_path, monkeypatch): |
| 98 | + target = tmp_path / "large.bin" |
| 99 | + message = _message(size=5) |
| 100 | + |
| 101 | + async def fail_download(file, kwargs): |
| 102 | + raise AssertionError("download must not start") |
| 103 | + |
| 104 | + client = _Client(message, fail_download) |
| 105 | + monkeypatch.setitem(media.MAX_FILE_BYTES, "download_media", 4) |
| 106 | + |
| 107 | + result = await _call_download(monkeypatch, target, client, message) |
| 108 | + |
| 109 | + assert "too large" in result.lower() |
| 110 | + assert client.download_calls == 0 |
| 111 | + assert list(tmp_path.iterdir()) == [] |
| 112 | + |
| 113 | + |
| 114 | +@pytest.mark.asyncio |
| 115 | +async def test_download_media_aborts_in_progress_oversize_and_cleans_staging( |
| 116 | + tmp_path, monkeypatch |
| 117 | +): |
| 118 | + target = tmp_path / "bounded.bin" |
| 119 | + message = _message(size=None) |
| 120 | + |
| 121 | + async def oversized_download(file, kwargs): |
| 122 | + partial = Path(f"{file}.bin") |
| 123 | + partial.write_bytes(b"12345") |
| 124 | + kwargs["progress_callback"](5, 10) |
| 125 | + return str(partial) |
| 126 | + |
| 127 | + client = _Client(message, oversized_download) |
| 128 | + monkeypatch.setitem(media.MAX_FILE_BYTES, "download_media", 4) |
| 129 | + |
| 130 | + result = await _call_download(monkeypatch, target, client, message) |
| 131 | + |
| 132 | + assert "too large" in result.lower() |
| 133 | + assert client.download_calls == 1 |
| 134 | + assert list(tmp_path.iterdir()) == [] |
| 135 | + |
| 136 | + |
| 137 | +@pytest.mark.asyncio |
| 138 | +async def test_download_media_verifies_final_size_and_cleans_staging(tmp_path, monkeypatch): |
| 139 | + target = tmp_path / "stale-size.bin" |
| 140 | + message = _message(size=4) |
| 141 | + |
| 142 | + async def oversized_download(file, kwargs): |
| 143 | + downloaded = Path(f"{file}.bin") |
| 144 | + downloaded.write_bytes(b"12345") |
| 145 | + return str(downloaded) |
| 146 | + |
| 147 | + client = _Client(message, oversized_download) |
| 148 | + monkeypatch.setitem(media.MAX_FILE_BYTES, "download_media", 4) |
| 149 | + |
| 150 | + result = await _call_download(monkeypatch, target, client, message) |
| 151 | + |
| 152 | + assert "too large" in result.lower() |
| 153 | + assert list(tmp_path.iterdir()) == [] |
| 154 | + |
| 155 | + |
| 156 | +@pytest.mark.asyncio |
| 157 | +async def test_download_media_cleans_extension_appended_file_after_false_return( |
| 158 | + tmp_path, monkeypatch |
| 159 | +): |
| 160 | + target = tmp_path / "missing.bin" |
| 161 | + message = _message(size=3) |
| 162 | + |
| 163 | + async def failed_download(file, kwargs): |
| 164 | + Path(f"{file}.part").write_bytes(b"123") |
| 165 | + return None |
| 166 | + |
| 167 | + client = _Client(message, failed_download) |
| 168 | + monkeypatch.setitem(media.MAX_FILE_BYTES, "download_media", 4) |
| 169 | + |
| 170 | + result = await _call_download(monkeypatch, target, client, message) |
| 171 | + |
| 172 | + assert "download failed" in result.lower() |
| 173 | + assert list(tmp_path.iterdir()) == [] |
| 174 | + |
| 175 | + |
| 176 | +@pytest.mark.asyncio |
| 177 | +async def test_download_media_cleans_extension_appended_file_after_exception( |
| 178 | + tmp_path, monkeypatch |
| 179 | +): |
| 180 | + target = tmp_path / "broken.bin" |
| 181 | + message = _message(size=3) |
| 182 | + |
| 183 | + async def failed_download(file, kwargs): |
| 184 | + Path(f"{file}.part").write_bytes(b"123") |
| 185 | + raise RuntimeError("network failed") |
| 186 | + |
| 187 | + client = _Client(message, failed_download) |
| 188 | + monkeypatch.setitem(media.MAX_FILE_BYTES, "download_media", 4) |
| 189 | + |
| 190 | + result = await _call_download(monkeypatch, target, client, message) |
| 191 | + |
| 192 | + assert "error occurred" in result.lower() |
| 193 | + assert list(tmp_path.iterdir()) == [] |
| 194 | + |
| 195 | + |
| 196 | +@pytest.mark.asyncio |
| 197 | +async def test_download_media_stages_atomically_and_preserves_detected_extension( |
| 198 | + tmp_path, monkeypatch |
| 199 | +): |
| 200 | + requested = tmp_path / "photo.jpg" |
| 201 | + final_path = tmp_path / "photo.webp" |
| 202 | + final_path.write_bytes(b"old") |
| 203 | + message = _message(size=3) |
| 204 | + |
| 205 | + async def successful_download(file, kwargs): |
| 206 | + assert file != requested.with_suffix("") |
| 207 | + assert file.is_relative_to(tmp_path) |
| 208 | + assert final_path.read_bytes() == b"old" |
| 209 | + kwargs["progress_callback"](3, 3) |
| 210 | + downloaded = Path(f"{file}.webp") |
| 211 | + downloaded.write_bytes(b"new") |
| 212 | + assert final_path.read_bytes() == b"old" |
| 213 | + return str(downloaded) |
| 214 | + |
| 215 | + client = _Client(message, successful_download) |
| 216 | + monkeypatch.setitem(media.MAX_FILE_BYTES, "download_media", 4) |
| 217 | + |
| 218 | + result = await _call_download(monkeypatch, requested, client, message) |
| 219 | + |
| 220 | + assert result == f"Media downloaded to {final_path.resolve()}." |
| 221 | + assert final_path.read_bytes() == b"new" |
| 222 | + assert list(tmp_path.iterdir()) == [final_path] |
0 commit comments