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."""