API Reference

Mocking frontends

Mocking frontends are used to provide easy to use interface on top of classes from mockify.engine module that act like a backend.

So instead of doing this:

>>> from mockify.engine import Call, Registry
>>> reg = Registry()
>>> reg.expect_call(Call('foo', (1, 2)), 'foo.py', 123)
<mockify.Expectation: foo(1, 2)>
>>> reg(Call('foo', (1, 2)))
>>> reg.assert_satisfied()

You use a frontend to do the same much easier:

>>> from mockify.mock.function import Function
>>> foo = Function('foo')
>>> foo.expect_call(1, 2)
<mockify.Expectation: foo(1, 2)>
>>> foo(1, 2)
>>> foo.assert_satisfied()

mockify.mock.function - Frontends for mocking functions

class mockify.mock.function.Function(name, registry=None)

Bases: object

Class for mocking Python functions.

Example usage:

>>> foo = Function('foo')
>>> foo.expect_call(1, 2).times(2)
<mockify.Expectation: foo(1, 2)>
>>> for _ in range(2):
...     foo(1, 2)
>>> foo.assert_satisfied()
Parameters:
  • name – Mock function name
  • registry

    This is optional.

    Use this to pass custom instance of mockify.engine.Registry class if you need to share it between multiple frontends. Sharing is useful for example to check if all mocks are satisfied using one assert_satisfied call:

    >>> from mockify.engine import Registry
    >>> reg = Registry()
    >>> foo = Function('foo', registry=reg)
    >>> bar = Function('bar', registry=reg)
    >>> foo.expect_call()
    <mockify.Expectation: foo()>
    >>> bar.expect_call()
    <mockify.Expectation: bar()>
    >>> foo()
    >>> bar()
    >>> reg.assert_satisfied()
    
assert_satisfied()

Assert that this function mock is satisfied.

This method just calls mockify.engine.Registry.assert_satisfied() with name given via constructor as an argument.

expect_call(*args, **kwargs)

Record call expectation.

This method creates mockify.engine.Call instance giving it args and kwargs, fetches file and line number from current call stack and triggers mockify.engine.Registry.expect_call() and returns expectation object it produces.

class mockify.mock.function.FunctionFactory(registry=None)

Bases: object

Helper factory class for easier function mocks creating.

This helper can be created with no params or with mockify.engine.Registry instance as parameter. It provides an easy way of function mock creating by simply getting factory attributes that become function mock names. Once such attribute is get for the first time, Function instance is created, and later it is just returned.

This allows to create function mocks as easy as in this example:

>>> factory = FunctionFactory()
>>> factory.foo.expect_call()
<mockify.Expectation: foo()>
>>> factory.bar.expect_call(1, 2)
<mockify.Expectation: bar(1, 2)>

Then pass to some unit under test:

>>> def unit_under_test(foo, bar):
...     foo()
...     bar(1, 2)
>>> unit_under_test(factory.foo, factory.bar)

To finally check if all mocks registered in one FunctionFactory object are satisfied using one single call:

>>> factory.assert_satisfied()
assert_satisfied()

Check if all function mocks registered by this factory are satisfied.

This method simply calls mockify.engine.Registry.assert_satisfied() with names of all created mocks as arguments.

mockify.engine - Library core

This module contains set of classes that provides backend mechanism for storing and tracking call expectations.

class mockify.engine.Call(name, args=None, kwargs=None)

Bases: object

Binds mock name with arguments it was called with or it is expected to be called with.

Call objects are created in mock frontends (like mockify.mock.function.Function mock class) by methods expected_call and __call__ by simply passing their argument to Call constructor.

Instances of this class are comparable. Two Call objects are equal if and only if all attributes (name, args and kwargs) are the same. For example:

>>> Call('foo') == Call('foo')
True
>>> Call('foo') != Call('bar')
True
>>> Call('foo', (1, 2), {'c': 3}) == Call('foo', (1, 2), {'c': 3})
True

Call objects can also be created with use of matchers, for example mockify.matchers.Any, that will match any value:

