Pymox Reference

Mox

class mox.Mox

Mox: a factory for creating mock objects.

CreateMock(class_to_mock, attrs=None)

Create a new mock object.

Args:

# class_to_mock: the class to be mocked class_to_mock: class attrs: dict of attribute names to values that will be set on the mock

object. Only public attributes may be set.
Returns:
MockObject that can be used as the class_to_mock would be.
CreateMockAnything(description=None)

Create a mock that will accept any method calls.

This does not enforce an interface.

Args:
description: str. Optionally, a descriptive name for the mock object
being created, for debugging output purposes.
ReplayAll()

Set all mock objects to replay mode.

ResetAll()

Call reset on all mock objects. This does not unset stubs.

StubOutClassWithMocks(obj, attr_name)

Replace a class with a “mock factory” that will create mock objects.

This is useful if the code-under-test directly instantiates dependencies. Previously some boilerplate was necessary to create a mock that would act as a factory. Using stubout_class, once you’ve stubbed out the class you may use the stubbed class as you would any other mock created by mox: during the record phase, new mock instances will be created, and during replay, the recorded mocks will be returned.

In replay mode

# Example using StubOutWithMock (the old, clunky way):

mock1 = mox.CreateMock(my_import.FooClass) mock2 = mox.CreateMock(my_import.FooClass) foo_factory = mox.StubOutWithMock(my_import, ‘FooClass’,

use_mock_anything=True)

foo_factory(1, 2).AndReturn(mock1) foo_factory(9, 10).AndReturn(mock2) mox.ReplayAll()

my_import.FooClass(1, 2) # Returns mock1 again. my_import.FooClass(9, 10) # Returns mock2 again. mox.verify_all()

# Example using StubOutClassWithMocks:

mox.StubOutClassWithMocks(my_import, ‘FooClass’) mock1 = my_import.FooClass(1, 2) # Returns a new mock of FooClass mock2 = my_import.FooClass(9, 10) # Returns another mock instance mox.ReplayAll()

my_import.FooClass(1, 2) # Returns mock1 again. my_import.FooClass(9, 10) # Returns mock2 again. mox.verify_all()

StubOutWithMock(obj, attr_name, use_mock_anything=False)

Replace a method, attribute, etc. with a Mock.

This will replace a class or module with a MockObject, and everything else (method, function, etc) with a MockAnything. This can be overridden to always use a MockAnything by setting use_mock_anything to True.

Args:

obj: A Python object (class, module, instance, callable). attr_name: str. The name of the attribute to replace with a mock. use_mock_anything: bool. True if a MockAnything should be used

regardless of the type of attribute.
UnsetStubs()

Restore stubs to their original state.

VerifyAll()

Call verify on all mock objects created.

create_mock(class_to_mock, attrs=None)

Create a new mock object.

Args:

# class_to_mock: the class to be mocked class_to_mock: class attrs: dict of attribute names to values that will be set on the mock

object. Only public attributes may be set.
Returns:
MockObject that can be used as the class_to_mock would be.
create_mock_anything(description=None)

Create a mock that will accept any method calls.

This does not enforce an interface.

Args:
description: str. Optionally, a descriptive name for the mock object
being created, for debugging output purposes.
replay_all()

Set all mock objects to replay mode.

reset_all()

Call reset on all mock objects. This does not unset stubs.

stubout(obj, attr_name, use_mock_anything=False)

Replace a method, attribute, etc. with a Mock.

This will replace a class or module with a MockObject, and everything else (method, function, etc) with a MockAnything. This can be overridden to always use a MockAnything by setting use_mock_anything to True.

Args:

obj: A Python object (class, module, instance, callable). attr_name: str. The name of the attribute to replace with a mock. use_mock_anything: bool. True if a MockAnything should be used

regardless of the type of attribute.
stubout_class(obj, attr_name)

Replace a class with a “mock factory” that will create mock objects.

