mockify.core - Library core

Library core module.

mockify.core.assert_satisfied(*mocks)

Check if all given mocks are satisfied.

This function collects all expectations from given mock for which mockify.core.Expectation.is_satisfied() evaluates to False. Finally, if at least one unsatisfied expectation is found, this method raises mockify.exc.Unsatisfied exception.

class mockify.core.Call(_name_, *args, **kwargs)

An object representing mock call.

Instances of this class are created when expectations are recorded or when mock is called. Call objects are comparable. Two call objects are equal if and only if:

  • mock names are the same,
  • args are the same,
  • and keyword args are the same.
Parameters:_name_ – The name of a mock
__init__(_name_, *args, **kwargs)

Initialize self. See help(type(self)) for accurate signature.

__str__()

Return str(self).

__repr__()

Return repr(self).

__eq__(other)

Return self==value.

__ne__(other)

Return self!=value.

name

The name of a mock.

args

Positional args mock was called with or is expected to be called with.

kwargs

Keyword args mock was called with or is expected to be called with.

location

Information of place in test or tested code where this call object was created.

New in version 0.6.

Return type:mockify.core.LocationInfo
__weakref__

list of weak references to the object (if defined)

class mockify.core.LocationInfo(filename, lineno)

A placeholder for file name and line number obtained from the stack.

Used by mockify.core.Call objects to get their location in the code. That information is later used in assertion messages.

New in version 0.6.

Parameters:
  • filename – Name of the file
  • lineno – Line number in given file
__init__(filename, lineno)

Initialize self. See help(type(self)) for accurate signature.

__eq__(other)

Return self==value.

__ne__(other)

Return self!=value.

__str__()

Return str(self).

filename

File name from stack.

lineno

Line number form stack.

classmethod get_external()

Factory method for creating instances of this class.

It extracts stack and finds (in reversed order) first frame that is outside of the Mockify library. Thanks to this all mock calls or expectation recordings will point to test function or tested code that uses Mockify, not to Mockify’s internals.

Return type:mockify.core.LocationInfo
__weakref__

list of weak references to the object (if defined)

mockify.core.satisfied(*mocks)

Context manager wrapper for assert_satisfied().

mockify.core.ordered(*mocks)

Context manager that checks if expectations in wrapped scope are consumed in same order as they were defined.

This context manager will raise mockify.exc.UnexpectedCallOrder assertion on first found mock that is executed out of specified order.

See Recording ordered expectations for more details.

mockify.core.patched(*mocks)

Context manager that replaces imported objects and functions with their mocks using mock name as a name of patched module.

It will patch only functions or objects that have expectations recorded, so all needed expectations will have to be recorded before this context manager is used.

See Patching imported modules for more details.

class mockify.core.Expectation(expected_call)

An class representing single expectation.

Instances of this class are created and returned by factory expect_call() method you will use to record expectations on your mocks:

>>> from mockify.mock import Mock
>>> mock = Mock('mock')
>>> mock.expect_call(1, 2)
<mockify.Expectation: mock(1, 2)>
Parameters:expected_call – Instance of Call class containing parameters passed to expect_call() factory method that created this expectation object.
__init__(expected_call)

Initialize self. See help(type(self)) for accurate signature.

__repr__()

Return repr(self).

