mockify.actions - Classes for recording side effects

Module containing action types.

Actions are used to tell the mock what it must do once called with given set of arguments. This can be returning a value, returning a generator, calling a function, raising exception etc.

class mockify.actions.Action

Bases: IAction, DictEqualityMixin

Abstract base class for actions.

This is common base class for all actions defined in this module. Custom actions should also inherit from this one.

Added in version 0.6.

abstract __call__(actual_call)

Action body.

It receives actual call object and returns action result based on that call object. This method may also raise exceptions if that is functionality of the action being implemented.

Parameters:

actual_call – Instance of mockify.core.Call containing params of actual call being made

abstract __str__()

Return string representation of this action.

This is later used in error messages when test fails.

Changed in version 0.11: Now this is made abstract and previous abstract format_params() was removed

class mockify.actions.Invoke(func, *args, **kwargs)

Bases: Action

Forces mock to invoke func when called.

When func is called, it is called with all bound arguments plus all arguments mock was called with. Value that mock returns is the one func returns. Use this action when more sophisticated checks have to be done when mock gets called or when your mock must operate on some output parameter.

See Mocking functions with output parameters for more details.

Here’s an example using one of built-in functions as a func:

>>> from mockify.mock import Mock
>>> from mockify.actions import Invoke
>>> mock = Mock('mock')
>>> mock.expect_call([1, 2, 3]).will_once(Invoke(sum))
<mockify.core.Expectation: mock([1, 2, 3])>
>>> mock([1, 2, 3])
6

Changed in version 0.6: Now this action allows binding args to function being called.

Parameters:
  • func – Function to be executed

  • args – Additional positional args to be bound to func.

  • kwargs – Additional named args to be bound to func.

__call__(actual_call)

Action body.

It receives actual call object and returns action result based on that call object. This method may also raise exceptions if that is functionality of the action being implemented.

Parameters:

actual_call – Instance of mockify.core.Call containing params of actual call being made

__str__()

Return string representation of this action.

This is later used in error messages when test fails.

Changed in version 0.11: Now this is made abstract and previous abstract format_params() was removed

class mockify.actions.InvokeAsync(func, *args, **kwargs)

Bases: Invoke

Similar to Invoke, but to be used with asynchronous Python code.

This action can be instantiated with either non-async or async func. No matter which one you pick, it always makes mock awaitable. Here’s an example showing usage with both callback function types:

from mockify.core import satisfied
from mockify.mock import Mock
from mockify.actions import InvokeAsync
from mockify.matchers import _

async def test_invoke_async_with_non_async_func():

    def func(numbers):
        return sum(numbers)

    mock = Mock('func')
    mock.expect_call(_).will_once(InvokeAsync(func))
    with satisfied(mock):
        assert await mock([1, 2, 3]) == 6

async def test_invoke_async_with_async_func():

    async def async_func(numbers):
        return sum(numbers)

    mock = Mock('func')
    mock.expect_call(_).will_once(InvokeAsync(async_func))
    with satisfied(mock):
        assert await mock([1, 2, 3]) == 6

Added in version 0.11.

__call__(actual_call)

Action body.

It receives actual call object and returns action result based on that call object. This method may also raise exceptions if that is functionality of the action being implemented.

Parameters:

actual_call – Instance of mockify.core.Call containing params of actual call being made

class mockify.actions.Iterate(iterable)

Bases: Action

Similar to Return, but returns an iterator to given iterable.

For example:

>>> from mockify.mock import Mock
>>> from mockify.actions import Iterate
>>> mock = Mock('mock')
>>> mock.expect_call().will_once(Iterate('foo'))
<mockify.core.Expectation: mock()>
>>> next(mock())
'f'

Added in version 0.6.

__call__(actual_call)

Action body.

It receives actual call object and returns action result based on that call object. This method may also raise exceptions if that is functionality of the action being implemented.

Parameters:

actual_call – Instance of mockify.core.Call containing params of actual call being made

__str__()

Return string representation of this action.

This is later used in error messages when test fails.

Changed in version 0.11: Now this is made abstract and previous abstract format_params() was removed

class mockify.actions.IterateAsync(iterable)

Bases: Iterate

Similar to Iterate, but returns awaitable that returns an iterator to given iterable.

For example:

from mockify.core import satisfied
from mockify.mock import Mock
from mockify.actions import IterateAsync

async def get_next(func):
    iterable = await func()
    return next(iterable)

async def test_get_next():
    func = Mock('func')
    func.expect_call().will_once(IterateAsync('foo'))
    with satisfied(func):
        assert await get_next(func) == 'f'

Added in version 0.11.

__call__(actual_call)

Action body.

It receives actual call object and returns action result based on that call object. This method may also raise exceptions if that is functionality of the action being implemented.

Parameters:

actual_call – Instance of mockify.core.Call containing params of actual call being made

class mockify.actions.Raise(exc)

Bases: Action

Forces mock to raise exc when called.

For example:

>>> from mockify.mock import Mock
>>> from mockify.actions import Raise
>>> mock = Mock('mock')
>>> mock.expect_call().will_once(Raise(ValueError('invalid value')))
<mockify.core.Expectation: mock()>
>>> mock()
Traceback (most recent call last):
    ...
ValueError: invalid value
__call__(actual_call)

Action body.

It receives actual call object and returns action result based on that call object. This method may also raise exceptions if that is functionality of the action being implemented.