>>> from mockify.matchers import _
>>> Call('foo', (_, _)) == Call('foo', (1, 2))
True
>>> Call('foo', (_, _)) == Call('foo', (3, 4))
True
Parameters:
  • name – Function or method name.
  • args – Positional arguments
  • kwargs – Named arguments
args

Mock positional args.

kwargs

Mock named args.

name

Mock name.

class mockify.engine.Expectation(expected_call, filename, lineno)

Bases: object

Class representing single expectation.

Instances of this class are normally created by registry objects using Registry.expect_call() method. Each instance of this class is correlated with exactly one mockify.engine.Call object representing expected mock call pattern.

After Expectation object is created by call to some expect_call method, it can be mutated using following methods:

Parameters:
  • call – Instance of mockify.engine.Call representing expected mock call pattern
  • filename – File name were this expectation was created
  • lineno – Line number where this expectation was created
__call__(call)

Call this expectation object.

If given call object does not match expected_call then this method will raise TypeError exception.

Otherwise, total call count is increased by one and:

  • if actions are recorded, then next action is executed and its result returned or mockify.exc.OversaturatedCall exception is raised if there are no more actions
  • if there are no actions recorded, just None is returned
expected_call

Instance of mockify.engine.Call representing expected mock call pattern.

This basically is exactly the same Call object as was passed to Expectation constructor.

format_action()

Return textual representation of next action to be executed.

This method uses action’s __str__ method to render action name.

Returns None if there were no actions recorded or all were consumed.

This is used by mockify.exc.Unsatisfied exception when rendering error message.

format_actual()

Return textual representation of how many times this expectation was called so far.

This is used by mockify.exc.Unsatisfied exception when rendering error message.

format_expected()

Return textual representation of how many times this expectation is expected to be called.

This is used by mockify.exc.Unsatisfied exception when rendering error message.

format_location()

Return textual representation of place (filename and lineno) where this expectation was created.

Basically, it just returns [filename]:[lineno] string, where filename and lineno are given via Expectation constructor.

is_satisfied()

Check if this expectation is satisfied.

match(call)

Check if expected_call matches call.

times(expected_count)

Record how many times this expectation is expected to be called.

Parameters:expected_count

Expected call count.

This can be either integer number (exact call count) or instance of one of classes from mockify.times module.

will_once(action)

Attach action to be executed when this expectation gets consumed.

This method can be used several times, making action chains. Once expectation is consumed, next action is executed and removed from the list. If there are no more actions, another call will fail with mockify.exc.OversaturatedCall exception.

After this method is used, you can also use will_repeatedly() to record repeated action that will get executed after all single actions are consumed.

Parameters:action

Action to be executed.

See mockify.actions for details.

will_repeatedly(action)

Attach repeated action to be executed when this expectation is called.

This method is used to record one action that gets executed each time this expectation object is called. By default, when repeated action is recorded, expectation can be called any number of times (including zero).

After setting repeated action, you can also set expected call count using times().

Parameters:action

Action to be executed.

See mockify.actions for details.

class mockify.engine.Registry(expectation_class=None)

Bases: object

Acts like a database for Expectation objects.

This class is used as a backend for higher level mocking utilities (a.k.a. frontends), like mockify.mock.function.Function mocking class. It provides methods to record, lookup and verifying of expectations.

There can be many instances of registry classes, or one that can be shared between various mock frontends. For example, you can create one registry in setup code, then create various mocks inside your tests, to finally trigger assert_satisfied() of that single registry in test’s teardown code. Or you can just use frontends with their defaults. It is completely up to you.

Parameters:expectation_class

This is optional.

Used to give custom subclass of Expectation to be used inside this registry.

__call__(call)

Call a mock.

When this method is called, registry performs a lookup of matching unsatisfied expectations and calls first expectation found. If there are no matching expectation, then mockify.exc.UninterestedCall exception is raised. If there are matching expectations but all are satisfied, then last is called (making it oversaturated).

Parameters:call – Instance of mockify.engine.Call class representing mock being called
assert_satisfied(*names)

