Source code for kuha_common.testing

# Author(s): Toni Sissala
# Copyright 2019 Finnish Social Science Data Archive FSD / University of Tampere
# Licensed under the EUPL. See LICENSE.txt for full license.
"""Package for common testing functions and classes.
"""
import datetime
import functools


[docs]def time_me(func): """Decorate function to print its execution time to stdout. :note: test runner may capture the output. :param func: Function to decorate. Count execution time of function. """ @functools.wraps(func) def wrapper(*args, **kwargs): """Wrapper prints the time taken to execute function. Compare the timestamp before calling the function to the timestamp after calling the function. Returns functions return value. :returns: func return value. """ before = datetime.datetime.now() rval = func(*args, **kwargs) after = datetime.datetime.now() print("Execution time %s" % (after - before,)) return rval return wrapper
[docs]def mock_coro(dummy_rval=None, func=None): """Mock out a coroutine function. Accepts either keyword argument but not both. Submitting both will raise TypeError. Mock out coroutine and set return value:: >>> coro = mock_coro(dummy_rval='return_value') >>> rval = await coro() >>> assert rval == 'return_value' Mock out coroutine with custom function:: >>> call_args = [] >>> async def custom_func(*args): >>> call_args.append(args) >>> coro = mock_coro(func=custom_func) >>> await coro() >>> assert call_args == [('expected', 'args')] Use as a side_effect when patching:: >>> @mock.patch.object(pkg.Class, 'async_method', side_effect=mock_coro()) >>> def test_something(mock_method): >>> inst = pkg.Class() >>> eventloop.run_until_complete(inst.async_method()) >>> mock_method.assert_called_once_with() :param dummy_rval: return value of dummy function. :param func: function to call instead of original mocked out function. :returns: coroutine function. """ if dummy_rval is not None and func is not None: raise TypeError("mock_coro does not support dummy_rval and func at the same time") async def _wrap(*args, **kwargs): rval = await func(*args, **kwargs) return rval if func: return _wrap async def _dummy(*_, **__): return dummy_rval return _dummy
# Alias for backwards compatibility MockCoro = mock_coro