diff --git a/tests/unit/test_lipsync_gpu_async_task.py b/tests/unit/test_lipsync_gpu_async_task.py index 2ab3a9404..00b8ece1f 100644 --- a/tests/unit/test_lipsync_gpu_async_task.py +++ b/tests/unit/test_lipsync_gpu_async_task.py @@ -263,21 +263,21 @@ def test_cancelled_gpu_task_does_not_fallback_mediakit(monkeypatch): fake_gpu_svc = MagicMock() fake_gpu_svc.wait_for_result.return_value = gpu_task + gpu_service_cls = MagicMock(return_value=fake_gpu_svc) fake_db = MagicMock() fake_db.query.return_value.filter_by.return_value.first.return_value = job - # wait_for_result 直接被 mock 到 gpu_svc,这里仅备查 - monkeypatch.setattr( - "app.services.gpu_lipsync_service.GpuLipsyncService", - MagicMock(return_value=fake_gpu_svc), - ) - session_factory = MagicMock() - session_factory.return_value = fake_db - # _get_db_session 优先用 worker_app.db(pytest 环境可导入),两个都 patch - monkeypatch.setattr("worker_app.db.SessionLocal", session_factory) - monkeypatch.setattr("app.db.SessionLocal", session_factory) - monkeypatch.setattr("app.tasks.lipsync_gpu.logger", MagicMock()) + # 直接替换 sys.modules 里的 gpu_lipsync_service 模块(全量跑时它可能已被 + # 其他测试换成 MagicMock),保证任务函数内 from...import 一定拿到我们的类; + # 并替换 _get_db_session 绕开 worker_app / app.db 两条 import 分支。 + import sys + from types import SimpleNamespace + + fake_mod = SimpleNamespace(GpuLipsyncService=gpu_service_cls) + monkeypatch.setitem(sys.modules, "app.services.gpu_lipsync_service", fake_mod) + monkeypatch.setattr(task_mod, "_get_db_session", lambda: fake_db) + monkeypatch.setattr(task_mod, "logger", MagicMock()) task_mod.lipsync_gpu_process_async.run("job-1", "u1", "gpu-task-1") @@ -285,3 +285,4 @@ def test_cancelled_gpu_task_does_not_fallback_mediakit(monkeypatch): assert not str(job.mediakit_task_id).startswith("mk-") fake_db.commit.assert_called() fake_gpu_svc.wait_for_result.assert_called_once() + gpu_service_cls.assert_called_once_with(fake_db)