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 boilder plate was necessary to create a mock that would act as a factory. Using StubOutClassWithMocks, 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.VerifyAll()
# 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.VerifyAll()
-
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.
-
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.
-
next
()¶ Raise a TypeError with a helpful message.
-
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.
-
-
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.
-
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
(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
() → list¶ return a type’s method resolution order
-
static
-
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.
-
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 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 signficant digit).
If the two objects compare equal then they will automatically compare almost equal.
-
assertAlmostEquals
(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 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 signficant digit).
If the two objects compare equal then they will automatically compare almost equal.
-
assertDictContainsSubset
(expected, actual, msg=None)¶ Checks whether actual is a superset of expected.
-
assertEqual
(first, second, msg=None)¶ Fail if the two objects are unequal as determined by the ‘==’ operator.
-
assertEquals
(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.
-
assertItemsEqual
(expected_seq, actual_seq, msg=None)¶ An unordered sequence specific comparison. It asserts that actual_seq and expected_seq have the same element counts. Equivalent to:
self.assertEqual(Counter(iter(actual_seq)), Counter(iter(expected_seq)))
Asserts that each element has the same count in both sequences. Example:
- [0, 1, 1] and [1, 0, 1] compare equal.
- [0, 0, 1] and [0, 1] compare unequal.
-
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.
-
assertMultiLineEqual
(first, second, msg=None)¶ Assert that two multi-line strings are equal.
-
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 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 signficant digit).
Objects that are equal automatically fail.
-
assertNotAlmostEquals
(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 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 signficant digit).
Objects that are equal automatically fail.
-
assertNotEqual
(first, second, msg=None)¶ Fail if the two objects are equal as determined by the ‘!=’ operator.
-
assertNotEquals
(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.
-
assertNotRegexpMatches
(text, unexpected_regexp, msg=None)¶ Fail the test if the text matches the regular expression.
-
assertRaises
(excClass, callableObj=None, *args, **kwargs)¶ Fail unless an exception of class excClass is raised by callableObj when invoked with arguments args and keyword arguments kwargs. 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 callableObj omitted or None, will return a context object used like this:
with self.assertRaises(SomeException): do_something()
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)
-
assertRaisesRegexp
(expected_exception, expected_regexp, callable_obj=None, *args, **kwargs)¶ Asserts that the message in a raised exception matches a regexp.
- Args:
expected_exception: Exception class expected to be raised. expected_regexp: Regexp (re pattern object or string) expected
to be found in error message.callable_obj: Function to be called. args: Extra args. kwargs: Extra kwargs.
-
assertRegexpMatches
(text, expected_regexp, 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.
-
assert_
(expr, msg=None)¶ Check that the expression is true.
-
debug
()¶ Run the test without collecting errors in a TestResult
-
doCleanups
()¶ Execute all cleanup functions. Normally called for you after tearDown.
-
fail
(msg=None)¶ Fail immediately, with the given message.
-
failureException
¶ alias of
AssertionError
-
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.
-
tearDown
()¶ Hook method for deconstructing the test fixture after testing it.
-
tearDownClass
()¶ Hook method for deconstructing the class fixture after running all tests in the class.
-
Functions¶
-
class
mox.
Replay
¶ Put mocks into Replay mode.
- Args:
- # args is any number of mocks to put into replay mode.
-
class
mox.
Verify
¶ Verify mocks.
- Args:
- # args is any number of mocks to be verified.
-
class
mox.
Reset
¶ Reset mocks.
- Args:
- # args is any number of mocks to be reset.
Exceptions¶
-
class
mox.
Error
¶ Base exception for this module.
-
class
mox.
ExpectedMethodCallsError
(expected_methods)¶ Raised when Verify() is called before all expected methods have been called
-
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.
-
class
mox.
UnknownMethodCallError
(unknown_method_name)¶ Raised if an unknown method is requested of the mock object.
-
class
mox.
PrivateAttributeError
(attr)¶ Raised if a MockObject is passed a private additional attribute name.
-
class
mox.
ExpectedMockCreationError
(expected_mocks)¶ Raised if mocks should have been created by StubOutClassWithMocks.
-
class
mox.
UnexpectedMockCreationError
(instance, *params, **named_params)¶ Raised if too many mocks were created by StubOutClassWithMocks.