Skip to content

Commit

Permalink
Dynamically import hyperopt modules
Browse files Browse the repository at this point in the history
  • Loading branch information
xmatthias committed Sep 25, 2019
1 parent 0102413 commit 27cc73f
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 5 deletions.
12 changes: 7 additions & 5 deletions freqtrade/optimize/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import logging
from typing import Any, Dict

from filelock import FileLock, Timeout

from freqtrade import DependencyException, constants
from freqtrade import DependencyException, constants, OperationalException
from freqtrade.state import RunMode
from freqtrade.utils import setup_utils_configuration

Expand Down Expand Up @@ -53,8 +51,12 @@ def start_hyperopt(args: Dict[str, Any]) -> None:
:return: None
"""
# Import here to avoid loading hyperopt module when it's not used
from freqtrade.optimize.hyperopt import Hyperopt

try:
from filelock import FileLock, Timeout
from freqtrade.optimize.hyperopt import Hyperopt
except ImportError as e:
raise OperationalException(
f"{e}. Please ensure that the hyperopt dependencies are installed.") from e
# Initialize configuration
config = setup_configuration(args, RunMode.HYPEROPT)

Expand Down
31 changes: 31 additions & 0 deletions tests/optimize/test_hyperopt.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,37 @@ def test_hyperoptlossresolver_wrongname(mocker, default_conf, caplog) -> None:
HyperOptLossResolver(default_conf, ).hyperopt


def test_start_not_installed(mocker, default_conf, caplog) -> 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)

args = [
'--config', 'config.json',
'hyperopt',
'--epochs', '5'
]
args = get_args(args)

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()
patched_configuration_load_config_file(mocker, default_conf)
Expand Down

0 comments on commit 27cc73f

Please sign in to comment.