This is useful if the code-under-test directly instantiates dependencies. Previously some boilerplate was necessary to create a mock that would act as a factory. Using stubout_class, once you’ve stubbed out the class you may use the stubbed class as you would any other mock created by mox: during the record phase, new mock instances will be created, and during replay, the recorded mocks will be returned.

In replay mode

# Example using StubOutWithMock (the old, clunky way):

mock1 = mox.CreateMock(my_import.FooClass) mock2 = mox.CreateMock(my_import.FooClass) foo_factory = mox.StubOutWithMock(my_import, ‘FooClass’,

use_mock_anything=True)

foo_factory(1, 2).AndReturn(mock1) foo_factory(9, 10).AndReturn(mock2) mox.ReplayAll()

my_import.FooClass(1, 2) # Returns mock1 again. my_import.FooClass(9, 10) # Returns mock2 again. mox.verify_all()

# Example using StubOutClassWithMocks:

mox.StubOutClassWithMocks(my_import, ‘FooClass’) mock1 = my_import.FooClass(1, 2) # Returns a new mock of FooClass mock2 = my_import.FooClass(9, 10) # Returns another mock instance mox.ReplayAll()

my_import.FooClass(1, 2) # Returns mock1 again. my_import.FooClass(9, 10) # Returns mock2 again. mox.verify_all()

unset_stubs()

Restore stubs to their original state.

verify_all()

Call verify on all mock objects created.

MockAnything

class mox.MockAnything(description=None)

A mock that can be used to mock anything.

This is helpful for mocking classes that do not provide a public interface.

MockObject

class mox.MockObject(class_to_mock, attrs=None)

A mock object that simulates the public/protected interface of a class.

MethodCallChecker

MockMethod

class mox.MockMethod(method_name, call_queue, exception_list, replay_mode, method_to_mock=None, description=None)

Callable mock method.

A MockMethod should act exactly like the method it mocks, accepting parameters and returning a value, or throwing an exception (as specified). When this method is called, it can optionally verify whether the called method (name and signature) matches the expected method.

AndRaise(exception)

Set the exception to raise when this method is called.

Args:
# exception: the exception to raise when this method is called. exception: Exception
AndReturn(return_value)

Set the value to return when this method is called.

Args:
# return_value can be anything.
GetPossibleGroup()

Returns a possible group from the end of the call queue or None if no other methods are on the stack.

InAnyOrder(group_name='default')

Move this method into a group of unordered calls.

A group of unordered calls must be defined together, and must be executed in full before the next expected method can be called. There can be multiple groups that are expected serially, if they are given different group names. The same group name can be reused if there is a standard method call, or a group with a different name, spliced between usages.

Args:
group_name: the name of the unordered group.
Returns:
self
MultipleTimes(group_name='default')

Move this method into group of calls which may be called multiple times.

A group of repeating calls must be defined together, and must be executed in full before the next expected method can be called.

Args:
group_name: the name of the unordered group.
Returns:
self
WithSideEffects(side_effects)

Set the side effects that are simulated when this method is called.

Args:
side_effects: A callable which modifies the parameters or other
relevant state which a given test case depends on.
Returns:
Self for chaining with AndReturn and AndRaise.
any_order(group_name='default')

Move this method into a group of unordered calls.

A group of unordered calls must be defined together, and must be executed in full before the next expected method can be called. There can be multiple groups that are expected serially, if they are given different group names. The same group name can be reused if there is a standard method call, or a group with a different name, spliced between usages.

Args:
group_name: the name of the unordered group.
Returns:
self
get_possible_group()

Returns a possible group from the end of the call queue or None if no other methods are on the stack.

multiple_times(group_name='default')

Move this method into group of calls which may be called multiple times.

A group of repeating calls must be defined together, and must be executed in full before the next expected method can be called.

Args:
group_name: the name of the unordered group.
Returns:
self
next()

Raise a TypeError with a helpful message.

raises(exception)

Set the exception to raise when this method is called.

