From 87dfed2f8a0ab84a0f39af452c6558d17ee1bdfe Mon Sep 17 00:00:00 2001 From: saas-backend Date: Tue, 22 Sep 2026 01:10:22 +0800 Subject: [PATCH] =?UTF-8?q?test:=20=E4=BF=AE=E5=A4=8D=E5=8F=96=E6=B6=88?= =?UTF-8?q?=E9=93=BE=E8=B7=AF=E6=B5=8B=E8=AF=95=E5=9C=A8=E5=85=A8=E9=87=8F?= =?UTF-8?q?=E8=B7=91=E6=97=B6=E5=8F=97=20sys.modules=20=E6=B1=A1=E6=9F=93?= =?UTF-8?q?=E5=A4=B1=E8=B4=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 全量跑时其他测试可能把 app.services.gpu_lipsync_service 换成 MagicMock, 导致任务函数内 from...import 拿到污染对象。改用 monkeypatch.setitem 直接替换 sys.modules 模块项,并 patch _get_db_session 绕开双 import 分支, 确保测试在任何污染场景下都稳定。 --- tests/unit/test_lipsync_gpu_async_task.py | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) 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)