aspectlib.test

aspectlib.test.record Factory or decorator (depending if func is initially given).
aspectlib.test.mock Factory for a decorator that makes the function return a given return_value.

This module is designed to be a lightweight, orthogonal and easy to learn replacement for the popular mock framework.

Example usage, suppose you want to test this class:

>>> class ProductionClass(object):
...     def method(self):
...         return 'stuff'
>>> real = ProductionClass()

With aspectlib.test:

>>> from aspectlib import weave, test
>>> patch = weave(real.method, [test.mock(3), test.record(call=True)])
>>> real.method(3, 4, 5, key='value')
3
>>> assert real.method.calls == [(real, (3, 4, 5), {'key': 'value'})]

As a bonus, you have an easy way to rollback all the mess:

>>> patch.rollback()
>>> real.method()
'stuff'

With mock:

>>> from mock import Mock
>>> real = ProductionClass()
>>> real.method = Mock(return_value=3)
>>> real.method(3, 4, 5, key='value')
3
>>> real.method.assert_called_with(3, 4, 5, key='value')
aspectlib.test.mock(return_value, call=False)[source]

Factory for a decorator that makes the function return a given return_value.

Parameters:
  • return_value – Value to return from the wrapper.
  • call (bool) – If True, call the decorated function. (default: False)
Returns:

A decorator.

aspectlib.test.record(func=None, call=False, history=None)[source]

Factory or decorator (depending if func is initially given).

Parameters:
  • history (list) – An object where the Call objects are appended. If not given a new list object will be created.
  • call (bool) – If True the func will be called. (default: False)
Returns:

A wrapper that has a calls property.

The decorator returns a wrapper that records all calls made to func. The history is available as a call property. If access to the function is too hard then you need to specify the history manually.

Example:

>>> @record
... def a():
...     pass
>>> a(1, 2, 3, b='c')
>>> a.calls
[Call(self=None, args=(1, 2, 3), kwargs={'b': 'c'})]

Or, with your own history list:

>>> calls = []
>>> @record(history=calls)
... def a():
...     pass
>>> a(1, 2, 3, b='c')
>>> a.calls
[Call(self=None, args=(1, 2, 3), kwargs={'b': 'c'})]
>>> calls is a.calls
True