Args:
# exception: the exception to raise when this method is called. exception: Exception
returns(return_value)

Set the value to return when this method is called.

Args:
# return_value can be anything.
with_side_effects(side_effects)

Set the side effects that are simulated when this method is called.

Args:
side_effects: A callable which modifies the parameters or other
relevant state which a given test case depends on.
Returns:
Self for chaining with AndReturn and AndRaise.

Comparators

class mox.Comparator

Base class for all Mox comparators.

A Comparator can be used as a parameter to a mocked method when the exact value is not known. For example, the code you are testing might build up a long SQL string that is passed to your mock DAO. You’re only interested that the IN clause contains the proper primary keys, so you can set your mock up as follows:

mock_dao.RunQuery(StrContains(‘IN (1, 2, 4, 5)’)).AndReturn(mock_result)

Now whatever query is passed in must contain the string ‘IN (1, 2, 4, 5)’.

A Comparator may replace one or more parameters, for example: # return at most 10 rows mock_dao.RunQuery(StrContains(‘SELECT’), 10)

or

# Return some non-deterministic number of rows mock_dao.RunQuery(StrContains(‘SELECT’), IsA(int))

equals(rhs)

Special equals method that all comparators must implement.

Args:
rhs: any python object
class mox.IsA(class_name)

This class wraps a basic Python type or class. It is used to verify that a parameter is of the given type or class.

Example: mock_dao.Connect(IsA(DbConnectInfo))

equals(rhs)

Check to see if the RHS is an instance of class_name.

Args:
# rhs: the right hand side of the test rhs: object
Returns:
bool
class mox.IsAlmost(float_value, places=7)

Comparison class used to check whether a parameter is nearly equal to a given value. Generally useful for floating point numbers.

Example mock_dao.SetTimeout((IsAlmost(3.9)))

equals(rhs)

Check to see if RHS is almost equal to float_value

Args:
rhs: the value to compare to float_value
Returns:
bool
class mox.StrContains(search_string)

Comparison class used to check whether a substring exists in a string parameter. This can be useful in mocking a database with SQL passed in as a string parameter, for example.

Example: mock_dao.RunQuery(StrContains(‘IN (1, 2, 4, 5)’)).AndReturn(mock_result)

equals(rhs)

Check to see if the search_string is contained in the rhs string.

Args:
# rhs: the right hand side of the test rhs: object
Returns:
bool
class mox.Regex(pattern, flags=0)

Checks if a string matches a regular expression.

This uses a given regular expression to determine equality.

equals(rhs)

Check to see if rhs matches regular expression pattern.

Returns:
bool
class mox.In(key)

Checks whether an item (or key) is in a list (or dict) parameter.

Example: mock_dao.GetUsersInfo(In(‘expectedUserName’)).AndReturn(mock_result)

equals(rhs)

Check to see whether key is in rhs.

Args:
rhs: dict
Returns:
bool
class mox.Not(predicate)

Checks whether a predicates is False.

Example:
mock_dao.UpdateUsers(Not(ContainsKeyValue(‘stevepm’, stevepm_user_info)))
equals(rhs)

Check to see whether the predicate is False.

Args:
rhs: A value that will be given in argument of the predicate.
Returns:
bool
class mox.ContainsKeyValue(key, value)

Checks whether a key/value pair is in a dict parameter.

Example: mock_dao.UpdateUsers(ContainsKeyValue(‘stevepm’, stevepm_user_info))

equals(rhs)

Check whether the given key/value pair is in the rhs dict.

Returns:
bool
class mox.ContainsAttributeValue(key, value)

Checks whether a passed parameter contains attributes with a given value.

Example: mock_dao.UpdateSomething(ContainsAttribute(‘stevepm’, stevepm_user_info))

equals(rhs)

Check whether the given attribute has a matching value in the rhs object.

Returns:
bool
class mox.SameElementsAs(expected_seq)

