diff --git a/tests/conftest.py b/tests/conftest.py index 8a5ba6683..6a0a74b5b 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1054,3 +1054,24 @@ def rpc_balance(): def testdatadir() -> Path: """Return the path where testdata files are stored""" return (Path(__file__).parent / "testdata").resolve() + + +@pytest.fixture(scope="function") +def import_fails() -> None: + # Source of this test-method: + # https://stackoverflow.com/questions/2481511/mocking-importerror-in-python + import builtins + realimport = builtins.__import__ + + def mockedimport(name, *args, **kwargs): + if name in ["filelock"]: + raise ImportError(f"No module named '{name}'") + return realimport(name, *args, **kwargs) + + builtins.__import__ = mockedimport + + # Run test - then cleanup + yield + + # restore previous importfunction + builtins.__import__ = realimport diff --git a/tests/optimize/test_hyperopt.py b/tests/optimize/test_hyperopt.py index 8ceea6caa..55f94f572 100644 --- a/tests/optimize/test_hyperopt.py +++ b/tests/optimize/test_hyperopt.py @@ -190,19 +190,9 @@ def test_hyperoptlossresolver_wrongname(mocker, default_conf, caplog) -> None: HyperOptLossResolver(default_conf, ).hyperopt -def test_start_not_installed(mocker, default_conf, caplog) -> None: +def test_start_not_installed(mocker, default_conf, caplog, import_fails) -> None: start_mock = MagicMock() patched_configuration_load_config_file(mocker, default_conf) - # Source of this test-method: https://stackoverflow.com/questions/2481511/mocking-importerror-in-python - import builtins - realimport = builtins.__import__ - - def mockedimport(name, *args, **kwargs): - if name == "filelock": - raise ImportError("No module named 'filelock'") - return realimport(name, *args, **kwargs) - - builtins.__import__ = mockedimport mocker.patch('freqtrade.optimize.hyperopt.Hyperopt.start', start_mock) patch_exchange(mocker) @@ -217,9 +207,6 @@ def test_start_not_installed(mocker, default_conf, caplog) -> None: with pytest.raises(OperationalException, match=r"Please ensure that the hyperopt dependencies"): start_hyperopt(args) - # restore previous importfunction - builtins.__import__ = realimport - def test_start(mocker, default_conf, caplog) -> None: start_mock = MagicMock()