cmvr-visual/backend/tests/test_media.py
zhanghao 88cf14d794 feat: consolidate story studio and editable automatic production
Restructure backend and frontend modules; add story, library, and editor schema migrations.

Support editable automatic production, manual confirmation modes, account and user lifecycle management, compact container scrolling, consistent forms, and per-task result previews.

Update inference and TTS scheduling, deployment guidance, and regression coverage; remove obsolete standalone pages and temporary acceptance artifacts.
2026-11-14 14:07:26 +08:00

173 lines
6.8 KiB
Python

from __future__ import annotations
import asyncio
import gc
import importlib
import json
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
from types import SimpleNamespace
import unittest
import warnings
from unittest.mock import patch
from PIL import Image
class MediaTests(unittest.IsolatedAsyncioTestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name).resolve()
self.settings = SimpleNamespace(
workspace_root=self.root,
asset_root=self.root / "assets",
job_work_root=self.root / "jobs",
ffmpeg_bin=shutil.which("ffmpeg") or "ffmpeg",
ffprobe_bin=shutil.which("ffprobe") or "ffprobe",
request_timeout_seconds=3,
max_output_bytes=1024 * 1024,
)
self.media = importlib.import_module("app.adapters.media")
async def test_image_is_decoded_and_thumbnail_really_exists(self):
source = self.root / "source.png"
Image.new("RGB", (800, 400), "red").save(source)
info = await self.media.inspect_media(source, self.settings)
self.assertEqual(
(info["kind"], info["mime_type"], info["width"], info["height"]),
("image", "image/png", 800, 400),
)
target = await self.media.make_thumbnail(source, self.root / "thumb.jpg", self.settings)
with Image.open(target) as thumbnail:
self.assertEqual(thumbnail.size, (512, 256))
async def test_generated_json_and_text_are_validated_as_assets(self):
source = self.root / "answer.json"
source.write_text('{"text":"数学"}', encoding="utf-8")
self.assertEqual((await self.media.inspect_media(source, self.settings))["kind"], "json")
source.write_text("{broken", encoding="utf-8")
with self.assertRaises(self.media.MediaError):
await self.media.inspect_media(source, self.settings)
source = self.root / "answer.txt"
source.write_text("答案是 42", encoding="utf-8")
self.assertEqual(
(await self.media.inspect_media(source, self.settings))["mime_type"], "text/plain"
)
self.assertIsNone(
await self.media.make_thumbnail(source, self.root / "unused.jpg", self.settings)
)
async def test_outside_path_and_fake_image_fail_without_path_disclosure(self):
with self.assertRaises(self.media.MediaError) as caught:
await self.media.inspect_media(self.root.parent / "PRIVATE-SECRET.png", self.settings)
self.assertNotIn("PRIVATE-SECRET", str(caught.exception))
broken = self.root / "fake.png"
broken.write_bytes(b"not an image")
with self.assertRaises(self.media.MediaError):
await self.media.inspect_media(broken, self.settings)
async def test_cancel_waits_for_owned_subprocess_and_preserves_unrelated_process(self):
observed = []
create = asyncio.create_subprocess_exec
async def record(*args, **kwargs):
process = await create(*args, **kwargs)
observed.append(process)
return process
unrelated = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
try:
with patch.object(self.media.asyncio, "create_subprocess_exec", side_effect=record):
task = asyncio.create_task(
self.media.run_process(
[sys.executable, "-c", "import time; time.sleep(60)"], timeout=30
)
)
for _ in range(100):
if observed:
break
await asyncio.sleep(0.01)
self.assertTrue(observed)
task.cancel()
with self.assertRaises(asyncio.CancelledError):
await asyncio.wait_for(task, 5)
self.assertIsNotNone(observed[0].returncode)
self.assertIsNone(unrelated.poll())
finally:
unrelated.kill()
unrelated.wait(timeout=5)
async def test_process_timeout_and_output_bound_are_enforced(self):
with self.assertRaises(self.media.MediaError) as caught:
await self.media.run_process(
[sys.executable, "-c", "import time; time.sleep(60)"], timeout=0.1
)
self.assertEqual(caught.exception.code, "media_timeout")
with self.assertRaises(self.media.MediaError):
await self.media.run_process(
[sys.executable, "-c", 'print("x"*100000)'], timeout=3, max_output=256
)
with warnings.catch_warnings(record=True) as captured:
warnings.simplefilter("always", ResourceWarning)
with self.assertRaises(self.media.MediaError):
await asyncio.wait_for(
self.media.run_process(
[
sys.executable,
"-c",
'import sys; sys.stdout.write("x"*10000000); sys.stdout.flush()',
],
timeout=3,
max_output=256,
),
5,
)
await asyncio.sleep(0.05)
gc.collect()
self.assertFalse(
[warning for warning in captured if issubclass(warning.category, ResourceWarning)]
)
async def test_bounded_diagnostics_can_return_actual_frame_timestamps(self):
stdout, stderr = await self.media.run_process(
[
sys.executable,
"-c",
'import sys; print("result"); print("pts_time:0.541667",file=sys.stderr)',
],
timeout=3,
return_stderr=True,
)
self.assertIn(b"result", stdout)
self.assertIn(b"pts_time:0.541667", stderr)
@unittest.skipUnless(shutil.which("ffmpeg") and shutil.which("ffprobe"), "FFmpeg not installed")
async def test_real_video_probe_and_thumbnail(self):
video = self.root / "tiny.mp4"
await self.media.run_process(
[
self.settings.ffmpeg_bin,
"-v",
"error",
"-f",
"lavfi",
"-i",
"color=c=blue:s=320x240:r=24:d=0.5",
"-c:v",
"libx264",
"-pix_fmt",
"yuv420p",
str(video),
],
timeout=30,
)
info = await self.media.inspect_media(video, self.settings)
self.assertEqual((info["kind"], info["width"], info["height"]), ("video", 320, 240))
self.assertGreater(info["duration_seconds"], 0.4)
thumb = await self.media.make_thumbnail(video, self.root / "video.jpg", self.settings)
self.assertTrue(thumb.is_file())