Parameters:

actual_call – Instance of mockify.core.Call containing params of actual call being made

__str__()

Return string representation of this action.

This is later used in error messages when test fails.

Changed in version 0.11: Now this is made abstract and previous abstract format_params() was removed

class mockify.actions.RaiseAsync(exc)

Bases: Raise

Similar to Raise, but to be used with asynchronous Python code.

For example:

from mockify.core import satisfied
from mockify.mock import Mock
from mockify.actions import RaiseAsync

async def async_caller(func):
    try:
        return await func()
    except ValueError as e:
        return str(e)

async def test_async_caller():
    func = Mock('func')
    func.expect_call().will_once(RaiseAsync(ValueError('an error')))
    with satisfied(func):
        assert await async_caller(func) == 'an error'

Added in version 0.11.

__call__(actual_call)

Action body.

It receives actual call object and returns action result based on that call object. This method may also raise exceptions if that is functionality of the action being implemented.

Parameters:

actual_call – Instance of mockify.core.Call containing params of actual call being made

class mockify.actions.Return(value)

Bases: Action

Forces mock to return value when called.

For example:

>>> from mockify.mock import Mock
>>> from mockify.actions import Return
>>> mock = Mock('mock')
>>> mock.expect_call().will_once(Return('foo'))
<mockify.core.Expectation: mock()>
>>> mock()
'foo'
__call__(actual_call)

Action body.

It receives actual call object and returns action result based on that call object. This method may also raise exceptions if that is functionality of the action being implemented.

Parameters:

actual_call – Instance of mockify.core.Call containing params of actual call being made

__str__()

Return string representation of this action.

This is later used in error messages when test fails.

Changed in version 0.11: Now this is made abstract and previous abstract format_params() was removed

class mockify.actions.ReturnAsync(value)

Bases: Return

Similar to Return, but to be used with asynchronous Python code.

For example:

from mockify.core import satisfied
from mockify.mock import Mock
from mockify.actions import ReturnAsync

async def async_caller(func):
    return await func()

async def test_async_caller():
    func = Mock('func')
    func.expect_call().will_once(ReturnAsync('foo'))
    with satisfied(func):
        assert await async_caller(func) == 'foo'

Added in version 0.11.

__call__(actual_call)

Action body.

It receives actual call object and returns action result based on that call object. This method may also raise exceptions if that is functionality of the action being implemented.

Parameters:

actual_call – Instance of mockify.core.Call containing params of actual call being made

class mockify.actions.ReturnAsyncContext(value)

Bases: ReturnContext

Similar to ReturnContext, but returns value via async context manager.

For example:

from mockify.core import satisfied
from mockify.mock import MockFactory
from mockify.actions import Return, ReturnAsyncContext

class UserStorage:

    def __init__(self, database):
        self._database = database

    async def get(self, user_id):
        async with self._database.begin_transaction() as transaction:
            return await transaction.users.get(user_id)

async def test_user_storage_async_get():
    factory = MockFactory()
    transaction = factory.mock('transaction')
    transaction.users.get.expect_call(123).will_once(ReturnAsync('user-123'))
    database = factory.mock('database')
    database.begin_transaction.expect_call().will_once(ReturnAsyncContext(transaction))
    with satisfied(factory):
        assert await UserStorage(database).get(123) == 'user-123'

Added in version 0.12.

__call__(actual_call)

Action body.

It receives actual call object and returns action result based on that call object. This method may also raise exceptions if that is functionality of the action being implemented.

Parameters:

actual_call – Instance of mockify.core.Call containing params of actual call being made

class mockify.actions.ReturnContext(value)

Bases: Return

Similar to Return, but returns value via context manager.

For example:

from mockify.core import satisfied
from mockify.mock import MockFactory
from mockify.actions import Return, ReturnContext

class UserStorage:

    def __init__(self, database):
        self._database = database

    def get(self, user_id):
        with self._database.begin_transaction() as transaction:
            return transaction.users.get(user_id)

def test_user_storage_get():
    factory = MockFactory()
    transaction = factory.mock('transaction')
    transaction.users.get.expect_call(123).will_once(Return('user-123'))
    database = factory.mock('database')
    database.begin_transaction.expect_call().will_once(ReturnContext(transaction))
    with satisfied(factory):
        assert UserStorage(database).get(123) == 'user-123'

Added in version 0.12.

__call__(actual_call)

Action body.

It receives actual call object and returns action result based on that call object. This method may also raise exceptions if that is functionality of the action being implemented.

Parameters:

actual_call – Instance of mockify.core.Call containing params of actual call being made

class mockify.actions.YieldAsync(iterable)

Bases: Iterate

Similar to Iterate, but returns async iterator to given iterable.

This iterator can later be used with async for statement.

For example:

from mockify.core import satisfied
from mockify.mock import Mock
from mockify.actions import YieldAsync

async def fetch(func):
    result = []
    async for item in func():
        result.append(item)
    return result

async def test_fetch():
    func = Mock('func')
    func.expect_call().will_once(YieldAsync('foo'))
    with satisfied(func):
        assert await fetch(func) == ['f', 'o', 'o']

Added in version 0.12.

__call__(actual_call)

Action body.

It receives actual call object and returns action result based on that call object. This method may also raise exceptions if that is functionality of the action being implemented.

Parameters:

actual_call – Instance of mockify.core.Call containing params of actual call being made