1
0
mirror of https://github.com/home-assistant/core.git synced 2025-12-24 12:59:34 +00:00

Use a future for mock coro (#34989)

This commit is contained in:
Paulus Schoutsen
2020-04-30 16:31:00 -07:00
committed by GitHub
parent ba7391528f
commit 76f392476b
26 changed files with 154 additions and 262 deletions

View File

@@ -744,16 +744,12 @@ def patch_yaml_files(files_dict, endswith=True):
def mock_coro(return_value=None, exception=None):
"""Return a coro that returns a value or raise an exception."""
return mock_coro_func(return_value, exception)()
def mock_coro_func(return_value=None, exception=None):
"""Return a method to create a coro function that returns a value."""
if exception:
return AsyncMock(side_effect=exception)
return AsyncMock(return_value=return_value)
fut = asyncio.Future()
if exception is not None:
fut.set_exception(exception)
else:
fut.set_result(return_value)
return fut
@contextmanager
@@ -838,52 +834,6 @@ def mock_restore_cache(hass, states):
hass.data[key] = hass.async_create_task(get_restore_state_data())
class MockDependency:
"""Decorator to mock install a dependency."""
def __init__(self, root, *args):
"""Initialize decorator."""
self.root = root
self.submodules = args
def __enter__(self):
"""Start mocking."""
def resolve(mock, path):
"""Resolve a mock."""
if not path:
return mock
return resolve(getattr(mock, path[0]), path[1:])
base = MagicMock()
to_mock = {
f"{self.root}.{tom}": resolve(base, tom.split("."))
for tom in self.submodules
}
to_mock[self.root] = base
self.patcher = patch.dict("sys.modules", to_mock)
self.patcher.start()
return base
def __exit__(self, *exc):
"""Stop mocking."""
self.patcher.stop()
return False
def __call__(self, func):
"""Apply decorator."""
def run_mocked(*args, **kwargs):
"""Run with mocked dependencies."""
with self as base:
args = list(args) + [base]
func(*args, **kwargs)
return run_mocked
class MockEntity(entity.Entity):
"""Mock Entity class."""