| 1 | from __future__ import annotations |
| 2 | |
| 3 | import base64 |
| 4 | import sys |
| 5 | from pathlib import Path |
| 6 | |
| 7 | import pytest |
| 8 | |
| 9 | |
| 10 | PROJECT_ROOT = Path(__file__).resolve().parents[1] |
| 11 | if str(PROJECT_ROOT) not in sys.path: |
| 12 | sys.path.insert(0, str(PROJECT_ROOT)) |
| 13 | |
| 14 | from helpers import media_artifacts |
| 15 | |
| 16 | |
| 17 | def test_image_data_url_from_base64_compacts_and_normalizes_mime(): |
| 18 | encoded = " \n" + base64.b64encode(b"image-bytes").decode("ascii") + "\n" |
| 19 | |
| 20 | image = media_artifacts.image_data_url_from_base64( |
| 21 | encoded, |
| 22 | mime_type="IMAGE/WEBP", |
| 23 | ) |
| 24 | |
| 25 | assert image.mime == "image/webp" |
| 26 | assert image.size == 11 |
| 27 | assert image.url == "data:image/webp;base64,aW1hZ2UtYnl0ZXM=" |
| 28 | |
| 29 | |
| 30 | def test_decode_base64_payload_rejects_empty_invalid_and_oversized_data(): |
| 31 | with pytest.raises(media_artifacts.EmptyBase64Data): |
| 32 | media_artifacts.decode_base64_payload(" \n ") |
| 33 | |
| 34 | with pytest.raises(media_artifacts.InvalidBase64Data): |
| 35 | media_artifacts.decode_base64_payload("not base64") |
| 36 | |
| 37 | with pytest.raises(media_artifacts.ArtifactTooLarge) as exc_info: |
| 38 | media_artifacts.decode_base64_payload("ZmFrZQ==", max_bytes=2) |
| 39 | |
| 40 | assert exc_info.value.size == media_artifacts.estimated_base64_decoded_size("ZmFrZQ==") |
| 41 | assert exc_info.value.limit == 2 |
| 42 | |
| 43 | |
| 44 | def test_save_base64_artifact_uses_uri_filename_and_normalized_a0_path(monkeypatch, tmp_path): |
| 45 | def fake_get_abs_path(*parts): |
| 46 | return str(tmp_path.joinpath(*parts)) |
| 47 | |
| 48 | def fake_normalize_a0_path(path: str): |
| 49 | return "/a0/" + str(Path(path).relative_to(tmp_path)).replace("\\", "/") |
| 50 | |
| 51 | monkeypatch.setattr(media_artifacts.files, "get_abs_path", fake_get_abs_path) |
| 52 | monkeypatch.setattr(media_artifacts.files, "normalize_a0_path", fake_normalize_a0_path) |
| 53 | |
| 54 | artifact = media_artifacts.save_base64_artifact( |
| 55 | base64.b64encode(b"audio-bytes").decode("ascii"), |
| 56 | mime_type="audio/mpeg", |
| 57 | directory_parts=("tmp", "media-test"), |
| 58 | preferred_name="memory://venice/generated track.mp3", |
| 59 | default_filename="fallback.bin", |
| 60 | ) |
| 61 | |
| 62 | assert artifact.mime == "audio/mpeg" |
| 63 | assert artifact.size == 11 |
| 64 | assert artifact.path.startswith("/a0/tmp/media-test/generated_track_") |
| 65 | assert artifact.path.endswith(".mp3") |
| 66 | assert (tmp_path / artifact.path.removeprefix("/a0/")).read_bytes() == b"audio-bytes" |