Assert that all expectations are satisfied.

If there is at least one unsatisfied expectation, then this method will raise mockify.exc.Unsatisfied exception containing list of failed expectations.

This method can be called as many times as you want.

Changed in version 0.2: Accepts names of mocks to check as positional args. If one or more names are given, then this method limits checking only to mocks of matching names.

expect_call(call, filename, lineno)

Register expectation.

Returns instance of expectation_class (usually Expectation) representing newly created expectation.

Parameters:
  • call – Instance of mockify.engine.Call class representing exact mock call or a pattern (if created with matchers) that is expected to be executed
  • filename – Path to file were expectation is created
  • lineno – Line number (inside filename) where expectation is created

mockify.actions - Actions for use with will_once or will_repeatedly

Module containing predefined actions that can be used as argument for Expectation.will_once() or Expectation.will_repeatedly().

Basically, any class containing following methods is considered an action:

__str__(self)

Returning string representation of an action.

This is used for error reporting.

__call__(self, *args, **kwargs)

Method that is called when mock is called.

Entire action logic goes in here.

class mockify.actions.Invoke(func)

Bases: object

Makes mock invoking given function when called.

When mock is called, all arguments (if there are any) are passed to the func and its return value is returned as mock’s return value.

Parameters:func – Function to be executed
class mockify.actions.Raise(exc)

Bases: object

Makes mock raising given exception when called.

Parameters:exc – Instance of exception to be raised
class mockify.actions.Return(value)

Bases: object

Makes mock returning given value when called.

Parameters:value – Value to be returned

mockify.exc - Exceptions

exception mockify.exc.OversaturatedCall(expectation, call)

Bases: TypeError

Raised when mock is called more times than expected.

This exception will be thrown only if mock has actions defined as it does not know what to do next if all expected actions were already executed.

Parameters:
call

Instance of mockify.engine.Call passed to OversaturatedCall constructor.

expectation

Instance of mockify.engine.Expectation passed to OversaturatedCall constructor.

exception mockify.exc.UninterestedCall(call)

Bases: TypeError

Raised when uninterested mock is called.

Mockify requires each mock call to have matching expectation recorded. If none is found during call, then this exception is raised, terminating the test.

Parameters:call – Instance of mockify.engine.Call class representing uinterested mock call
call

Instance of mockify.engine.Call passed to UninterestedCall constructor.

exception mockify.exc.Unsatisfied(expectations)

Bases: AssertionError

Raised by mockify.engine.Registry.assert_satisfied() method when there is at least one unsatisfied expectation.

This exception displays explanatory information to the user:

  • file location where unsatisfied expectation was recorded
  • expected call pattern
  • expected call count
  • actual call count
  • next action to be executed (if any)
Parameters:expectations – List of mockify.engine.Expectation instances representing all unsatisfied expectations
expectations

Instance of mockify.engine.Expectation passed to Unsatisfied constructor.

mockify.helpers - Various helper utilities

mockify.helpers.assert_satisfied(*subjects)

Context manager for verifying multiple subjects at once.

Each passed subject must have assert_satisfied method defined, so it can be used with mockify.mock.function.Function or mockify.engine.Registry instances for example.

Basically, the role of this helper is to ensure that all subjects become satisfied after leaving wrapped context. For example:

>>> from mockify.mock.function import Function
>>> foo = Function('foo')
>>> bar = Function('bar')
>>> foo.expect_call()
<mockify.Expectation: foo()>
>>> bar.expect_call().times(0)
<mockify.Expectation: bar()>
>>> with assert_satisfied(foo, bar):
...     foo()

And that’s it - you don’t have to explicitly check if foo and bar are satisfied, because the helper will do it for you. And also it emphasizes part of code that actually uses given mocks.

mockify.matchers - Matchers for use with expect_call

Module containing predefined matchers.

A matcher is every class that inherits from Matcher and implements following methods:

__repr__(self)
Return matcher’s text representation.
__eq__(self, other)

Check if self is equal to other.

