137 lines
5.6 KiB
Python
137 lines
5.6 KiB
Python
"""列表页缩略图层(services/thumbs.py + api/media.py)。
|
||
|
||
这一层存在的唯一理由是「列表页不许再下载原图」,所以用例只盯三件事:
|
||
1. 缓存键会随源文件变化失效(AI 重新生成同名覆盖不能看到旧图);
|
||
2. 任何不可缩略 / 生成失败的情况都必须回落,绝不能把列表打成 500;
|
||
3. 边界与响应头(越界路径、中文路径的 latin-1 头)。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import shutil
|
||
|
||
import pytest
|
||
|
||
from app.services import ffmpeg as ff
|
||
from app.services import storage, thumbs
|
||
|
||
from tests.conftest import _make_image_png
|
||
|
||
needs_ffmpeg = pytest.mark.skipif(not ff.available(), reason="需要 ffmpeg 才能真出图")
|
||
|
||
|
||
def _write(rel: str, width: int = 480, height: int = 270, color: str = "0x3a6ea5"):
|
||
target = storage.media_root() / rel
|
||
target.parent.mkdir(parents=True, exist_ok=True)
|
||
target.write_bytes(_make_image_png(width, height, color))
|
||
return target
|
||
|
||
|
||
# ------------------------------------------------------------------ 纯函数
|
||
def test_width_is_quantised_to_fixed_steps():
|
||
assert thumbs.normalize_width(200) == 256 # 向上取整到档位
|
||
assert thumbs.normalize_width(384) == 384
|
||
assert thumbs.normalize_width(4000) == thumbs.WIDTHS[-1]
|
||
for junk in (None, "", "abc", 0, -3):
|
||
assert thumbs.normalize_width(junk) == thumbs.DEFAULT_WIDTH
|
||
|
||
|
||
def test_only_raster_and_video_are_thumbable():
|
||
assert thumbs.is_thumbable("a/b/c.png")
|
||
assert thumbs.is_thumbable("a/b/c.MP4")
|
||
assert thumbs.is_thumbable("/media/1/keyframe/shot.png?v=2")
|
||
for nope in ("voice.wav", "notes.md", "icon.svg", "", None):
|
||
assert not thumbs.is_thumbable(nope)
|
||
|
||
|
||
def test_resolve_accepts_url_relative_and_absolute_forms(tmp_path):
|
||
made = _write("1/keyframe/a.png")
|
||
assert thumbs.resolve("1/keyframe/a.png") == made.resolve()
|
||
assert thumbs.resolve("/1/keyframe/a.png") == made.resolve()
|
||
assert thumbs.resolve("/media/1/keyframe/a.png") == made.resolve()
|
||
assert thumbs.resolve(str(made)) == made.resolve()
|
||
|
||
|
||
def test_resolve_refuses_escapes_and_missing_files():
|
||
assert thumbs.resolve("../../etc/passwd") is None
|
||
assert thumbs.resolve("1/keyframe/nope.png") is None
|
||
assert thumbs.resolve("/etc/hosts") is None
|
||
|
||
|
||
# ------------------------------------------------------------------ 缓存生成
|
||
@needs_ffmpeg
|
||
def test_build_generates_once_and_reuses_cache():
|
||
made = _write("1/keyframe/cache.png")
|
||
first = thumbs.build(made, 200)
|
||
assert first is not None and first.is_file() and first.stat().st_size > 0
|
||
assert first.parent == storage.media_root() / thumbs.CACHE_DIR
|
||
assert first.stat().st_size < made.stat().st_size # 缩略图必须比原图小才有意义
|
||
|
||
second = thumbs.build(made, 200)
|
||
assert second == first # 第二次直接命中,不重新编码
|
||
|
||
made.write_bytes(_make_image_png(600, 340, "0xaa11bb")) # 同名覆盖 → 缓存键必须变
|
||
third = thumbs.build(made, 200)
|
||
assert third is not None and third != first
|
||
|
||
|
||
@needs_ffmpeg
|
||
def test_drop_clears_every_cached_variant():
|
||
made = _write("1/keyframe/drop.png")
|
||
widths = {thumbs.build(made, w).name.split("-w")[1] for w in (128, 384)}
|
||
assert len(widths) == 2
|
||
assert thumbs.drop(made) == 2
|
||
assert thumbs.drop(made) == 0
|
||
|
||
|
||
@needs_ffmpeg
|
||
def test_delete_media_file_evicts_thumbnails():
|
||
made = _write("1/keyframe/evict.png")
|
||
assert thumbs.build(made, 384) is not None
|
||
storage.delete_media_file(str(made))
|
||
assert list((storage.media_root() / thumbs.CACHE_DIR).glob("*")) == []
|
||
|
||
|
||
@needs_ffmpeg
|
||
def test_broken_source_falls_back_instead_of_raising(monkeypatch):
|
||
made = _write("1/keyframe/broken.png")
|
||
monkeypatch.setattr(thumbs, "_generate", lambda *a, **k: None)
|
||
monkeypatch.setattr(thumbs, "_failed", {}) # 绕开失败短路,验证真的回落
|
||
assert thumbs.build(made, 384) is None
|
||
|
||
|
||
# ------------------------------------------------------------------ 接口
|
||
@needs_ffmpeg
|
||
def test_thumbnail_route_serves_small_image_with_long_cache(api):
|
||
_write("1/keyframe/route.png", 640, 360)
|
||
response = api.get("/api/media/thumb/200/1/keyframe/route.png", expect=200)
|
||
assert response.headers["content-type"].startswith("image/")
|
||
assert "immutable" in response.headers["cache-control"]
|
||
assert response.headers["etag"]
|
||
assert response.headers["x-thumb-source"] == "/media/1/keyframe/route.png"
|
||
|
||
|
||
def test_thumbnail_route_handles_cjk_paths(api):
|
||
"""中文素材名在真实项目里是常态:响应头必须转义,否则整张卡片 500。"""
|
||
_write("素材/1/定妆图.png")
|
||
response = api.get("/api/media/thumb/384/%E7%B4%A0%E6%9D%90/1/%E5%AE%9A%E5%A6%86%E5%9B%BE.png",
|
||
expect=None)
|
||
assert response.status_code in (200, 307), response.text[:300]
|
||
|
||
|
||
def test_thumbnail_route_redirects_audio_and_404s_missing(api):
|
||
wav = storage.media_root() / "1/voiceover/a.wav"
|
||
wav.parent.mkdir(parents=True, exist_ok=True)
|
||
wav.write_bytes(b"RIFF....WAVEfmt ")
|
||
redirected = api.get("/api/media/thumb/384/1/voiceover/a.wav", expect=None,
|
||
follow_redirects=False)
|
||
assert redirected.status_code == 307
|
||
assert redirected.headers["location"] == "/media/1/voiceover/a.wav"
|
||
api.get("/api/media/thumb/384/1/keyframe/ghost.png", expect=404)
|
||
|
||
|
||
def test_cache_url_is_empty_for_assets_without_files(api):
|
||
assert thumbs.cache_url("1/keyframe/ghost.png") == ""
|
||
assert thumbs.cache_url("1/voiceover/a.mp3") == ""
|
||
_write("1/keyframe/url.png")
|
||
assert thumbs.cache_url("/media/1/keyframe/url.png", 100) == "/api/media/thumb/128/1/keyframe/url.png"
|