Mocktest module

Note: (all of these classes and methods are available from the toplevel mocktest module, despite the use of fully-qualified names here)

class mocktest.mocktest.TestCase(methodName='runTest')

A subclass of unittest.TestCase with the following additions:

  • Automatically calls MockTransaction.__enter__ and __exit__ in order to reset mock state and verify expectations upon test completion.
  • enhanced versions of assertTrue / False, assertRaises
  • assertMatches
assertMatches(matcher, val, message=None)

Fail the test if an object does not satisfy the given matcher.

assertRaises(exception, func, message=None, args=None, kwargs=None, matching=None)

Enhanced assertRaises, able to: - check arguments (args) - check keyword arguments (kwargs) - match a regular expression on the resulting expression message (matching) - compare message strings (message)

failUnlessRaises(exception, func, message=None, args=None, kwargs=None, matching=None)

Enhanced assertRaises, able to: - check arguments (args) - check keyword arguments (kwargs) - match a regular expression on the resulting expression message (matching) - compare message strings (message)

run(result=None)

This is (mostly) the default implementation of unittest.run the only modification is that a self.FailureException raised in the teardown method counts for a failure

mocktest.mocktest.Skeleton(cls)

Generate a subclass inheriting only private methods and setUp/tearDown, for the purpose of inheriting test setup but not any actual test implementations

Mock Objects

mocktest.mocking.when(obj)

Replace a method on an object. Just like expect, except that no verification against the number of calls received will be performed.

Return type:MockAct
mocktest.mocking.expect(obj)

Add an expectation to a method of obj. By default, the method is expected at least once. E.g:

>>> expect(some_object).method
Return type:MockAct
mocktest.mocking.mock(name='unnamed mock', create_children=True)

Make a mock object.

Parameters:
  • name – the name of this mock object
  • create_children – when attributes are accessed on this mock, they will be created by default. Set this to False to raise an AttributeError instead
Return type:

RecursiveStub

mocktest.mocking.modify(obj)

Replace children of an existing object for the duration of this test. E.g:

>>> modify(obj).child = replacement_child
>>> modify(obj).grand.child = replacement_grand_child
>>> modify(obj)['item'] = replacement_item

All replaced attributes / items will be reverted when the test completes.

Return type:RecursiveAssignmentWrapper
class mocktest.mocking.Object(name='unnamed object')

a named object

Indirectly-used classes

These classes are not exposed for you to instantiate, but instances are returned instances from other (public) methods:

class mocktest.mocking.RecursiveStub(name='unnamed object', create_unknown_children=True)

The return value from mock().

An object that returns new instances of itself when attributes are accessed (unless create_unknown_children is False).

Returns None (and saves the call information) when called

with_children(**children)

Set children via kwargs, e.g.:

>>> mock("name").with_children(x=1, y='child y')
>>> obj.x
1
>>> obj.y
'child y'
with_methods(**methods)

Set child methods via kwargs, e.g.:

>>> mock("name").with_methods(x=1, y=mock('child y'))
>>> obj.x()
1
>>> obj.y()
'child y'
class mocktest.mocking.RecursiveAssignmentWrapper(delegate, modify_delegate=True)

The return value from modify().

Assigning a value to an attribute of this object assigns the same value to the original object, but only for the duration of the current test.

The same goes for items (i.e dictionary-style access).

Getting an attribute or item from this object replaces that item on the original object with a wrapped version that always supports assignment of attributes / items. This is useful e.g to replace readonly attributes on nested objects:

# does NOT work, as write is not assignable >>> modify(sys.stderr).write = my_write_func

# but we can work around it, by replacing the whole stderr # object with one that has all the values of the real stderr # but allowing us to override of any attribute: >>> modify(sys).stderr.write = my_write_func

children(**children)

Set children via kwargs, e.g.:

>>> modify(obj).children(x=1, y='child y')
>>> obj.x
1
>>> obj.y
'child y'
copying(other, value=<function <lambda> at 0x7f1d0755f8c0>)

Copy all non-special attributes of other, setting the value of each child to value. The default value paramater is a function returning None for all arguments.

methods(**methods)

Set child methods via kwargs, e.g.:

>>> modify(obj).methods(x=1, y=mock('child y'))

Setting expectations

class mocktest.mocking.MockAct(name)

The return type from when() and expect().

__call__(*a, **kw)

Set the conditions under which this act will apply. Arguments can be normal objects (checked for equality), or Matcher instances.

and_call(func)

When this act matches, call the given func and return its value.

and_raise(exc)

When this act matches, raise the given exception instance.

and_return(val, *subsequent_vals)

When this act matches, return the given result to the caller. If provided with multiple arguments, those values will be returned in order. e.g:

>>> expect(obj).foo().and_return(True, True, False)
>>> obj.foo()
True
>>> obj.foo()
True
>>> obj.foo()
False

Once all return values have been used up, any further calls with throw a MockError.

Note: and_raise(), and_return() and and_call() each have a then_* alias for better readability when using when(). e.g:

>>> expect(obj).foo().and_return(True)

Is readable, however when using when(), the following is more readable:

>>> when(obj).foo().then_return(True)

Both and_ and then_ versions have the same effect however.

at_least(n)

Expect this act to match at least number times.

at_most(n)

Expect this act to match at most number times.

between(start_range, end_range)

Expect this act to match between lower and upper times.

exactly(n)

Expect this act to be triggered exactly number times. Usually followed by times() for readability, as in:

>>> expect(obj).meth.exactly(3).times()
never()

Alias for exactly(0).times

once()

Alias for exactly(1).times

then_call(func)

When this act matches, call the given func and return its value.

then_raise(exc)

When this act matches, raise the given exception instance.

then_return(val, *subsequent_vals)

When this act matches, return the given result to the caller. If provided with multiple arguments, those values will be returned in order. e.g:

>>> expect(obj).foo().and_return(True, True, False)
>>> obj.foo()
True
>>> obj.foo()
True
>>> obj.foo()
False

Once all return values have been used up, any further calls with throw a MockError.

Note: and_raise(), and_return() and and_call() each have a then_* alias for better readability when using when(). e.g:

>>> expect(obj).foo().and_return(True)

Is readable, however when using when(), the following is more readable:

>>> when(obj).foo().then_return(True)

Both and_ and then_ versions have the same effect however.

thrice()

Alias for exactly(3).times

twice()

Alias for exactly(2).times

where(func)

Match only when condition_func returns true, when called with the same arguments as this method.

class mocktest.mocking.StubbedMethod(name)
This is the type that mocktest uses as a stand-in for a replaced (stubbed) method. For example:
>>> when(obj).method().then_return(True)

Will set obj.method to an instance of StubbedMethod (for the duration of the current test)

received_calls:

The set of calls this stub has received, as a list of Call instances.

Mock Transaction

Call Records

class mocktest.callrecord.Call(args, kwargs, stack=False)

An encapsulation of call arguments. Can compare for equality with a tuple of (args, kwargs), e.g:

>>> Call.like(1,2,3, x=4) == ((1,2,3), {'x':4})
True
Parameters:
  • args (tuple) – non-keyword arguments
  • kwargs (dict) – keyword arguments
  • stack – If True, a stack trace is captured for reporting where a given call was made.
Members :

args, kwargs

classmethod like(*a, **kw)

capture a call with the given arguments

play(function)

apply this call’s arguments to the given callable

Table Of Contents

This Page