__call__(actual_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
is_satisfied()

Check if this expectation is satisfied.

Expectation object is satisfied if and only if:

  • total number of calls is not exceeding expected number of calls,
  • all actions (if any were recorded) are consumed.
Return type:bool
times(cardinality)

Set expected number or range of call counts.

Following values are possible:

See Setting expected call count tutorial section for more details.

will_once(action)

Append next action to be executed when this expectation object receives a call.

Once this method is called, it returns special proxy object that you can use to mutate this expectation even further by calling one of given methods on that proxy:

Thanks to that you can record so called action chains (see Recording actions for more details).

This method can be called with any action object from mockify.actions as an argument.

will_repeatedly(action)

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

Unlike single actions, recorded with will_once(), repeated actions are by default executed any number of times, including zero (see Repeated actions for more details).

Once this method is called, it returns a proxy object you can use to adjust repeated action even more by calling one of following methods:

  • times(), used to record repeated action call count limits (see times()).

This method accepts actions defined in mockify.actions module.

expected_call

Returns expected_call parameter passed during construction.

This is used when this expectation is compared with mockify.core.Call object representing actual call, to find expectations matching that call.

Return type:mockify.core.Call
actual_call_count

Number of matching calls this expectation object received so far.

This is relative value; if one action expires and another one is started to be executed, then the counter starts counting from 0 again. Thanks to this you’ll receive information about actual action execution count. If your expectation does not use will_once() or will_repeatedly(), then this counter will return total number of calls.

New in version 0.6.

expected_call_count

Return object representing expected number of mock calls.

Like actual_call_count, this varies depending on internal expectation object state.

Return type:mockify.cardinality.ExpectedCallCount
action

Return action to be executed when this expectation receives another call or None if there are no (more) actions.

Return type:mockify.actions.Action
__weakref__

list of weak references to the object (if defined)

class mockify.core.Session

A class providing core logic of connecting mock calls with recorded expectations.

Sessions are created for each mock automatically, or can be created explicitly and then shared across multiple mocks. While mock classes can be seen as som kind of frontends that mimic behavior of various Python constructs, session instances are some kind of backends that receive mockify.core.Call instances created by mocks during either mock call, or expectation recording.

Changed in version 0.6: Previously this was named Registry.

__init__()

Initialize self. See help(type(self)) for accurate signature.

config

A dictionary-like object for configuring sessions.

Following options are currently available:

'expectation_class'

Can be used to override expectation class used when expectations are recorded.

By default, this is mockify.core.Expectation, and there is a requirement that custom class must inherit from original one.

'uninterested_call_strategy'

Used to set a way of processing so called unexpected calls, i.e. calls to mocks that has no expectations recorded. Following values are supported:

'fail'

This is default option.

When mock is called unexpectedly, mockify.exc.UninterestedCall exception is raised and test is terminated.

'warn'
Instead of raising exception, mockify.exc.UninterestedCallWarning warning is issued, and test continues.
'ignore'
Unexpected calls are silently ignored.
__call__(actual_call)

Trigger expectation matching actual_call received from mock being called.

This method is called on every mock call and basically all actual call processing takes place here. Values returned or exceptions raised by this method are also returned or raised by mock.

Parameters:actual_call – Instance of mockify.core.Call class created by calling mock.
expectations()

An iterator over all expectations recorded in this session.

Yields mockify.core.Expectation instances.

expect_call(expected_call)

Called by mock when expectation is recorded on it.

This method creates expectation object, adds it to the list of expectations, and returns.

Return type:mockify.Expectation
Parameters:expected_call

Instance of mockify.core.Call created by mock when expect_call() was called on it.

Represents parameters the mock is expected to be called with.

assert_satisfied()

Check if all registered expectations are satisfied.

This works exactly the same as mockify.core.assert_satisfied(), but for given session only. Can be used as a replacement for any other checks if one global session object is used.

enable_ordered(names)

Mark expectations matching given mock names as ordered, so they will have to be resolved in their declaration order.

This is used internally by mockify.core.ordered().

disable_ordered()

Called by mockify.core.ordered() when processing of ordered expectations is done.

Moves any remaining expectations back to the unordered storage, so they will be later displayed as unsatisfied.

__weakref__

list of weak references to the object (if defined)

class mockify.core.BaseMock(name=None, session=None, parent=None)

Abstract base class for all mock classes.

In Mockify, mocks are composed in a tree-like structure. For example, to mock object with a methods we compose object mock (a root) and then supply it with leafs (or children), each representing single mocked method of that object. This class provides methods and properties for Mockify engine to walk through such defined structure.

If you need to declare your own mocks, make sure you implement this interface.

Parameters:
  • name

    Mock name.

    This is used for error reporting to display which mock has failed. This attribute must be set by inheriting class.

  • session

    Instance of mockify.core.Session to be used.

    If not given, parent’s session will be used if parent is set. Otherwise, a new session will be created.

  • parent

    Instance of BaseMock representing parent for this mock.

    When this parameter is given, mock implicitly uses same session as given parent and uses parent’s __m_fullname__ as a prefix for its fullname.

Note

Parameters session and parent are self-exclusive and cannot be used simultaneously.

Changed in version 0.9: Added __init__ method, as it is basically same for all mock classes.

New in version 0.8.

__init__(name=None, session=None, parent=None)

Initialize self. See help(type(self)) for accurate signature.

__repr__()

Return repr(self).

__m_name__

Name of this mock.

__m_session__

Instance of mockify.core.Session used by this mock.

This should always be the same object for mock and all its children.

__m_parent__

Weak reference to BaseMock that is a parent of this mock.

If mock has no parent, this should be set to None.

Note

Make sure this property is always set in subclass to either parent object or None - otherwise you may get errors.

__m_fullname__

Full name of this mock.

It is composed of parent’s __m_fullname__ and current __m_name__. If mock has no parent, then this will be same as __m_name__.

__m_walk__()

Recursively iterate over BaseMock object yielded by __m_children__() method.

It always yields self as first element.

This method is used by Mockify internals to collect all expectations recorded for mock and all its children.

__m_expectations__()

Iterator over mockify.core.Expectation objects recorded for this mock.

It should not include expectations recorded on mock’s children. To get all expectations (including children), use __m_walk__().

__m_children__()

Iterator over BaseMock objects representing direct children of this mock.

This should not include grandchildren.

__weakref__

list of weak references to the object (if defined)

class mockify.core.MockInfo(target)

A class for inspecting mocks.

This class simplifies access to mock’s special properties and methods defined in BaseMock, but wraps results (when applicable) with MockInfo instances. If you need to access mock metadata in your tests, then this class is a recommended way to do this.

Parameters:target – Instance of BaseMock object to be inspected
__init__(target)

Initialize self. See help(type(self)) for accurate signature.

__repr__()

Return repr(self).

mock

Target mock that is being inspected.

Deprecated since version 0.8: This is deprecated since version 0.8 and will be dropped in one of upcoming releases. Use target instead.

target

Reference to BaseMock being inspected.

New in version 0.8.

parent

A proxy to access BaseMock.__m_parent__.

Returns None if target has no parent, or parent wrapped with MockInfo object otherwise.

New in version 0.8.

name

A proxy to access BaseMock.__m_name__ of target mock.

Changed in version 0.8: It is no longer full name; for that purpose use new fullname

fullname

A proxy to access BaseMock.__m_fullname__ of target mock.

New in version 0.8.

session

A proxy to access BaseMock.__m_session__ of target mock.

expectations()

An iterator over results returned by BaseMock.__m_expectations__() method.

__weakref__

list of weak references to the object (if defined)

children()

An iterator over results returned by BaseMock.__m_children__() method.

It wraps each found child with a MockInfo object.

walk()

An iterator over results returnend by BaseMock.__m_walk__() method.

It wraps each found child with a MockInfo object.