Checks whether sequences contain the same elements (ignoring order).

Example: mock_dao.ProcessUsers(SameElementsAs(‘stevepm’, ‘salomaki’))

equals(actual_seq)

Check to see whether actual_seq has same elements as expected_seq.

Args:
actual_seq: sequence
Returns:
bool
class mox.And(*args)

Evaluates one or more Comparators on RHS and returns an AND of the results.

equals(rhs)

Checks whether all Comparators are equal to rhs.

Args:
# rhs: can be anything
Returns:
bool
class mox.Or(*args)

Evaluates one or more Comparators on RHS and returns an OR of the results.

equals(rhs)

Checks whether any Comparator is equal to rhs.

Args:
# rhs: can be anything
Returns:
bool
class mox.Func(func)

Call a function that should verify the parameter passed in is correct.

You may need the ability to perform more advanced operations on the parameter in order to validate it. You can use this to have a callable validate any parameter. The callable should return either True or False.

Example:

def myParamValidator(param):
# Advanced logic here return True

mock_dao.DoSomething(Func(myParamValidator), true)

equals(rhs)

Test whether rhs passes the function test.

rhs is passed into func.

Args:
rhs: any python object
Returns:
the result of func(rhs)
class mox.IgnoreArg

Ignore an argument.

This can be used when we don’t care about an argument of a method call.

Example: # Check if CastMagic is called with 3 as first arg and ‘disappear’ as third. mymock.CastMagic(3, IgnoreArg(), ‘disappear’)

equals(unused_rhs)

Ignores arguments and returns True.

Args:
unused_rhs: any python object
Returns:
always returns True

Method Groups

class mox.MethodGroup(group_name, exception_list)

Base class containing common behaviour for MethodGroups.

class mox.UnorderedGroup(group_name, exception_list)

UnorderedGroup holds a set of method calls that may occur in any order.

This construct is helpful for non-deterministic events, such as iterating over the keys of a dict.

AddMethod(mock_method)

Add a method to this group.

Args:
mock_method: A mock method to be added to this group.
IsSatisfied()

Return True if there are not any methods in this group.

MethodCalled(mock_method)

Remove a method call from the group.

If the method is not in the set, an UnexpectedMethodCallError will be raised.

Args:
mock_method: a mock method that should be equal to a method in the group.
Returns:
The mock method from the group
Raises:
UnexpectedMethodCallError if the mock_method was not in the group.
add_method(mock_method)

Add a method to this group.

Args:
mock_method: A mock method to be added to this group.
is_satisfied()

Return True if there are not any methods in this group.

method_called(mock_method)

Remove a method call from the group.

If the method is not in the set, an UnexpectedMethodCallError will be raised.

Args:
mock_method: a mock method that should be equal to a method in the group.
Returns:
The mock method from the group
Raises:
UnexpectedMethodCallError if the mock_method was not in the group.
class mox.MultipleTimesGroup(group_name, exception_list)

MultipleTimesGroup holds methods that may be called any number of times.

Note: Each method must be called at least once.

This is helpful, if you don’t know or care how many times a method is called.

AddMethod(mock_method)

Add a method to this group.

Args:
mock_method: A mock method to be added to this group.
IsSatisfied()

Return True if all methods in this group are called at least once.

MethodCalled(mock_method)

Remove a method call from the group.

If the method is not in the set, an UnexpectedMethodCallError will be raised.

Args:
mock_method: a mock method that should be equal to a method in the
group.
Returns:
The mock method from the group
Raises:
UnexpectedMethodCallError if the mock_method was not in the group.
add_method(mock_method)

Add a method to this group.

Args:
mock_method: A mock method to be added to this group.
is_satisfied()

Return True if all methods in this group are called at least once.

method_called(mock_method)

Remove a method call from the group.

If the method is not in the set, an UnexpectedMethodCallError will be raised.

Args:
mock_method: a mock method that should be equal to a method in the
group.
Returns:
The mock method from the group
Raises:
UnexpectedMethodCallError if the mock_method was not in the group.