Here we use standard Python __eq__ operator as it will be automatically executed by Python no matter where the matcher is used. But equality definition is completely up to the matcher implementation.

class mockify.matchers.Any

Bases: mockify.matchers.Matcher

Matcher that matches any value.

It is available also as _ (underscore) single instance that can be imported from this module.

For example, you can record expectation that mock must be called with one positional argument of any value but exactly 3 times:

>>> from mockify.matchers import _
>>> from mockify.mock.function import Function
>>> foo = Function('foo')
>>> foo.expect_call(_).times(3)
<mockify.Expectation: foo(_)>
>>> for i in range(3):
...     foo(i)
>>> foo.assert_satisfied()
class mockify.matchers.Matcher

Bases: object

Base class for matchers.

class mockify.matchers.SaveArg

Bases: mockify.matchers.Matcher

Matcher that matches any value and keeps ordered track of unique values.

This can be used as a replacement for Any in case that you need to ensure that mock was called in specified order.

For example:

>>> from mockify.mock.function import Function
>>> arg = SaveArg()
>>> foo = Function('foo')
>>> foo.expect_call(arg).times(3)
<mockify.Expectation: foo(SaveArg)>
>>> for i in range(3):
...     foo(i)
>>> foo.assert_satisfied()
>>> arg.called_with == [0, 1, 2]
True
called_with

List of ordered unique values that this matcher was called with.

mockify.times - Classes for use with times method

Module containing set of classes to be used with mockify.engine.Expectation.times() method.

You can also create your own classes to be used with that method. The only thing required from such class is to implement following interface:

is_satisfied(self, actual)

Return True if actual call count is satisfied by self, or False otherwise.

Here, actual is absolute call count expectation received so far. It is completely implementation-specific of which values of actual are said to be satisfied and which are not. For example, Exactly will compare actual with fixed value (given via constructor) and return True only if those two are equal.

adjust_by(self, minimal)

Adjust self by current minimal expected call count and return new instance of type(self).

In some complex expectation there could be a situation in which expectation must be computed again. This is not visible for library user, but must be done behind the scenes to properly process expectations. Such situation can be presented in this example:

>>> from mockify.actions import Return
>>> from mockify.mock.function import Function
>>> foo = Function('foo')
>>> foo.expect_call(1, 2).will_once(Return(1)).will_repeatedly(Return(2)).times(2)
<mockify.Expectation: foo(1, 2)>
>>> foo(1, 2)
1
>>> foo(1, 2)
2
>>> foo(1, 2)
2
>>> foo.assert_satisfied()

In example above we’ve used times(2) to tell that last repeated action is expected to be called twice, but real expected call count is 3 times, as will_once is used. Behind the scenes, this is recalculated using this metho.

format_expected(self)

Return textual representation of expected call count.

This is used by mockify.exc.Unsatisfied exception when error message is being rendered.

minimal(sefl) (property)

Property containing minimal call count that is considered valid for given instance.

For example, for AtLeast or Exactly it would be just its constructor argument, for :class`AtMost` it will be 0, for Between it will be its minimal argument.

class mockify.times.AtLeast(minimal)

Bases: object

Used to set minimal expected call count.

If this is used, then expectation is said to be satisfied if actual call count is not less that minimal.

Parameters:minimal – Integer value representing minimal expected call count
class mockify.times.AtMost(maximal)

Bases: object

Used to set maximal expected call count.

If this is used, then expectation is said to be satisfied if actual call count is not greater than maximal.

Parameters:maximal – Integer value representing maximal expected call count
class mockify.times.Between(minimal, maximal)

Bases: object

Used to set a range of valid call counts.

If this is used, then expectation is said to be satisfied if actual call count is not less than minimal and not greater than maximal.

Parameters:
  • minimal – Integer value representing minimal expected call count
  • maximal – Integer value representing maximal expected call count
class mockify.times.Exactly(expected)

Bases: object

Used to expect fixed call count to be made.

You do not have to use this class explicitly as its instances are automatically created when you call times method with integer value as argument.

Parameters:expected – Integer value representing expected call count