mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-03 06:25:10 +00:00
61 lines
2.1 KiB
Python
61 lines
2.1 KiB
Python
"""An attachment with no given MIME type takes it from the file signature before the suffix."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import importlib
|
|
from collections.abc import Iterator
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
from unshackle.core.config import config
|
|
from unshackle.core.tracks.attachment import Attachment
|
|
|
|
downloader = importlib.import_module("unshackle.core.downloaders.requests")
|
|
PNG = b"\x89PNG\r\n\x1a\n" + bytes(32)
|
|
JPEG = b"\xff\xd8\xff\xe0" + bytes(32)
|
|
|
|
|
|
def test_a_png_saved_as_jpg_is_image_png(tmp_path: Path) -> None:
|
|
path = tmp_path / "thumb.jpg"
|
|
path.write_bytes(PNG)
|
|
assert Attachment(path=path).mime_type == "image/png"
|
|
|
|
|
|
def test_an_unknown_signature_falls_back_to_the_suffix(tmp_path: Path) -> None:
|
|
path = tmp_path / "font.ttf"
|
|
path.write_bytes(b"junk" * 8)
|
|
assert Attachment(path=path).mime_type == "application/x-truetype-font"
|
|
|
|
|
|
def test_a_given_mime_type_stays(tmp_path: Path) -> None:
|
|
path = tmp_path / "thumb.jpg"
|
|
path.write_bytes(PNG)
|
|
assert Attachment(path=path, mime_type="image/jpeg").mime_type == "image/jpeg"
|
|
|
|
|
|
@pytest.fixture
|
|
def png_download(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
def fake_download(url: str, path: Path, **kwargs: object) -> Iterator[dict]:
|
|
path.write_bytes(PNG)
|
|
yield {}
|
|
|
|
monkeypatch.setattr(config.directories, "temp", tmp_path)
|
|
monkeypatch.setattr(downloader, "download", fake_download)
|
|
|
|
|
|
@pytest.mark.usefixtures("png_download")
|
|
@pytest.mark.parametrize("mime_type", [None, "image/jpeg"])
|
|
def test_a_url_attachment_takes_the_type_of_the_downloaded_file(mime_type: str | None) -> None:
|
|
"""The suffix type also arrives as a given type when a remote server sends the attachment."""
|
|
attachment = Attachment(url="https://cdn.example/thumb.jpg", mime_type=mime_type)
|
|
attachment.download()
|
|
assert attachment.mime_type == "image/png"
|
|
|
|
|
|
@pytest.mark.usefixtures("png_download")
|
|
def test_a_url_attachment_keeps_a_given_type_that_is_not_the_suffix_type() -> None:
|
|
attachment = Attachment(url="https://cdn.example/thumb.jpg", mime_type="image/x-example")
|
|
attachment.download()
|
|
assert attachment.mime_type == "image/x-example"
|