Testing

class mox.MoxMetaTestBase(name, bases, d)

Metaclass to add mox cleanup and verification to every test. As the mox unit testing class is being constructed (MoxTestBase or a subclass), this metaclass will modify all test functions to call the CleanUpMox method of the test class after they finish. This means that unstubbing and verifying will happen for every test with no additional code, and any failures will result in test failures as opposed to errors.

static CleanUpTest(cls, func)

Adds Mox cleanup code to any MoxTestBase method. Always unsets stubs after a test. Will verify all mocks for tests that otherwise pass. Args:

cls: MoxTestBase or subclass; the class whose test method we are
altering.
func: method; the method of the MoxTestBase test class we wish to
alter.
Returns:
The modified method.
static clean_up_test(cls, func)

Adds Mox cleanup code to any MoxTestBase method. Always unsets stubs after a test. Will verify all mocks for tests that otherwise pass. Args:

cls: MoxTestBase or subclass; the class whose test method we are
altering.
func: method; the method of the MoxTestBase test class we wish to
alter.
Returns:
The modified method.
mro()

Return a type’s method resolution order.

class mox.MoxTestBase(methodName='runTest')

Convenience test class to make stubbing easier. Sets up a “mox” attribute which is an instance of Mox (any mox tests will want this), and a “stubs” attribute that is an instance of StubOutForTesting (needed at times). Also automatically unsets any stubs and verifies that all mock methods have been called at the end of each test, eliminating boilerplate code.

classmethod addClassCleanup(function, *args, **kwargs)

Same as addCleanup, except the cleanup items are called even if setUpClass fails (unlike tearDownClass).

addCleanup(function, *args, **kwargs)

Add a function, with arguments, to be called when the test is completed. Functions added are called on a LIFO basis and are called after tearDown on test failure or success.

Cleanup items are called even if setUp fails (unlike tearDown).

addTypeEqualityFunc(typeobj, function)

Add a type specific assertEqual style function to compare a type.

This method is for use by TestCase subclasses that need to register their own type equality functions to provide nicer error messages.

Args:
typeobj: The data type to call this function on when both values
are of the same type in assertEqual().
function: The callable taking two arguments and an optional
msg= argument that raises self.failureException with a useful error message when the two arguments are not equal.
assertAlmostEqual(first, second, places=None, msg=None, delta=None)

Fail if the two objects are unequal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is more than the given delta.

Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit).

If the two objects compare equal then they will automatically compare almost equal.

assertCountEqual(first, second, msg=None)

Asserts that two iterables have the same elements, the same number of times, without regard to order.

self.assertEqual(Counter(list(first)),
Counter(list(second)))
Example:
  • [0, 1, 1] and [1, 0, 1] compare equal.
  • [0, 0, 1] and [0, 1] compare unequal.
assertDictContainsSubset(subset, dictionary, msg=None)

Checks whether dictionary is a superset of subset.

assertEqual(first, second, msg=None)

Fail if the two objects are unequal as determined by the ‘==’ operator.

assertFalse(expr, msg=None)

Check that the expression is false.

assertGreater(a, b, msg=None)

Just like self.assertTrue(a > b), but with a nicer default message.

assertGreaterEqual(a, b, msg=None)

Just like self.assertTrue(a >= b), but with a nicer default message.

assertIn(member, container, msg=None)

Just like self.assertTrue(a in b), but with a nicer default message.

assertIs(expr1, expr2, msg=None)

Just like self.assertTrue(a is b), but with a nicer default message.

assertIsInstance(obj, cls, msg=None)

Same as self.assertTrue(isinstance(obj, cls)), with a nicer default message.

assertIsNone(obj, msg=None)

Same as self.assertTrue(obj is None), with a nicer default message.

assertIsNot(expr1, expr2, msg=None)

Just like self.assertTrue(a is not b), but with a nicer default message.

