From 41a855d4003f5b9bf8f1d3d0709989afdeb05578 Mon Sep 17 00:00:00 2001 From: claude_dev Date: Sat, 11 Jul 2026 14:11:49 +0800 Subject: [PATCH] =?UTF-8?q?test(backtest):=20=E4=BF=AE=E5=A4=8Dtest=5Fcta?= =?UTF-8?q?=5Fengine=E7=9A=84sys.modules=E5=85=A8=E5=B1=80=E6=B1=A1?= =?UTF-8?q?=E6=9F=93=E2=80=94=E5=8A=A0=E6=A8=A1=E5=9D=97=E7=BA=A7=E8=BF=98?= =?UTF-8?q?=E5=8E=9Ffixture(=E6=B6=889=E4=B8=AA=E7=BA=A7=E8=81=94=E5=A4=B1?= =?UTF-8?q?=E8=B4=A5)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/backtest/test_cta_engine.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/tests/backtest/test_cta_engine.py b/tests/backtest/test_cta_engine.py index 468de11..7ca012c 100644 --- a/tests/backtest/test_cta_engine.py +++ b/tests/backtest/test_cta_engine.py @@ -2,6 +2,16 @@ # Mock vnpy and tzlocal modules before importing anything that depends on them import sys from unittest.mock import MagicMock + +# Mock vnpy/tzlocal/empyrical BEFORE importing cta_engine (which imports them at top). +# Save originals so we can RESTORE after this module — otherwise the global sys.modules +# pollution breaks every later test that imports real vnpy/empyrical (datareader/spike/factor/metrics). +_MOCKED_KEYS = ( + "tzlocal", "vnpy.trader.setting", "vnpy.trader.constant", "vnpy.trader.object", + "vnpy.trader.database", "vnpy_ctastrategy.backtesting", "empyrical", +) +_SAVED_MODULES = {k: sys.modules.get(k) for k in _MOCKED_KEYS} + mock_tzlocal = MagicMock() mock_tzlocal.get_localzone_name = MagicMock(return_value="UTC") sys.modules["tzlocal"] = mock_tzlocal @@ -21,6 +31,22 @@ import pandas as pd from sanguo_backtest.cta_engine import run_cta_backtest +@pytest.fixture(scope="module", autouse=True) +def _restore_modules_after(): + """Restore sys.modules after this module's tests, so downstream tests import the + REAL vnpy/empyrical instead of the mocks we installed above. Also drop cta_engine/ + metrics from the module cache (they were imported while mocks were active) so they + re-import fresh with real dependencies.""" + yield + for cached in ("sanguo_backtest.cta_engine", "sanguo_backtest.metrics"): + sys.modules.pop(cached, None) + for k, orig in _SAVED_MODULES.items(): + if orig is None: + sys.modules.pop(k, None) + else: + sys.modules[k] = orig + + class TestRunCtaBacktest: """Test suite for run_cta_backtest function."""