Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Paid, hosted product at menivor.com, now retired as a company project. Fresh squashed history of the cleaned working tree (secret-scanned, no .env, no customer data, no outreach logs). Built on MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
1627 lines
64 KiB
Python
1627 lines
64 KiB
Python
import unittest
|
||
import os
|
||
import shutil
|
||
import sys
|
||
import tempfile
|
||
from concurrent.futures import Future
|
||
from pathlib import Path
|
||
from unittest.mock import MagicMock, patch
|
||
from uuid import uuid4
|
||
|
||
# add project root to python path
|
||
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
|
||
|
||
from app.services import task as tm
|
||
from app.models.schema import MaterialInfo, VideoParams
|
||
from app.services.state import MemoryState, RedisState
|
||
from app.utils import utils
|
||
|
||
resources_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "resources")
|
||
RUN_INTEGRATION_TESTS = os.environ.get("MPT_RUN_INTEGRATION_TESTS", "").lower() in {
|
||
"1",
|
||
"true",
|
||
"yes",
|
||
}
|
||
|
||
class TestTaskService(unittest.TestCase):
|
||
def setUp(self):
|
||
# 发布 Future 注册表是进程级状态。测试间清理可以避免某个模拟 Future
|
||
# 影响后续恢复测试,同时不会触碰真正线程池中的生产任务。
|
||
with tm._cross_post_registry_lock:
|
||
tm._cross_post_futures.clear()
|
||
|
||
def tearDown(self):
|
||
with tm._cross_post_registry_lock:
|
||
tm._cross_post_futures.clear()
|
||
|
||
def test_is_task_busy_covers_generation_and_cross_posting(self):
|
||
"""删除入口必须同时识别视频生成和跨平台发布的活跃状态。"""
|
||
busy_tasks = (
|
||
{"state": tm.const.TASK_STATE_PROCESSING},
|
||
{
|
||
"state": tm.const.TASK_STATE_COMPLETE,
|
||
"cross_post_state": tm.const.CROSS_POST_STATE_PENDING,
|
||
},
|
||
{
|
||
"state": tm.const.TASK_STATE_COMPLETE,
|
||
"cross_post_state": tm.const.CROSS_POST_STATE_PROCESSING,
|
||
},
|
||
)
|
||
for task in busy_tasks:
|
||
with self.subTest(task=task):
|
||
self.assertTrue(tm.is_task_busy(task))
|
||
|
||
self.assertFalse(
|
||
tm.is_task_busy(
|
||
{
|
||
"state": tm.const.TASK_STATE_COMPLETE,
|
||
"cross_post_state": tm.const.CROSS_POST_STATE_COMPLETE,
|
||
}
|
||
)
|
||
)
|
||
self.assertFalse(tm.is_task_busy(None))
|
||
|
||
def test_generate_script_forwards_advanced_prompt_options(self):
|
||
"""
|
||
任务生成入口和 WebUI/API 共用 VideoParams。这里验证自动生成文案时,
|
||
高级提示词参数会继续传到 LLM 服务层,避免只在 /scripts 接口生效。
|
||
"""
|
||
params = VideoParams(
|
||
video_subject="咖啡",
|
||
video_script="",
|
||
video_language="zh-CN",
|
||
paragraph_number=2,
|
||
video_script_prompt="语气轻松",
|
||
custom_system_prompt="Only write short narration.",
|
||
)
|
||
|
||
with patch.object(tm.llm, "generate_script", return_value="生成的文案") as generate:
|
||
result = tm.generate_script("task-id", params)
|
||
|
||
self.assertEqual(result, "生成的文案")
|
||
generate.assert_called_once_with(
|
||
video_subject="咖啡",
|
||
language="zh-CN",
|
||
paragraph_number=2,
|
||
video_script_prompt="语气轻松",
|
||
custom_system_prompt="Only write short narration.",
|
||
)
|
||
|
||
def test_generate_final_videos_forwards_clip_speed(self):
|
||
"""任务编排层必须把用户选择的画面速度传给视频合成服务。"""
|
||
params = VideoParams(
|
||
video_subject="test",
|
||
video_count=1,
|
||
video_clip_speed=1.25,
|
||
)
|
||
|
||
with (
|
||
patch.object(tm.video, "combine_videos") as combine_videos,
|
||
patch.object(tm.video, "generate_video"),
|
||
patch.object(tm.sm.state, "update_task"),
|
||
):
|
||
tm.generate_final_videos(
|
||
task_id="clip-speed-task",
|
||
params=params,
|
||
downloaded_videos=["material.mp4"],
|
||
audio_file="audio.mp3",
|
||
subtitle_path="",
|
||
audio_duration=5,
|
||
)
|
||
|
||
self.assertEqual(combine_videos.call_args.kwargs["clip_speed"], 1.25)
|
||
|
||
def test_generate_final_videos_uses_generated_sonilo_music(self):
|
||
"""Sonilo 必须针对每条拼接后的视频生成配乐,并传给最终混音。"""
|
||
params = VideoParams(
|
||
video_subject="test",
|
||
video_count=1,
|
||
bgm_type="sonilo",
|
||
sonilo_bgm_prompt="warm acoustic",
|
||
)
|
||
|
||
with (
|
||
patch.object(tm.video, "combine_videos"),
|
||
patch.object(
|
||
tm.sonilo,
|
||
"generate_bgm",
|
||
side_effect=lambda **kwargs: kwargs["output_path"],
|
||
) as generate_bgm,
|
||
patch.object(tm.video, "generate_video") as generate_video,
|
||
patch.object(tm.sm.state, "update_task"),
|
||
):
|
||
_, _, warnings = tm.generate_final_videos(
|
||
task_id="sonilo-task",
|
||
params=params,
|
||
downloaded_videos=["material.mp4"],
|
||
audio_file="audio.mp3",
|
||
subtitle_path="",
|
||
audio_duration=5,
|
||
)
|
||
|
||
self.assertEqual(warnings, [])
|
||
self.assertEqual(generate_bgm.call_args.kwargs["video_duration"], 5)
|
||
self.assertEqual(generate_bgm.call_args.kwargs["prompt"], "warm acoustic")
|
||
self.assertTrue(
|
||
generate_video.call_args.kwargs["bgm_file_override"].endswith(
|
||
"sonilo-bgm-1.m4a"
|
||
)
|
||
)
|
||
|
||
def test_generate_final_videos_uses_generated_elevenlabs_music(self):
|
||
"""ElevenLabs 应复用视频配乐编排,并使用通用风格提示词。"""
|
||
params = VideoParams(
|
||
video_subject="test",
|
||
video_count=1,
|
||
bgm_type="elevenlabs",
|
||
video_music_prompt="gentle documentary",
|
||
)
|
||
|
||
with (
|
||
patch.object(tm.video, "combine_videos"),
|
||
patch.object(
|
||
tm.elevenlabs_music,
|
||
"generate_bgm",
|
||
side_effect=lambda **kwargs: kwargs["output_path"],
|
||
) as generate_bgm,
|
||
patch.object(tm.video, "generate_video") as generate_video,
|
||
patch.object(tm.sm.state, "update_task"),
|
||
):
|
||
_, _, warnings = tm.generate_final_videos(
|
||
task_id="elevenlabs-task",
|
||
params=params,
|
||
downloaded_videos=["material.mp4"],
|
||
audio_file="audio.mp3",
|
||
subtitle_path="",
|
||
audio_duration=5,
|
||
)
|
||
|
||
self.assertEqual(warnings, [])
|
||
self.assertEqual(generate_bgm.call_args.kwargs["video_duration"], 5)
|
||
self.assertEqual(
|
||
generate_bgm.call_args.kwargs["prompt"], "gentle documentary"
|
||
)
|
||
self.assertTrue(
|
||
generate_video.call_args.kwargs["bgm_file_override"].endswith(
|
||
"elevenlabs-bgm-1.mp3"
|
||
)
|
||
)
|
||
|
||
def test_generate_final_videos_falls_back_on_elevenlabs_failure(self):
|
||
"""ElevenLabs 暂时失败时必须保留无配乐视频和结构化警告。"""
|
||
params = VideoParams(video_subject="test", bgm_type="elevenlabs")
|
||
|
||
with (
|
||
patch.object(tm.video, "combine_videos"),
|
||
patch.object(
|
||
tm.elevenlabs_music,
|
||
"generate_bgm",
|
||
side_effect=tm.elevenlabs_music.ElevenLabsMusicError(
|
||
"temporary outage"
|
||
),
|
||
),
|
||
patch.object(tm.video, "generate_video") as generate_video,
|
||
patch.object(tm.sm.state, "update_task"),
|
||
):
|
||
final_paths, _, warnings = tm.generate_final_videos(
|
||
task_id="elevenlabs-fallback",
|
||
params=params,
|
||
downloaded_videos=["material.mp4"],
|
||
audio_file="audio.mp3",
|
||
subtitle_path="",
|
||
audio_duration=5,
|
||
)
|
||
|
||
self.assertEqual(len(final_paths), 1)
|
||
self.assertEqual(
|
||
warnings,
|
||
[{"code": "elevenlabs_bgm_failed", "video_index": 1}],
|
||
)
|
||
self.assertEqual(generate_video.call_args.kwargs["bgm_file_override"], "")
|
||
|
||
def test_generate_final_videos_falls_back_without_bgm_on_sonilo_failure(self):
|
||
"""第三方配乐失败时应完成视频并返回可见警告,而不是丢弃所有产物。"""
|
||
params = VideoParams(video_subject="test", bgm_type="sonilo")
|
||
|
||
with (
|
||
patch.object(tm.video, "combine_videos"),
|
||
patch.object(
|
||
tm.sonilo,
|
||
"generate_bgm",
|
||
side_effect=tm.sonilo.SoniloError("temporary outage"),
|
||
),
|
||
patch.object(tm.video, "generate_video") as generate_video,
|
||
patch.object(tm.sm.state, "update_task"),
|
||
):
|
||
final_paths, _, warnings = tm.generate_final_videos(
|
||
task_id="sonilo-fallback",
|
||
params=params,
|
||
downloaded_videos=["material.mp4"],
|
||
audio_file="audio.mp3",
|
||
subtitle_path="",
|
||
audio_duration=5,
|
||
)
|
||
|
||
self.assertEqual(len(final_paths), 1)
|
||
self.assertEqual(
|
||
warnings, [{"code": "sonilo_bgm_failed", "video_index": 1}]
|
||
)
|
||
self.assertEqual(generate_video.call_args.kwargs["bgm_file_override"], "")
|
||
|
||
def test_generate_final_videos_skips_sonilo_when_volume_is_zero(self):
|
||
"""0 音量必须完全跳过 Sonilo 生成,并显式禁用残留背景音乐。"""
|
||
params = VideoParams(
|
||
video_subject="test",
|
||
bgm_type="sonilo",
|
||
bgm_volume=0.0,
|
||
bgm_file="stale-custom-bgm.mp3",
|
||
)
|
||
|
||
with (
|
||
patch.object(tm.video, "combine_videos"),
|
||
patch.object(tm.sonilo, "generate_bgm") as generate_bgm,
|
||
patch.object(tm.video, "generate_video", return_value=True) as generate,
|
||
patch.object(tm.sm.state, "update_task"),
|
||
):
|
||
final_paths, _, warnings = tm.generate_final_videos(
|
||
task_id="sonilo-zero-volume",
|
||
params=params,
|
||
downloaded_videos=["material.mp4"],
|
||
audio_file="audio.mp3",
|
||
subtitle_path="",
|
||
audio_duration=5,
|
||
)
|
||
|
||
self.assertEqual(len(final_paths), 1)
|
||
self.assertEqual(warnings, [])
|
||
generate_bgm.assert_not_called()
|
||
self.assertEqual(generate.call_args.kwargs["bgm_file_override"], "")
|
||
|
||
def test_generate_final_videos_warns_when_sonilo_mix_fails(self):
|
||
"""Sonilo 生成成功但最终混音失败时,任务必须保留视频并返回警告。"""
|
||
params = VideoParams(video_subject="test", bgm_type="sonilo")
|
||
|
||
with (
|
||
patch.object(tm.video, "combine_videos"),
|
||
patch.object(
|
||
tm.sonilo,
|
||
"generate_bgm",
|
||
side_effect=lambda **kwargs: kwargs["output_path"],
|
||
),
|
||
patch.object(tm.video, "generate_video", return_value=False) as generate,
|
||
patch.object(tm.sm.state, "update_task"),
|
||
):
|
||
final_paths, _, warnings = tm.generate_final_videos(
|
||
task_id="sonilo-mix-fallback",
|
||
params=params,
|
||
downloaded_videos=["material.mp4"],
|
||
audio_file="audio.mp3",
|
||
subtitle_path="",
|
||
audio_duration=5,
|
||
)
|
||
|
||
self.assertEqual(len(final_paths), 1)
|
||
self.assertEqual(
|
||
warnings, [{"code": "sonilo_bgm_failed", "video_index": 1}]
|
||
)
|
||
self.assertTrue(
|
||
generate.call_args.kwargs["bgm_file_override"].endswith(".m4a")
|
||
)
|
||
|
||
def test_start_rejects_missing_sonilo_key_before_costly_pipeline_steps(self):
|
||
"""完整任务缺少 Sonilo Key 时不能先调用 LLM、TTS 或素材服务。"""
|
||
params = VideoParams(video_subject="test", bgm_type="sonilo")
|
||
state = MemoryState()
|
||
with (
|
||
patch.object(tm.sonilo, "is_enabled", return_value=False),
|
||
patch.object(tm, "generate_script") as generate_script,
|
||
patch.object(tm, "generate_audio") as generate_audio,
|
||
patch.object(tm, "get_video_materials") as get_materials,
|
||
patch.object(tm.sm, "state", state),
|
||
):
|
||
result = tm.start("missing-sonilo-key", params)
|
||
|
||
generate_script.assert_not_called()
|
||
generate_audio.assert_not_called()
|
||
get_materials.assert_not_called()
|
||
failed_task = state.get_task("missing-sonilo-key")
|
||
self.assertEqual(result, failed_task)
|
||
self.assertEqual(failed_task["state"], tm.const.TASK_STATE_FAILED)
|
||
self.assertEqual(failed_task["failed_stage"], "preflight")
|
||
self.assertIn("API key", failed_task["error"])
|
||
|
||
def test_start_does_not_require_sonilo_key_when_volume_is_zero(self):
|
||
"""0 音量不会使用 Sonilo,因此缺少 Key 时仍应进入正常任务流水线。"""
|
||
params = VideoParams(
|
||
video_subject="test",
|
||
bgm_type="sonilo",
|
||
bgm_volume=0.0,
|
||
)
|
||
state = MemoryState()
|
||
with (
|
||
patch.object(tm.sonilo, "is_enabled", return_value=False),
|
||
patch.object(tm, "generate_script", return_value="") as generate_script,
|
||
patch.object(tm.sm, "state", state),
|
||
):
|
||
result = tm.start("zero-volume-without-key", params)
|
||
|
||
generate_script.assert_called_once_with("zero-volume-without-key", params)
|
||
self.assertEqual(result["failed_stage"], "script")
|
||
|
||
def test_start_rejects_missing_elevenlabs_key_before_pipeline_steps(self):
|
||
"""完整任务缺少 ElevenLabs Key 时必须在任何付费步骤前失败。"""
|
||
params = VideoParams(video_subject="test", bgm_type="elevenlabs")
|
||
state = MemoryState()
|
||
with (
|
||
patch.object(
|
||
tm.elevenlabs_music, "is_enabled", return_value=False
|
||
),
|
||
patch.object(tm, "generate_script") as generate_script,
|
||
patch.object(tm, "generate_audio") as generate_audio,
|
||
patch.object(tm.sm, "state", state),
|
||
):
|
||
result = tm.start("missing-elevenlabs-key", params)
|
||
|
||
generate_script.assert_not_called()
|
||
generate_audio.assert_not_called()
|
||
self.assertEqual(result["state"], tm.const.TASK_STATE_FAILED)
|
||
self.assertEqual(result["failed_stage"], "preflight")
|
||
self.assertIn("ElevenLabs", result["error"])
|
||
|
||
def test_start_rejects_free_elevenlabs_plan_before_pipeline_steps(self):
|
||
"""已确认的免费套餐不能先消耗 LLM、TTS 或素材服务额度。"""
|
||
params = VideoParams(video_subject="test", bgm_type="elevenlabs")
|
||
state = MemoryState()
|
||
with (
|
||
patch.object(
|
||
tm.elevenlabs_music, "is_enabled", return_value=True
|
||
),
|
||
patch.object(
|
||
tm.elevenlabs_music,
|
||
"validate_generation_access",
|
||
side_effect=(
|
||
tm.elevenlabs_music.ElevenLabsPaidPlanRequiredError(
|
||
"ElevenLabs Music API requires a paid plan"
|
||
)
|
||
),
|
||
) as validate_access,
|
||
patch.object(tm, "generate_script") as generate_script,
|
||
patch.object(tm, "generate_audio") as generate_audio,
|
||
patch.object(tm.sm, "state", state),
|
||
):
|
||
result = tm.start("free-elevenlabs-plan", params)
|
||
|
||
validate_access.assert_called_once_with()
|
||
generate_script.assert_not_called()
|
||
generate_audio.assert_not_called()
|
||
self.assertEqual(result["failed_stage"], "preflight")
|
||
self.assertIn("paid plan", result["error"])
|
||
|
||
def test_start_rejects_oversized_elevenlabs_prompt_before_account_check(self):
|
||
"""API/CLI 绕过 WebUI 时,超长提示词也必须在昂贵步骤前被拒绝。"""
|
||
params = VideoParams(
|
||
video_subject="test",
|
||
bgm_type="elevenlabs",
|
||
video_music_prompt="x" * 1001,
|
||
)
|
||
state = MemoryState()
|
||
with (
|
||
patch.object(
|
||
tm.elevenlabs_music, "is_enabled", return_value=True
|
||
),
|
||
patch.object(
|
||
tm.elevenlabs_music, "validate_generation_access"
|
||
) as validate_access,
|
||
patch.object(tm, "generate_script") as generate_script,
|
||
patch.object(tm.sm, "state", state),
|
||
):
|
||
result = tm.start("oversized-elevenlabs-prompt", params)
|
||
|
||
validate_access.assert_not_called()
|
||
generate_script.assert_not_called()
|
||
self.assertEqual(result["failed_stage"], "preflight")
|
||
self.assertIn("1000", result["error"])
|
||
|
||
def test_generate_terms_uses_script_order_mode_when_enabled(self):
|
||
"""
|
||
默认模式不受影响;只有用户显式开启素材按文案顺序匹配时,任务层才
|
||
要求 LLM 生成有序关键词,并适当增加关键词数量以覆盖更多脚本片段。
|
||
"""
|
||
params = VideoParams(
|
||
video_subject="城市通勤",
|
||
video_script="",
|
||
match_materials_to_script=True,
|
||
)
|
||
|
||
with patch.object(tm.llm, "generate_terms", return_value=["city", "train"]) as generate:
|
||
result = tm.generate_terms("task-id", params, "先城市,再地铁")
|
||
|
||
self.assertEqual(result, ["city", "train"])
|
||
generate.assert_called_once_with(
|
||
video_subject="城市通勤",
|
||
video_script="先城市,再地铁",
|
||
amount=8,
|
||
match_script_order=True,
|
||
)
|
||
|
||
def test_term_provider_outage_does_not_stop_the_reel(self):
|
||
"""
|
||
MG8: when every LLM fails, the terms stage uses subject terms and the
|
||
pipeline continues to audio instead of failing a paid reel at "terms".
|
||
"""
|
||
params = VideoParams(
|
||
video_subject="startup story",
|
||
video_script="A short startup story.",
|
||
)
|
||
state = MemoryState()
|
||
|
||
with (
|
||
patch.object(
|
||
tm.llm,
|
||
"_generate_response",
|
||
return_value="Error: invalid API key",
|
||
),
|
||
patch.object(tm, "generate_audio", return_value=(None, 0, None)) as generate_audio,
|
||
patch.object(tm, "get_video_materials") as get_video_materials,
|
||
patch.object(tm.sm, "state", state),
|
||
):
|
||
tm.start("term-provider-error", params)
|
||
|
||
generate_audio.assert_called_once()
|
||
get_video_materials.assert_not_called()
|
||
task = state.get_task("term-provider-error")
|
||
self.assertNotEqual(task.get("failed_stage"), "terms")
|
||
|
||
def test_generate_audio_uses_custom_file_inside_task_directory(self):
|
||
task_id = "test-custom-audio-safe"
|
||
task_dir = utils.task_dir(task_id)
|
||
custom_audio_file = os.path.join(task_dir, "custom-audio.mp3")
|
||
with open(custom_audio_file, "wb") as audio:
|
||
audio.write(b"fake audio")
|
||
|
||
params = VideoParams(
|
||
video_subject="custom audio",
|
||
video_script="",
|
||
custom_audio_file=custom_audio_file,
|
||
voice_name="test-voice",
|
||
)
|
||
|
||
try:
|
||
with (
|
||
patch.object(tm.voice, "tts") as tts,
|
||
patch.object(tm.voice, "get_audio_duration", return_value=7),
|
||
):
|
||
audio_file, audio_duration, sub_maker = tm.generate_audio(
|
||
task_id, params, "script"
|
||
)
|
||
finally:
|
||
shutil.rmtree(task_dir, ignore_errors=True)
|
||
|
||
self.assertEqual(audio_file, os.path.realpath(custom_audio_file))
|
||
self.assertEqual(audio_duration, 7)
|
||
self.assertIsNone(sub_maker)
|
||
tts.assert_not_called()
|
||
|
||
def test_generate_audio_accepts_server_side_custom_file(self):
|
||
task_id = "test-custom-audio-server-side"
|
||
task_dir = utils.task_dir(task_id)
|
||
|
||
with tempfile.NamedTemporaryFile(suffix=".mp3") as server_audio:
|
||
server_audio.write(b"fake audio")
|
||
server_audio.flush()
|
||
params = VideoParams(
|
||
video_subject="custom audio",
|
||
video_script="",
|
||
custom_audio_file=server_audio.name,
|
||
voice_name="test-voice",
|
||
)
|
||
|
||
try:
|
||
with (
|
||
patch.object(tm.voice, "tts") as tts,
|
||
patch.object(tm.voice, "get_audio_duration", return_value=6),
|
||
):
|
||
audio_file, audio_duration, result_sub_maker = tm.generate_audio(
|
||
task_id, params, "script"
|
||
)
|
||
finally:
|
||
shutil.rmtree(task_dir, ignore_errors=True)
|
||
|
||
self.assertEqual(audio_file, os.path.realpath(server_audio.name))
|
||
self.assertEqual(audio_duration, 6)
|
||
self.assertIsNone(result_sub_maker)
|
||
tts.assert_not_called()
|
||
|
||
def test_generate_audio_rejects_missing_custom_file_without_tts(self):
|
||
task_id = "test-custom-audio-missing"
|
||
task_dir = utils.task_dir(task_id)
|
||
missing_audio_file = os.path.join(task_dir, "missing.mp3")
|
||
params = VideoParams(
|
||
video_subject="custom audio",
|
||
video_script="",
|
||
custom_audio_file=missing_audio_file,
|
||
voice_name="test-voice",
|
||
)
|
||
state = MemoryState()
|
||
|
||
try:
|
||
with (
|
||
patch.object(tm.voice, "tts") as tts,
|
||
patch.object(tm.sm, "state", state),
|
||
):
|
||
audio_file, audio_duration, result_sub_maker = tm.generate_audio(
|
||
task_id, params, "script"
|
||
)
|
||
finally:
|
||
shutil.rmtree(task_dir, ignore_errors=True)
|
||
|
||
self.assertIsNone(audio_file)
|
||
self.assertIsNone(audio_duration)
|
||
self.assertIsNone(result_sub_maker)
|
||
tts.assert_not_called()
|
||
failed_task = state.get_task(task_id)
|
||
self.assertEqual(failed_task["failed_stage"], "audio")
|
||
self.assertIn("does not exist", failed_task["error"])
|
||
|
||
def test_generate_subtitle_uses_whisper_for_custom_audio_without_sub_maker(self):
|
||
"""
|
||
自定义音频不会经过 TTS,所以没有 sub_maker。
|
||
Whisper 可以直接从音频文件转写,此时不能被 sub_maker 为空的保护逻辑提前跳过。
|
||
"""
|
||
task_id = "test-custom-audio-whisper-subtitle"
|
||
task_dir = utils.task_dir(task_id)
|
||
audio_file = os.path.join(task_dir, "custom-audio.mp3")
|
||
Path(audio_file).write_bytes(b"fake audio")
|
||
params = VideoParams(
|
||
video_subject="custom audio",
|
||
video_script="Hello world.",
|
||
subtitle_enabled=True,
|
||
)
|
||
|
||
def fake_whisper_create(audio_file, subtitle_file):
|
||
Path(subtitle_file).write_text(
|
||
"1\n00:00:00,000 --> 00:00:01,000\nHello world.\n\n",
|
||
encoding="utf-8",
|
||
)
|
||
|
||
try:
|
||
with (
|
||
patch.object(
|
||
tm.config,
|
||
"app",
|
||
dict(tm.config.app, subtitle_provider="whisper"),
|
||
),
|
||
patch.object(
|
||
tm.subtitle, "create", side_effect=fake_whisper_create
|
||
) as create,
|
||
patch.object(tm.subtitle, "correct") as correct,
|
||
):
|
||
subtitle_path = tm.generate_subtitle(
|
||
task_id=task_id,
|
||
params=params,
|
||
video_script="Hello world.",
|
||
sub_maker=None,
|
||
audio_file=audio_file,
|
||
)
|
||
finally:
|
||
shutil.rmtree(task_dir, ignore_errors=True)
|
||
|
||
self.assertTrue(subtitle_path.endswith("subtitle.srt"))
|
||
create.assert_called_once_with(audio_file=audio_file, subtitle_file=subtitle_path)
|
||
correct.assert_called_once_with(
|
||
subtitle_file=subtitle_path, video_script="Hello world."
|
||
)
|
||
|
||
def test_generate_subtitle_skips_edge_provider_without_sub_maker(self):
|
||
"""
|
||
Edge 字幕依赖 TTS 返回的 sub_maker 时间轴。
|
||
自定义音频缺少该对象时应继续跳过,避免产生不可信的字幕时间轴。
|
||
"""
|
||
task_id = "test-custom-audio-edge-no-submaker"
|
||
task_dir = utils.task_dir(task_id)
|
||
audio_file = os.path.join(task_dir, "custom-audio.mp3")
|
||
Path(audio_file).write_bytes(b"fake audio")
|
||
params = VideoParams(
|
||
video_subject="custom audio",
|
||
video_script="Hello world.",
|
||
subtitle_enabled=True,
|
||
)
|
||
|
||
try:
|
||
with (
|
||
patch.object(
|
||
tm.config,
|
||
"app",
|
||
dict(tm.config.app, subtitle_provider="edge"),
|
||
),
|
||
patch.object(tm.voice, "create_subtitle") as create_subtitle,
|
||
patch.object(tm.subtitle, "create") as whisper_create,
|
||
):
|
||
subtitle_path = tm.generate_subtitle(
|
||
task_id=task_id,
|
||
params=params,
|
||
video_script="Hello world.",
|
||
sub_maker=None,
|
||
audio_file=audio_file,
|
||
)
|
||
finally:
|
||
shutil.rmtree(task_dir, ignore_errors=True)
|
||
|
||
self.assertEqual(subtitle_path, "")
|
||
create_subtitle.assert_not_called()
|
||
whisper_create.assert_not_called()
|
||
|
||
def test_generate_subtitle_does_not_fallback_to_whisper_when_edge_fails(self):
|
||
"""
|
||
Edge 没有生成字幕文件时应保留无字幕结果,不能自动下载 Whisper 模型。
|
||
|
||
该场景可能由 TTS 时间轴与原始文案无法匹配触发。自动回退会让未选择
|
||
Whisper 的用户意外下载数 GB 模型,因此必须验证 Whisper 完全不会被调用。
|
||
"""
|
||
task_id = "test-edge-subtitle-without-output"
|
||
task_dir = utils.task_dir(task_id)
|
||
params = VideoParams(
|
||
video_subject="edge subtitle",
|
||
video_script="Hello world.",
|
||
subtitle_enabled=True,
|
||
)
|
||
sub_maker = object()
|
||
|
||
try:
|
||
with (
|
||
patch.object(
|
||
tm.config,
|
||
"app",
|
||
dict(tm.config.app, subtitle_provider="edge"),
|
||
),
|
||
patch.object(tm.voice, "create_subtitle") as create_subtitle,
|
||
patch.object(tm.subtitle, "create") as whisper_create,
|
||
patch.object(tm.subtitle, "correct") as whisper_correct,
|
||
):
|
||
subtitle_path = tm.generate_subtitle(
|
||
task_id=task_id,
|
||
params=params,
|
||
video_script="Hello world.",
|
||
sub_maker=sub_maker,
|
||
audio_file=os.path.join(task_dir, "audio.mp3"),
|
||
)
|
||
finally:
|
||
shutil.rmtree(task_dir, ignore_errors=True)
|
||
|
||
self.assertEqual(subtitle_path, "")
|
||
create_subtitle.assert_called_once()
|
||
whisper_create.assert_not_called()
|
||
whisper_correct.assert_not_called()
|
||
|
||
def test_start_returns_each_intermediate_result(self):
|
||
"""
|
||
API 的 script、terms、audio、subtitle 和 materials 模式共用同一条任务
|
||
流水线。每个提前停止点都要返回对应产物,同时不能误执行后续阶段。
|
||
"""
|
||
expected_results = {
|
||
"script": {"script": "generated script"},
|
||
"terms": {
|
||
"script": "generated script",
|
||
"terms": ["coffee", "morning"],
|
||
},
|
||
"audio": {"audio_file": "audio.mp3", "audio_duration": 5},
|
||
"subtitle": {"subtitle_path": "subtitle.srt"},
|
||
"materials": {"materials": ["clip.mp4"]},
|
||
}
|
||
|
||
for stop_at, expected in expected_results.items():
|
||
with self.subTest(stop_at=stop_at):
|
||
params = VideoParams(video_subject="Coffee")
|
||
with (
|
||
patch.object(tm, "generate_script", return_value="generated script"),
|
||
patch.object(
|
||
tm,
|
||
"generate_terms",
|
||
return_value=["coffee", "morning"],
|
||
),
|
||
patch.object(tm, "save_script_data"),
|
||
patch.object(
|
||
tm,
|
||
"generate_audio",
|
||
return_value=("audio.mp3", 5, object()),
|
||
),
|
||
patch.object(
|
||
tm,
|
||
"generate_subtitle",
|
||
return_value="subtitle.srt",
|
||
),
|
||
patch.object(
|
||
tm,
|
||
"get_video_materials",
|
||
return_value=["clip.mp4"],
|
||
),
|
||
patch.object(tm, "generate_final_videos") as generate_final,
|
||
patch.object(tm.sm.state, "update_task"),
|
||
):
|
||
result = tm.start(
|
||
f"intermediate-{stop_at}", params, stop_at=stop_at
|
||
)
|
||
|
||
self.assertEqual(result, expected)
|
||
generate_final.assert_not_called()
|
||
|
||
def test_start_completes_video_without_cross_posting(self):
|
||
"""
|
||
完整任务在自动发布未配置时仍应稳定完成,并把所有中间产物写入最终
|
||
状态。这里还覆盖 API 可能传入字符串拼接模式的兼容转换。
|
||
"""
|
||
params = VideoParams(video_subject="Coffee")
|
||
params.video_concat_mode = "sequential"
|
||
|
||
with (
|
||
patch.object(tm, "generate_script", return_value="generated script"),
|
||
patch.object(tm, "generate_terms", return_value=["coffee"]),
|
||
patch.object(tm, "save_script_data"),
|
||
patch.object(
|
||
tm,
|
||
"generate_audio",
|
||
return_value=("audio.mp3", 5, object()),
|
||
),
|
||
patch.object(tm, "generate_subtitle", return_value="subtitle.srt"),
|
||
patch.object(
|
||
tm,
|
||
"get_video_materials",
|
||
return_value=["clip.mp4"],
|
||
),
|
||
patch.object(
|
||
tm,
|
||
"generate_final_videos",
|
||
return_value=(["final.mp4"], ["combined.mp4"], []),
|
||
),
|
||
patch.object(
|
||
tm.upload_post.upload_post_service,
|
||
"is_configured",
|
||
return_value=False,
|
||
),
|
||
patch.object(tm.upload_post, "cross_post_video") as cross_post,
|
||
patch.object(tm.sm.state, "update_task") as update_task,
|
||
):
|
||
result = tm.start("complete-video", params)
|
||
|
||
self.assertEqual(result["videos"], ["final.mp4"])
|
||
self.assertEqual(result["combined_videos"], ["combined.mp4"])
|
||
self.assertEqual(result["cross_post_results"], None)
|
||
self.assertEqual(params.video_concat_mode, tm.VideoConcatMode.sequential)
|
||
cross_post.assert_not_called()
|
||
update_task.assert_called_with(
|
||
"complete-video",
|
||
state=tm.const.TASK_STATE_COMPLETE,
|
||
progress=100,
|
||
**result,
|
||
)
|
||
|
||
def test_start_marks_pipeline_failures(self):
|
||
"""
|
||
音频、素材和最终视频任一关键产物缺失时都必须进入失败状态,不能把
|
||
不完整任务误报为完成。三个场景复用相同 mock,仅替换故障阶段。
|
||
"""
|
||
failure_cases = {
|
||
"audio": (
|
||
(None, None, None),
|
||
["clip.mp4"],
|
||
(["final.mp4"], ["combined.mp4"], []),
|
||
),
|
||
"materials": (
|
||
("audio.mp3", 5, object()),
|
||
None,
|
||
(["final.mp4"], ["combined.mp4"], []),
|
||
),
|
||
"video": (("audio.mp3", 5, object()), ["clip.mp4"], ([], [], [])),
|
||
}
|
||
|
||
for stage, failure_results in failure_cases.items():
|
||
with self.subTest(stage=stage):
|
||
audio_result, materials_result, videos_result = failure_results
|
||
params = VideoParams(video_subject="Coffee")
|
||
state = MemoryState()
|
||
with (
|
||
patch.object(tm, "generate_script", return_value="generated script"),
|
||
patch.object(tm, "generate_terms", return_value=["coffee"]),
|
||
patch.object(tm, "save_script_data"),
|
||
patch.object(tm, "generate_audio", return_value=audio_result),
|
||
patch.object(tm, "generate_subtitle", return_value="subtitle.srt"),
|
||
patch.object(
|
||
tm,
|
||
"get_video_materials",
|
||
return_value=materials_result,
|
||
),
|
||
patch.object(
|
||
tm,
|
||
"generate_final_videos",
|
||
return_value=videos_result,
|
||
),
|
||
patch.object(tm.sm, "state", state),
|
||
):
|
||
result = tm.start(f"failed-{stage}", params)
|
||
|
||
failed_task = state.get_task(f"failed-{stage}")
|
||
self.assertEqual(result, failed_task)
|
||
self.assertEqual(failed_task["state"], tm.const.TASK_STATE_FAILED)
|
||
self.assertEqual(failed_task["failed_stage"], stage)
|
||
self.assertTrue(failed_task["error"])
|
||
|
||
def test_start_records_unexpected_pipeline_exception(self):
|
||
"""未预期异常也必须结束任务,并向 API 暴露原始异常类型和信息。"""
|
||
params = VideoParams(video_subject="Coffee")
|
||
state = MemoryState()
|
||
|
||
with (
|
||
patch.object(
|
||
tm,
|
||
"generate_script",
|
||
side_effect=RuntimeError("provider connection reset"),
|
||
),
|
||
patch.object(tm.sm, "state", state),
|
||
):
|
||
result = tm.start("unexpected-failure", params)
|
||
|
||
failed_task = state.get_task("unexpected-failure")
|
||
self.assertEqual(result, failed_task)
|
||
self.assertEqual(failed_task["state"], tm.const.TASK_STATE_FAILED)
|
||
self.assertEqual(failed_task["failed_stage"], "pipeline")
|
||
self.assertEqual(
|
||
failed_task["error"],
|
||
"RuntimeError: provider connection reset",
|
||
)
|
||
|
||
def test_start_generates_youtube_metadata_for_each_cross_post(self):
|
||
"""
|
||
自动发布到 YouTube 时只生成一次元数据,但要把同一份字段传给每个
|
||
成片,并在任务结果中保留每次上传成功或失败的独立结果。
|
||
"""
|
||
params = VideoParams(
|
||
video_subject="Coffee",
|
||
video_language="en",
|
||
)
|
||
metadata = {
|
||
"title": "Morning Coffee",
|
||
"caption": "A better morning.",
|
||
"hashtags": ["coffee", "shorts"],
|
||
}
|
||
service = tm.upload_post.upload_post_service
|
||
state = MemoryState()
|
||
|
||
def run_immediately(function, *args):
|
||
future = Future()
|
||
try:
|
||
function(*args)
|
||
except Exception as exc:
|
||
future.set_exception(exc)
|
||
else:
|
||
future.set_result(None)
|
||
return future
|
||
|
||
with (
|
||
patch.object(tm, "generate_script", return_value="generated script"),
|
||
patch.object(tm, "generate_terms", return_value=["coffee"]),
|
||
patch.object(tm, "save_script_data"),
|
||
patch.object(
|
||
tm,
|
||
"generate_audio",
|
||
return_value=("audio.mp3", 5, object()),
|
||
),
|
||
patch.object(tm, "generate_subtitle", return_value="subtitle.srt"),
|
||
patch.object(
|
||
tm,
|
||
"get_video_materials",
|
||
return_value=["clip.mp4"],
|
||
),
|
||
patch.object(
|
||
tm,
|
||
"generate_final_videos",
|
||
return_value=(
|
||
["final-1.mp4", "final-2.mp4"],
|
||
["combined-1.mp4", "combined-2.mp4"],
|
||
[],
|
||
),
|
||
),
|
||
patch.object(service, "is_configured", return_value=True),
|
||
patch.object(service, "auto_upload", True),
|
||
patch.object(service, "platforms", ["youtube"]),
|
||
patch.object(service, "youtube_privacy_status", "unlisted"),
|
||
patch.object(
|
||
tm.llm,
|
||
"generate_social_metadata",
|
||
return_value=metadata,
|
||
) as generate_metadata,
|
||
patch.object(
|
||
tm.upload_post,
|
||
"cross_post_video",
|
||
side_effect=[
|
||
{"success": True},
|
||
{"success": False, "error": "upload failed"},
|
||
],
|
||
) as cross_post,
|
||
patch.object(tm.sm, "state", state),
|
||
patch.object(
|
||
tm._cross_post_executor,
|
||
"submit",
|
||
side_effect=run_immediately,
|
||
),
|
||
):
|
||
result = tm.start("youtube-cross-post", params)
|
||
|
||
generate_metadata.assert_called_once_with(
|
||
video_subject="Coffee",
|
||
video_script="generated script",
|
||
language="en",
|
||
platform="youtube_shorts",
|
||
)
|
||
expected_extra = {
|
||
"youtube_title": "Morning Coffee",
|
||
"youtube_description": "A better morning.",
|
||
"tags": ["coffee", "shorts"],
|
||
"privacyStatus": "unlisted",
|
||
"containsSyntheticMedia": True,
|
||
}
|
||
self.assertEqual(cross_post.call_count, 2)
|
||
for call in cross_post.call_args_list:
|
||
self.assertEqual(call.kwargs["youtube_extra"], expected_extra)
|
||
self.assertEqual(call.kwargs["platforms"], ["youtube"])
|
||
|
||
# start() 返回的是视频完成时的稳定快照;后台发布结果通过任务查询获取。
|
||
self.assertEqual(
|
||
result["cross_post_state"], tm.const.CROSS_POST_STATE_PENDING
|
||
)
|
||
self.assertIsNone(result["cross_post_results"])
|
||
published_task = state.get_task("youtube-cross-post")
|
||
self.assertEqual(published_task["state"], tm.const.TASK_STATE_COMPLETE)
|
||
self.assertEqual(
|
||
published_task["cross_post_state"], tm.const.CROSS_POST_STATE_FAILED
|
||
)
|
||
self.assertEqual(
|
||
published_task["cross_post_results"],
|
||
[
|
||
{"success": True},
|
||
{"success": False, "error": "upload failed"},
|
||
],
|
||
)
|
||
self.assertEqual(published_task["cross_post_error"], "upload failed")
|
||
|
||
def test_start_returns_before_cross_post_worker_runs(self):
|
||
"""视频任务完成时只提交发布工作,不能在生成线程中同步上传。"""
|
||
params = VideoParams(video_subject="Coffee")
|
||
service = tm.upload_post.upload_post_service
|
||
state = MemoryState()
|
||
submitted = []
|
||
|
||
def capture_submission(function, *args):
|
||
submitted.append((function, args))
|
||
return MagicMock(spec=Future)
|
||
|
||
with (
|
||
patch.object(tm, "generate_script", return_value="generated script"),
|
||
patch.object(tm, "generate_terms", return_value=["coffee"]),
|
||
patch.object(tm, "save_script_data"),
|
||
patch.object(
|
||
tm,
|
||
"generate_audio",
|
||
return_value=("audio.mp3", 5, object()),
|
||
),
|
||
patch.object(tm, "generate_subtitle", return_value="subtitle.srt"),
|
||
patch.object(tm, "get_video_materials", return_value=["clip.mp4"]),
|
||
patch.object(
|
||
tm,
|
||
"generate_final_videos",
|
||
return_value=(["final.mp4"], ["combined.mp4"], []),
|
||
),
|
||
patch.object(service, "is_configured", return_value=True),
|
||
patch.object(service, "auto_upload", True),
|
||
patch.object(service, "platforms", ["tiktok"]),
|
||
patch.object(service, "youtube_privacy_status", "private"),
|
||
patch.object(tm.upload_post, "cross_post_video") as cross_post,
|
||
patch.object(tm.sm, "state", state),
|
||
patch.object(
|
||
tm._cross_post_executor,
|
||
"submit",
|
||
side_effect=capture_submission,
|
||
) as submit,
|
||
):
|
||
result = tm.start("deferred-cross-post", params)
|
||
|
||
submit.assert_called_once()
|
||
cross_post.assert_not_called()
|
||
self.assertEqual(result["videos"], ["final.mp4"])
|
||
self.assertEqual(result["cross_post_state"], tm.const.CROSS_POST_STATE_PENDING)
|
||
completed_task = state.get_task("deferred-cross-post")
|
||
self.assertEqual(completed_task["state"], tm.const.TASK_STATE_COMPLETE)
|
||
self.assertEqual(completed_task["progress"], 100)
|
||
|
||
worker, worker_args = submitted[0]
|
||
with (
|
||
patch.object(tm.sm, "state", state),
|
||
patch.object(
|
||
tm.upload_post,
|
||
"cross_post_video",
|
||
return_value={"success": True, "request_id": "upload-1"},
|
||
),
|
||
):
|
||
worker(*worker_args)
|
||
|
||
published_task = state.get_task("deferred-cross-post")
|
||
self.assertEqual(published_task["videos"], ["final.mp4"])
|
||
self.assertEqual(
|
||
published_task["cross_post_state"], tm.const.CROSS_POST_STATE_COMPLETE
|
||
)
|
||
|
||
def test_cross_post_worker_failure_does_not_change_video_completion(self):
|
||
"""发布线程异常只能更新发布状态,不能破坏已完成的视频结果。"""
|
||
state = MemoryState()
|
||
state.update_task(
|
||
"cross-post-worker-failure",
|
||
state=tm.const.TASK_STATE_COMPLETE,
|
||
progress=100,
|
||
videos=["final.mp4"],
|
||
cross_post_state=tm.const.CROSS_POST_STATE_PENDING,
|
||
)
|
||
|
||
with (
|
||
patch.object(tm.sm, "state", state),
|
||
patch.object(
|
||
tm.llm,
|
||
"generate_social_metadata",
|
||
side_effect=RuntimeError("metadata provider unavailable"),
|
||
),
|
||
patch.object(tm.upload_post, "cross_post_video") as cross_post,
|
||
):
|
||
tm._run_cross_post(
|
||
"cross-post-worker-failure",
|
||
("final.mp4",),
|
||
"Coffee",
|
||
"A short coffee story.",
|
||
"en",
|
||
("youtube",),
|
||
"private",
|
||
)
|
||
|
||
cross_post.assert_not_called()
|
||
task = state.get_task("cross-post-worker-failure")
|
||
self.assertEqual(task["state"], tm.const.TASK_STATE_COMPLETE)
|
||
self.assertEqual(task["videos"], ["final.mp4"])
|
||
self.assertEqual(task["cross_post_state"], tm.const.CROSS_POST_STATE_FAILED)
|
||
self.assertIn("metadata provider unavailable", task["cross_post_error"])
|
||
|
||
def test_start_returns_cross_post_scheduling_failure(self):
|
||
"""同步调度失败必须同时体现在任务状态和 start() 返回快照中。"""
|
||
params = VideoParams(video_subject="Coffee")
|
||
service = tm.upload_post.upload_post_service
|
||
state = MemoryState()
|
||
|
||
with (
|
||
patch.object(tm, "generate_script", return_value="generated script"),
|
||
patch.object(tm, "generate_terms", return_value=["coffee"]),
|
||
patch.object(tm, "save_script_data"),
|
||
patch.object(
|
||
tm,
|
||
"generate_audio",
|
||
return_value=("audio.mp3", 5, object()),
|
||
),
|
||
patch.object(tm, "generate_subtitle", return_value="subtitle.srt"),
|
||
patch.object(tm, "get_video_materials", return_value=["clip.mp4"]),
|
||
patch.object(
|
||
tm,
|
||
"generate_final_videos",
|
||
return_value=(["final.mp4"], ["combined.mp4"], []),
|
||
),
|
||
patch.object(service, "is_configured", return_value=True),
|
||
patch.object(service, "auto_upload", True),
|
||
patch.object(service, "platforms", ["tiktok"]),
|
||
patch.object(service, "youtube_privacy_status", "private"),
|
||
patch.object(tm.sm, "state", state),
|
||
patch.object(tm._cross_post_slots, "acquire", return_value=False),
|
||
patch.object(tm._cross_post_executor, "submit") as submit,
|
||
):
|
||
result = tm.start("cross-post-queue-full-result", params)
|
||
|
||
submit.assert_not_called()
|
||
self.assertEqual(
|
||
result["cross_post_state"], tm.const.CROSS_POST_STATE_FAILED
|
||
)
|
||
self.assertIn("queue is full", result["cross_post_error"])
|
||
persisted_task = state.get_task("cross-post-queue-full-result")
|
||
self.assertEqual(
|
||
persisted_task["cross_post_state"], tm.const.CROSS_POST_STATE_FAILED
|
||
)
|
||
self.assertEqual(
|
||
persisted_task["cross_post_error"],
|
||
result["cross_post_error"],
|
||
)
|
||
|
||
def test_cross_post_schedule_failure_is_recorded_separately(self):
|
||
"""线程池拒绝新任务时应保留成片,并提供可查询的发布错误。"""
|
||
state = MemoryState()
|
||
slots = MagicMock()
|
||
slots.acquire.return_value = True
|
||
state.update_task(
|
||
"cross-post-schedule-failure",
|
||
state=tm.const.TASK_STATE_COMPLETE,
|
||
progress=100,
|
||
videos=["final.mp4"],
|
||
cross_post_state=tm.const.CROSS_POST_STATE_PENDING,
|
||
)
|
||
|
||
with (
|
||
patch.object(tm.sm, "state", state),
|
||
patch.object(tm, "_cross_post_slots", slots),
|
||
patch.object(
|
||
tm._cross_post_executor,
|
||
"submit",
|
||
side_effect=RuntimeError("executor is shutting down"),
|
||
),
|
||
):
|
||
scheduling_error = tm._schedule_cross_post(
|
||
task_id="cross-post-schedule-failure",
|
||
video_paths=["final.mp4"],
|
||
params=VideoParams(video_subject="Coffee"),
|
||
video_script="A short coffee story.",
|
||
platforms=["tiktok"],
|
||
youtube_privacy_status="private",
|
||
)
|
||
|
||
slots.release.assert_called_once_with()
|
||
self.assertIn("executor is shutting down", scheduling_error)
|
||
task = state.get_task("cross-post-schedule-failure")
|
||
self.assertEqual(task["state"], tm.const.TASK_STATE_COMPLETE)
|
||
self.assertEqual(task["videos"], ["final.mp4"])
|
||
self.assertEqual(task["cross_post_state"], tm.const.CROSS_POST_STATE_FAILED)
|
||
self.assertIn("executor is shutting down", task["cross_post_error"])
|
||
|
||
def test_cross_post_worker_always_releases_queue_slot(self):
|
||
"""发布工作异常退出时也必须归还容量,避免后续发布永久被拒绝。"""
|
||
slots = MagicMock()
|
||
state = MemoryState()
|
||
state.update_task(
|
||
"task-id",
|
||
state=tm.const.TASK_STATE_COMPLETE,
|
||
progress=100,
|
||
cross_post_state=tm.const.CROSS_POST_STATE_PENDING,
|
||
)
|
||
|
||
with (
|
||
patch.object(tm, "_cross_post_slots", slots),
|
||
patch.object(tm.sm, "state", state),
|
||
patch.object(
|
||
tm,
|
||
"_run_cross_post",
|
||
side_effect=RuntimeError("worker crashed"),
|
||
),
|
||
):
|
||
tm._run_cross_post_with_slot("task-id")
|
||
|
||
slots.release.assert_called_once_with()
|
||
task = state.get_task("task-id")
|
||
self.assertEqual(task["cross_post_state"], tm.const.CROSS_POST_STATE_FAILED)
|
||
self.assertIn("worker crashed", task["cross_post_error"])
|
||
|
||
def test_cross_post_state_backend_failure_is_logged_and_skips_upload(self):
|
||
"""首次状态写入失败时不能静默退出,也不能继续消耗发布额度。"""
|
||
state = MagicMock()
|
||
state.patch_task.side_effect = RuntimeError("redis unavailable")
|
||
|
||
with (
|
||
patch.object(tm.sm, "state", state),
|
||
patch.object(tm.upload_post, "cross_post_video") as cross_post,
|
||
patch.object(tm.logger, "exception") as log_exception,
|
||
patch.object(tm.time, "sleep") as sleep,
|
||
):
|
||
tm._run_cross_post(
|
||
"state-backend-failure",
|
||
("final.mp4",),
|
||
"Coffee",
|
||
"A short coffee story.",
|
||
"en",
|
||
("tiktok",),
|
||
"private",
|
||
)
|
||
|
||
cross_post.assert_not_called()
|
||
self.assertEqual(state.patch_task.call_count, 6)
|
||
self.assertEqual(sleep.call_count, 4)
|
||
self.assertEqual(log_exception.call_count, 2)
|
||
self.assertTrue(
|
||
all("redis unavailable" in call.args[0] for call in log_exception.call_args_list)
|
||
)
|
||
|
||
def test_cross_post_state_update_retries_transient_backend_failure(self):
|
||
"""状态后端短暂失败一次后应继续发布,并最终保存完成状态。"""
|
||
|
||
class FlakyMemoryState(MemoryState):
|
||
def __init__(self):
|
||
super().__init__()
|
||
self.patch_calls = 0
|
||
|
||
def patch_task(self, task_id, **kwargs):
|
||
self.patch_calls += 1
|
||
if self.patch_calls == 1:
|
||
raise RuntimeError("temporary redis outage")
|
||
return super().patch_task(task_id, **kwargs)
|
||
|
||
state = FlakyMemoryState()
|
||
state.update_task(
|
||
"transient-state-failure",
|
||
state=tm.const.TASK_STATE_COMPLETE,
|
||
progress=100,
|
||
videos=["final.mp4"],
|
||
cross_post_state=tm.const.CROSS_POST_STATE_PENDING,
|
||
)
|
||
|
||
with (
|
||
patch.object(tm.sm, "state", state),
|
||
patch.object(
|
||
tm.upload_post,
|
||
"cross_post_video",
|
||
return_value={"success": True, "request_id": "upload-1"},
|
||
) as cross_post,
|
||
patch.object(tm.time, "sleep") as sleep,
|
||
):
|
||
tm._run_cross_post(
|
||
"transient-state-failure",
|
||
("final.mp4",),
|
||
"Coffee",
|
||
"A short coffee story.",
|
||
"en",
|
||
("tiktok",),
|
||
"private",
|
||
)
|
||
|
||
sleep.assert_called_once_with(tm._CROSS_POST_STATE_RETRY_DELAY_SECONDS)
|
||
cross_post.assert_called_once()
|
||
task = state.get_task("transient-state-failure")
|
||
self.assertEqual(task["cross_post_state"], tm.const.CROSS_POST_STATE_COMPLETE)
|
||
self.assertIsNone(task["cross_post_error"])
|
||
|
||
def test_recover_interrupted_cross_posts_preserves_active_future(self):
|
||
"""启动恢复只处理遗留状态,当前进程仍持有的发布任务不能被误伤。"""
|
||
state = MemoryState()
|
||
for task_id in (
|
||
"stale-pending",
|
||
"active-processing",
|
||
"inactive-current-owner",
|
||
"remote-processing",
|
||
"already-complete",
|
||
):
|
||
cross_post_state = {
|
||
"stale-pending": tm.const.CROSS_POST_STATE_PENDING,
|
||
"active-processing": tm.const.CROSS_POST_STATE_PROCESSING,
|
||
"inactive-current-owner": tm.const.CROSS_POST_STATE_PROCESSING,
|
||
"remote-processing": tm.const.CROSS_POST_STATE_PROCESSING,
|
||
"already-complete": tm.const.CROSS_POST_STATE_COMPLETE,
|
||
}[task_id]
|
||
state.update_task(
|
||
task_id,
|
||
state=tm.const.TASK_STATE_COMPLETE,
|
||
progress=100,
|
||
videos=["final.mp4"],
|
||
cross_post_state=cross_post_state,
|
||
cross_post_owner=(
|
||
"another-host:123:remote"
|
||
if task_id == "remote-processing"
|
||
else (
|
||
tm._cross_post_process_owner
|
||
if task_id == "inactive-current-owner"
|
||
else None
|
||
)
|
||
),
|
||
)
|
||
|
||
active_future = Future()
|
||
tm._register_cross_post_future("active-processing", active_future)
|
||
with patch.object(tm.sm, "state", state):
|
||
recovered = tm.recover_interrupted_cross_posts(page_size=1)
|
||
|
||
self.assertEqual(recovered, 2)
|
||
stale_task = state.get_task("stale-pending")
|
||
self.assertEqual(stale_task["cross_post_state"], tm.const.CROSS_POST_STATE_FAILED)
|
||
self.assertEqual(stale_task["cross_post_error"], tm._INTERRUPTED_CROSS_POST_ERROR)
|
||
self.assertEqual(
|
||
state.get_task("active-processing")["cross_post_state"],
|
||
tm.const.CROSS_POST_STATE_PROCESSING,
|
||
)
|
||
self.assertEqual(
|
||
state.get_task("inactive-current-owner")["cross_post_state"],
|
||
tm.const.CROSS_POST_STATE_FAILED,
|
||
)
|
||
self.assertEqual(
|
||
state.get_task("remote-processing")["cross_post_state"],
|
||
tm.const.CROSS_POST_STATE_PROCESSING,
|
||
)
|
||
self.assertEqual(
|
||
state.get_task("already-complete")["cross_post_state"],
|
||
tm.const.CROSS_POST_STATE_COMPLETE,
|
||
)
|
||
active_future.set_result(None)
|
||
|
||
def test_recover_interrupted_cross_posts_uses_a_single_id_snapshot(self):
|
||
"""
|
||
issue #1408 的恢复场景:不能靠多次独立 SCAN 分页推进恢复逻辑。
|
||
|
||
这里直接验证新实现只调用一次 `get_all_task_ids`(不再按页重新
|
||
查询 Redis),并且快照里某个任务在读取状态前被删除时(`get_task`
|
||
返回 None)只是被跳过,不会影响其它任务的恢复,也不会抛异常。
|
||
"""
|
||
state = MagicMock()
|
||
state.get_all_task_ids.return_value = ["stale-a", "deleted-b", "stale-c"]
|
||
|
||
tasks = {
|
||
"stale-a": {
|
||
"task_id": "stale-a",
|
||
"cross_post_state": tm.const.CROSS_POST_STATE_PENDING,
|
||
"cross_post_owner": None,
|
||
},
|
||
"deleted-b": None,
|
||
"stale-c": {
|
||
"task_id": "stale-c",
|
||
"cross_post_state": tm.const.CROSS_POST_STATE_PROCESSING,
|
||
"cross_post_owner": None,
|
||
},
|
||
}
|
||
state.get_task.side_effect = lambda task_id: tasks[task_id]
|
||
|
||
patched = []
|
||
|
||
def _fake_patch(task_id, **kwargs):
|
||
patched.append(task_id)
|
||
return True
|
||
|
||
with (
|
||
patch.object(tm.sm, "state", state),
|
||
patch.object(tm, "_patch_cross_post_state", side_effect=_fake_patch),
|
||
):
|
||
recovered = tm.recover_interrupted_cross_posts()
|
||
|
||
self.assertEqual(recovered, 2)
|
||
self.assertEqual(sorted(patched), ["stale-a", "stale-c"])
|
||
state.get_all_task_ids.assert_called_once_with()
|
||
|
||
def test_cross_post_owner_uses_future_registry_for_current_process(self):
|
||
"""当前进程无活动 Future 时,同 PID 的新旧 owner 都应视为中断。"""
|
||
stale_owner = f"{tm.socket.gethostname()}:{tm.os.getpid()}:old-instance"
|
||
|
||
self.assertFalse(tm._is_cross_post_owner_alive(stale_owner))
|
||
self.assertFalse(tm._is_cross_post_owner_alive(tm._cross_post_process_owner))
|
||
|
||
def test_cross_post_owner_detection_handles_process_boundaries(self):
|
||
"""所有者探测应覆盖旧记录、其它主机和本机进程异常边界。"""
|
||
hostname = tm.socket.gethostname()
|
||
|
||
self.assertFalse(tm._is_cross_post_owner_alive(None))
|
||
self.assertFalse(tm._is_cross_post_owner_alive("invalid-owner"))
|
||
self.assertTrue(tm._is_cross_post_owner_alive("another-host:123:instance"))
|
||
|
||
with (
|
||
patch.object(tm.os, "name", "posix"),
|
||
patch.object(tm.os, "kill", side_effect=ProcessLookupError),
|
||
):
|
||
self.assertFalse(
|
||
tm._is_cross_post_owner_alive(f"{hostname}:987654:dead-instance")
|
||
)
|
||
with (
|
||
patch.object(tm.os, "name", "posix"),
|
||
patch.object(tm.os, "kill", side_effect=PermissionError),
|
||
):
|
||
self.assertTrue(
|
||
tm._is_cross_post_owner_alive(f"{hostname}:987654:restricted")
|
||
)
|
||
with (
|
||
patch.object(tm.os, "name", "posix"),
|
||
patch.object(tm.os, "kill", side_effect=OSError("inspection failed")),
|
||
patch.object(tm.logger, "warning") as log_warning,
|
||
):
|
||
self.assertTrue(
|
||
tm._is_cross_post_owner_alive(f"{hostname}:987654:unknown")
|
||
)
|
||
self.assertIn("inspection failed", log_warning.call_args.args[0])
|
||
|
||
with (
|
||
patch.object(tm.os, "name", "nt"),
|
||
patch.object(tm, "_is_windows_process_alive", return_value=True) as probe,
|
||
):
|
||
self.assertTrue(
|
||
tm._is_cross_post_owner_alive(f"{hostname}:987654:windows")
|
||
)
|
||
probe.assert_called_once_with(987654)
|
||
|
||
@unittest.skipUnless(os.name == "nt", "Windows process API test")
|
||
def test_windows_process_probe_is_read_only_and_detects_liveness(self):
|
||
"""Windows CI 应真实验证只读进程探测,不允许回退到 os.kill。"""
|
||
self.assertTrue(tm._is_windows_process_alive(os.getpid()))
|
||
self.assertFalse(tm._is_windows_process_alive(2_147_483_647))
|
||
|
||
def test_cross_post_terminal_check_converts_active_state_to_failure(self):
|
||
"""worker 已结束但状态仍活动时,最终回调必须补写失败终态。"""
|
||
state = MemoryState()
|
||
state.update_task(
|
||
"unfinished-cross-post",
|
||
state=tm.const.TASK_STATE_COMPLETE,
|
||
progress=100,
|
||
videos=["final.mp4"],
|
||
cross_post_state=tm.const.CROSS_POST_STATE_PROCESSING,
|
||
)
|
||
|
||
with patch.object(tm.sm, "state", state):
|
||
tm._ensure_cross_post_terminal_state("unfinished-cross-post")
|
||
|
||
task = state.get_task("unfinished-cross-post")
|
||
self.assertEqual(task["videos"], ["final.mp4"])
|
||
self.assertEqual(task["cross_post_state"], tm.const.CROSS_POST_STATE_FAILED)
|
||
self.assertIn("without persisting", task["cross_post_error"])
|
||
|
||
def test_cross_post_recovery_reports_state_backend_failure(self):
|
||
"""启动恢复读取状态失败时应返回 None,允许 WebUI 后续 rerun 重试。"""
|
||
state = MagicMock()
|
||
state.get_all_task_ids.side_effect = RuntimeError("redis unavailable")
|
||
|
||
with (
|
||
patch.object(tm.sm, "state", state),
|
||
patch.object(tm.logger, "exception") as log_exception,
|
||
):
|
||
recovered = tm.recover_interrupted_cross_posts()
|
||
|
||
self.assertIsNone(recovered)
|
||
self.assertIn("redis unavailable", log_exception.call_args.args[0])
|
||
|
||
def test_cancelled_cross_post_future_releases_slot_and_records_failure(self):
|
||
"""排队 Future 被取消时也必须释放容量并写入失败终态。"""
|
||
state = MemoryState()
|
||
state.update_task(
|
||
"cancelled-cross-post",
|
||
state=tm.const.TASK_STATE_COMPLETE,
|
||
progress=100,
|
||
cross_post_state=tm.const.CROSS_POST_STATE_PENDING,
|
||
)
|
||
slots = MagicMock()
|
||
future = Future()
|
||
tm._register_cross_post_future("cancelled-cross-post", future)
|
||
self.assertTrue(future.cancel())
|
||
|
||
with (
|
||
patch.object(tm.sm, "state", state),
|
||
patch.object(tm, "_cross_post_slots", slots),
|
||
):
|
||
tm._finalize_cross_post_future("cancelled-cross-post", future)
|
||
|
||
slots.release.assert_called_once_with()
|
||
self.assertFalse(tm._is_cross_post_active_in_process("cancelled-cross-post"))
|
||
task = state.get_task("cancelled-cross-post")
|
||
self.assertEqual(task["cross_post_state"], tm.const.CROSS_POST_STATE_FAILED)
|
||
self.assertIn("cancelled", task["cross_post_error"])
|
||
|
||
@unittest.skipUnless(
|
||
os.getenv("MPT_TEST_REDIS_HOST"),
|
||
"MPT_TEST_REDIS_HOST not set",
|
||
)
|
||
def test_real_redis_recovers_interrupted_cross_post_state(self):
|
||
"""真实 Redis 中的遗留发布状态必须在恢复后保留视频并进入失败终态。"""
|
||
state = RedisState(
|
||
host=os.environ["MPT_TEST_REDIS_HOST"],
|
||
port=int(os.getenv("MPT_TEST_REDIS_PORT", "6379")),
|
||
db=int(os.getenv("MPT_TEST_REDIS_DB", "15")),
|
||
)
|
||
task_id = f"ci-cross-post-recovery-{uuid4()}"
|
||
state.update_task(
|
||
task_id,
|
||
state=tm.const.TASK_STATE_COMPLETE,
|
||
progress=100,
|
||
videos=["final.mp4"],
|
||
cross_post_state=tm.const.CROSS_POST_STATE_PROCESSING,
|
||
cross_post_owner="",
|
||
)
|
||
|
||
try:
|
||
with patch.object(tm.sm, "state", state):
|
||
recovered = tm.recover_interrupted_cross_posts(page_size=10)
|
||
|
||
self.assertGreaterEqual(recovered, 1)
|
||
task = state.get_task(task_id)
|
||
self.assertEqual(task["videos"], ["final.mp4"])
|
||
self.assertEqual(
|
||
task["cross_post_state"], tm.const.CROSS_POST_STATE_FAILED
|
||
)
|
||
self.assertEqual(task["cross_post_error"], tm._INTERRUPTED_CROSS_POST_ERROR)
|
||
finally:
|
||
state.delete_task(task_id)
|
||
|
||
def test_cross_post_future_exception_is_observed(self):
|
||
"""线程池自身抛出的异常必须进入日志,不能留在无人读取的 Future 中。"""
|
||
future = Future()
|
||
future.set_exception(RuntimeError("executor worker failed"))
|
||
|
||
with patch.object(tm.logger, "error") as log_error:
|
||
tm._finalize_cross_post_future("future-failure", future)
|
||
|
||
log_error.assert_called_once()
|
||
self.assertIn("executor worker failed", log_error.call_args.args[0])
|
||
|
||
def test_cross_post_queue_full_rejects_only_publishing(self):
|
||
"""发布队列满载时必须保留成片,并且不能继续向线程池提交任务。"""
|
||
state = MemoryState()
|
||
state.update_task(
|
||
"cross-post-queue-full",
|
||
state=tm.const.TASK_STATE_COMPLETE,
|
||
progress=100,
|
||
videos=["final.mp4"],
|
||
cross_post_state=tm.const.CROSS_POST_STATE_PENDING,
|
||
)
|
||
|
||
with (
|
||
patch.object(tm.sm, "state", state),
|
||
patch.object(
|
||
tm._cross_post_slots,
|
||
"acquire",
|
||
return_value=False,
|
||
),
|
||
patch.object(tm._cross_post_executor, "submit") as submit,
|
||
):
|
||
scheduling_error = tm._schedule_cross_post(
|
||
task_id="cross-post-queue-full",
|
||
video_paths=["final.mp4"],
|
||
params=VideoParams(video_subject="Coffee"),
|
||
video_script="A short coffee story.",
|
||
platforms=["tiktok"],
|
||
youtube_privacy_status="private",
|
||
)
|
||
|
||
submit.assert_not_called()
|
||
self.assertIn("queue is full", scheduling_error)
|
||
task = state.get_task("cross-post-queue-full")
|
||
self.assertEqual(task["state"], tm.const.TASK_STATE_COMPLETE)
|
||
self.assertEqual(task["videos"], ["final.mp4"])
|
||
self.assertEqual(task["cross_post_state"], tm.const.CROSS_POST_STATE_FAILED)
|
||
self.assertIn("queue is full", task["cross_post_error"])
|
||
|
||
@unittest.skipUnless(
|
||
RUN_INTEGRATION_TESTS,
|
||
"MPT_RUN_INTEGRATION_TESTS not set",
|
||
)
|
||
def test_task_local_materials(self):
|
||
task_id = "00000000-0000-0000-0000-000000000000"
|
||
video_materials=[]
|
||
for i in range(1, 4):
|
||
video_materials.append(MaterialInfo(
|
||
provider="local",
|
||
url=os.path.join(resources_dir, f"{i}.png"),
|
||
duration=0
|
||
))
|
||
|
||
params = VideoParams(
|
||
video_subject="金钱的作用",
|
||
video_script="金钱不仅是交换媒介,更是社会资源的分配工具。它能满足基本生存需求,如食物和住房,也能提供教育、医疗等提升生活品质的机会。拥有足够的金钱意味着更多选择权,比如职业自由或创业可能。但金钱的作用也有边界,它无法直接购买幸福、健康或真诚的人际关系。过度追逐财富可能导致价值观扭曲,忽视精神层面的需求。理想的状态是理性看待金钱,将其作为实现目标的工具而非终极目的。",
|
||
video_terms="money importance, wealth and society, financial freedom, money and happiness, role of money",
|
||
video_aspect="9:16",
|
||
video_concat_mode="random",
|
||
video_transition_mode="None",
|
||
video_clip_duration=3,
|
||
video_count=1,
|
||
video_source="local",
|
||
video_materials=video_materials,
|
||
video_language="",
|
||
voice_name="zh-CN-XiaoxiaoNeural-Female",
|
||
voice_volume=1.0,
|
||
voice_rate=1.0,
|
||
bgm_type="random",
|
||
bgm_file="",
|
||
bgm_volume=0.2,
|
||
subtitle_enabled=True,
|
||
subtitle_position="bottom",
|
||
custom_position=70.0,
|
||
font_name="MicrosoftYaHeiBold.ttc",
|
||
text_fore_color="#FFFFFF",
|
||
text_background_color=True,
|
||
font_size=60,
|
||
stroke_color="#000000",
|
||
stroke_width=1.5,
|
||
n_threads=2,
|
||
paragraph_number=1
|
||
)
|
||
result = tm.start(task_id=task_id, params=params)
|
||
print(result)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
unittest.main()
|