assertIsNotNone(obj, msg=None)

Included for symmetry with assertIsNone.

assertLess(a, b, msg=None)

Just like self.assertTrue(a < b), but with a nicer default message.

assertLessEqual(a, b, msg=None)

Just like self.assertTrue(a <= b), but with a nicer default message.

assertListEqual(list1, list2, msg=None)

A list-specific equality assertion.

Args:

list1: The first list to compare. list2: The second list to compare. msg: Optional message to use on failure instead of a list of

differences.
assertLogs(logger=None, level=None)

Fail unless a log message of level level or higher is emitted on logger_name or its children. If omitted, level defaults to INFO and logger defaults to the root logger.

This method must be used as a context manager, and will yield a recording object with two attributes: output and records. At the end of the context manager, the output attribute will be a list of the matching formatted log messages and the records attribute will be a list of the corresponding LogRecord objects.

Example:

with self.assertLogs('foo', level='INFO') as cm:
    logging.getLogger('foo').info('first message')
    logging.getLogger('foo.bar').error('second message')
self.assertEqual(cm.output, ['INFO:foo:first message',
                             'ERROR:foo.bar:second message'])
assertMultiLineEqual(first, second, msg=None)

Assert that two multi-line strings are equal.

assertNoLogs(logger=None, level=None)

Fail unless no log messages of level level or higher are emitted on logger_name or its children.

This method must be used as a context manager.

assertNotAlmostEqual(first, second, places=None, msg=None, delta=None)

Fail if the two objects are equal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is less than the given delta.

Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit).

Objects that are equal automatically fail.

assertNotEqual(first, second, msg=None)

Fail if the two objects are equal as determined by the ‘!=’ operator.

assertNotIn(member, container, msg=None)

Just like self.assertTrue(a not in b), but with a nicer default message.

assertNotIsInstance(obj, cls, msg=None)

Included for symmetry with assertIsInstance.

assertNotRegex(text, unexpected_regex, msg=None)

Fail the test if the text matches the regular expression.

assertRaises(expected_exception, *args, **kwargs)

Fail unless an exception of class expected_exception is raised by the callable when invoked with specified positional and keyword arguments. If a different type of exception is raised, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception.

If called with the callable and arguments omitted, will return a context object used like this:

with self.assertRaises(SomeException):
    do_something()

An optional keyword argument ‘msg’ can be provided when assertRaises is used as a context object.

The context manager keeps a reference to the exception as the ‘exception’ attribute. This allows you to inspect the exception after the assertion:

with self.assertRaises(SomeException) as cm:
    do_something()
the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)
assertRaisesRegex(expected_exception, expected_regex, *args, **kwargs)

Asserts that the message in a raised exception matches a regex.

Args:

expected_exception: Exception class expected to be raised. expected_regex: Regex (re.Pattern object or string) expected

to be found in error message.

args: Function to be called and extra positional args. kwargs: Extra kwargs. msg: Optional message used in case of failure. Can only be used

when assertRaisesRegex is used as a context manager.
assertRegex(text, expected_regex, msg=None)

Fail the test unless the text matches the regular expression.

assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)

An equality assertion for ordered sequences (like lists and tuples).

For the purposes of this function, a valid ordered sequence type is one which can be indexed, has a length, and has an equality operator.

Args:

seq1: The first sequence to compare. seq2: The second sequence to compare. seq_type: The expected datatype of the sequences, or None if no

datatype should be enforced.
msg: Optional message to use on failure instead of a list of
differences.
assertSetEqual(set1, set2, msg=None)

A set-specific equality assertion.

Args:

set1: The first set to compare. set2: The second set to compare. msg: Optional message to use on failure instead of a list of

differences.

assertSetEqual uses ducktyping to support different types of sets, and is optimized for sets specifically (parameters must support a difference method).

assertTrue(expr, msg=None)

Check that the expression is true.

assertTupleEqual(tuple1, tuple2, msg=None)

A tuple-specific equality assertion.

Args:

tuple1: The first tuple to compare. tuple2: The second tuple to compare. msg: Optional message to use on failure instead of a list of

differences.
assertWarns(expected_warning, *args, **kwargs)

Fail unless a warning of class warnClass is triggered by the callable when invoked with specified positional and keyword arguments. If a different type of warning is triggered, it will not be handled: depending on the other warning filtering rules in effect, it might be silenced, printed out, or raised as an exception.

If called with the callable and arguments omitted, will return a context object used like this:

with self.assertWarns(SomeWarning):
    do_something()

An optional keyword argument ‘msg’ can be provided when assertWarns is used as a context object.

The context manager keeps a reference to the first matching warning as the ‘warning’ attribute; similarly, the ‘filename’ and ‘lineno’ attributes give you information about the line of Python code from which the warning was triggered. This allows you to inspect the warning after the assertion:

with self.assertWarns(SomeWarning) as cm:
    do_something()
the_warning = cm.warning
self.assertEqual(the_warning.some_attribute, 147)
assertWarnsRegex(expected_warning, expected_regex, *args, **kwargs)

Asserts that the message in a triggered warning matches a regexp. Basic functioning is similar to assertWarns() with the addition that only warnings whose messages also match the regular expression are considered successful matches.

Args:

expected_warning: Warning class expected to be triggered. expected_regex: Regex (re.Pattern object or string) expected

to be found in error message.

args: Function to be called and extra positional args. kwargs: Extra kwargs. msg: Optional message used in case of failure. Can only be used

when assertWarnsRegex is used as a context manager.
debug()

Run the test without collecting errors in a TestResult

classmethod doClassCleanups()

Execute all class cleanup functions. Normally called for you after tearDownClass.

doCleanups()

Execute all cleanup functions. Normally called for you after tearDown.

classmethod enterClassContext(cm)

Same as enterContext, but class-wide.

enterContext(cm)

Enters the supplied context manager.

If successful, also adds its __exit__ method as a cleanup function and returns the result of the __enter__ method.

fail(msg=None)

Fail immediately, with the given message.

failureException

alias of builtins.AssertionError

setUp()

Hook method for setting up the test fixture before exercising it.

classmethod setUpClass()

Hook method for setting up class fixture before running tests in the class.

shortDescription()

Returns a one-line description of the test, or None if no description has been provided.

The default implementation of this method returns the first line of the specified test method’s docstring.

skipTest(reason)

Skip this test.

subTest(msg=<object object>, **params)

Return a context manager that will return the enclosed block of code in a subtest identified by the optional message and keyword parameters. A failure in the subtest marks the test case as failed but resumes execution at the end of the enclosed block, allowing further test code to be executed.

tearDown()

Hook method for deconstructing the test fixture after testing it.

classmethod tearDownClass()

Hook method for deconstructing the class fixture after running all tests in the class.

Functions

mox.Replay

alias of mox.mox.replay

mox.Verify

alias of mox.mox.verify

mox.Reset

alias of mox.mox.reset

Exceptions

class mox.Error

Base exception for this module.

add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class mox.ExpectedMethodCallsError(expected_methods)

Raised when Verify() is called before all expected methods have been called

add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class mox.UnexpectedMethodCallError(unexpected_method, expected)

Raised when an unexpected method is called.

This can occur if a method is called with incorrect parameters, or out of the specified order.

add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class mox.UnknownMethodCallError(unknown_method_name)

Raised if an unknown method is requested of the mock object.

add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class mox.PrivateAttributeError(attr)

Raised if a MockObject is passed a private additional attribute name.

add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class mox.ExpectedMockCreationError(expected_mocks)

Raised if mocks should have been created by StubOutClassWithMocks.

add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class mox.UnexpectedMockCreationError(instance, *params, **named_params)

Raised if too many mocks were created by StubOutClassWithMocks.

add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.