The functions¶
Stable entrypoints are: when(), expect(), mock(), unstub(),
verify(), spy().
New function introduced in v1 are: when2(), verifyExpectedInteractions(), verifyStubbedInvocationsAreUsed(), patch().
New function introduced in v2 are: patch_attr(), patch_dict()
- mockito.when(obj, strict=True)¶
Central interface to stub functions on a given obj
obj should be a module, a class or an instance of a class; it can be a Dummy you created with
mock().whenexposes a fluent interface where you configure a stub in three steps:when(<obj>).<method_name>(<args>).thenReturn(<value>)
Compared to simple patching, stubbing in mockito requires you to specify concrete args for which the stub will answer with a concrete <value>. All invocations that do not match this specific call signature will be rejected. They usually throw at call time.
Stubbing in mockito’s sense thus means not only to get rid of unwanted side effects, but effectively to turn function calls into constants.
E.g.:
# Given ``dog`` is an instance of a ``Dog`` when(dog).bark('Grrr').thenReturn('Wuff') when(dog).bark('Miau').thenRaise(TypeError()) # With this configuration set up: assert dog.bark('Grrr') == 'Wuff' dog.bark('Miau') # will throw TypeError dog.bark('Wuff') # will throw unwanted interaction
Stubbing can effectively be used as monkeypatching; usage shown with the with context managing:
with when(os.path).exists('/foo').thenReturn(True): ...
Most of the time verifying your interactions is not necessary, because your code under tests implicitly verifies the return value by evaluating it. See
verify()if you need to, see alsoexpect()to setup expected call counts up front.If your function is pure side effect and does not return something, you can omit the specific answer. The function will then return None as by default for Python functions:
when(manager).do_work().thenReturn() # However, using `expect` may read better. expect(manager).do_work()
when verifies the method name, the expected argument signature, and the actual, factual arguments your code under test uses against the original object and its function so its easier to spot changing interfaces.
Sometimes it’s tedious to spell out all arguments:
from mockito import ANY, ARGS, KWARGS when(requests).get('http://example.com/', **KWARGS).thenReturn(...) when(os.path).exists(ANY) when(os.path).exists(ANY(str))
Note
You must
unstub()after stubbing, or use with statement.Set
strict=Falseto bypass the function signature checks.See related
when2()which has a more pythonic interface.
- mockito.expect(obj, strict=True, times=None, atleast=None, atmost=None, between=None)¶
Stub a function call, and set up an expected call count.
Usage:
# Given `dog` is an instance of a `Dog` expect(dog, times=1).bark('Wuff').thenReturn('Miau') dog.bark('Wuff') dog.bark('Wuff') # will throw at call time: too many invocations # maybe if you need to ensure that `dog.bark()` was called at all verifyExpectedInteractions()
Note
You must
unstub()after stubbing, or use with statement.
- mockito.mock(config_or_spec=None, spec=None, strict=OMITTED)¶
Create ‘empty’ objects (‘Mocks’).
Will create an empty unconfigured object, that you can pass around. All interactions (method calls) will be recorded and can be verified using
verify()et.al.A plain mock() will be not strict, and thus all methods regardless of the arguments will return
None.Note
Technically all attributes will return an internal interface. Because of that a simple
if mock().foo:will surprisingly pass.If you set strict to
True:mock(strict=True)all unexpected interactions will raise an error instead.You configure a mock using
when(),when2()orexpect(). You can also very conveniently just pass in a dict here:response = mock({'text': 'ok', 'raise_for_status': lambda: None})
You can also create an empty Mock which is specced against a given spec:
mock(requests.Response). These mock are by default strict, thus they raise if you want to stub a method, the spec does not implement. Mockito will also match the function signature.You can pre-configure a specced mock as well:
response = mock({'json': lambda: {'status': 'Ok'}}, spec=requests.Response)
Mocks are by default callable. Configure the callable behavior using when:
dummy = mock() when(dummy).__call__(1).thenReturn(2)
All other magic methods must be configured this way or they will raise an AttributeError.
See
verify()to verify your interactions after usage.
- mockito.patch(fn, attr_or_replacement, replacement=None)¶
Patch/Replace a function.
This is really like monkeypatching, but note that all interactions will be recorded and can be verified. That is, using patch you stay in the domain of mockito.
Two ways to call this. Either:
patch(os.path.exists, lambda str: True) # two arguments # OR patch(os.path, 'exists', lambda str: True) # three arguments
If called with three arguments, the mode is not strict to allow adding methods. If called with two arguments, mode is always strict.
Note
You must
unstub()after stubbing, or use with statement.
- mockito.patch_attr(obj_or_path, attr_or_replacement, replacement=OMITTED)¶
Patch/replace an attribute with a concrete value.
Unlike
patch(), this does not record interactions and does not expose verification. It is intended for simple attribute replacement likesys.stdoutorsys.argv.Two ways to call this. Either:
patch_attr('sys.stdout', StringIO()) # two arguments # OR patch_attr(sys, 'stdout', StringIO()) # three arguments
withcontext management is supported and restores the original value on__exit__.__enter__returns the replacement object.Note
You must
unstub()after patching, or use with statement.
- mockito.patch_dict(mapping_or_path, values=None, *, clear=False, remove=None, **kwargs)¶
Patch/update a dict-like object in place.
This is a convenience function for test-time dictionary patching, especially for mutable global maps like
os.environ.Usage:
patch_dict(os.environ, {'USER': 'foo'}) patch_dict(os.environ, [('USER', 'foo')]) patch_dict(os.environ, USER='foo') patch_dict(os.environ, remove={'USER', 'PATH'}) patch_dict(os.environ, remove=all) patch_dict(os.environ, clear=True) patch_dict('os.environ', {'USER': 'foo'})
withcontext management is supported and restores the original mapping state on__exit__.__enter__returns the patched mapping.valuescan be any value accepted bydict(values).kwargsare merged intovaluesand take precedence.Note
You must
unstub()after patching, or use with statement.
- mockito.unstub(*objs)¶
Unstubs all stubbed methods, functions, and patched attributes.
If you don’t pass in any argument, all registered mocks and patched modules, classes etc. will be unstubbed.
You can also unstub a single method/function target, e.g.:
unstub(os.path.exists) unstub("os.path.exists") unstub(cat.meow)
Or explicitly target one attribute by host and name, e.g.:
unstub((cat, "meow")) unstub(cat, "meow") unstub((cat, "meow"), (os.path, "exists"))
In these cases only the selected attributes are restored, while other stubs on the same objects stay active.
Note that additionally, the underlying registry will be cleaned. After an unstub you can’t
verify()anymore because all interactions will be forgotten.
- mockito.forget_invocations(*objs)¶
Forget all invocations of given objs.
If you already call mocks during your setup routine, you can now call
forget_invocationsat the end of your setup, and have a clean ‘recording’ for your actual test code. T.i. you don’t have to count the invocations from your setup code anymore when usingverify()afterwards.
- mockito.spy(object)¶
Spy an object.
Spying means that all functions will behave as before, so they will be side effects, but the interactions can be verified afterwards.
Returns Dummy-like, almost empty object as proxy to object.
The returned object must be injected and used by the code under test; after that all interactions can be verified as usual. T.i. the original object will not be patched, and has no further knowledge as before.
E.g.:
import time time = spy(time) # inject time do_work(..., time) verify(time).time()
- mockito.spy2(fn) None¶
Spy usage of given fn.
Patches the module, class or object fn lives in, so that all interactions can be recorded; otherwise executes fn as before, so that all side effects happen as before.
E.g.:
import time spy2(time.time) do_work(...) # nothing injected, uses global patched `time` module verify(time).time()
Note that builtins often cannot be patched because they’re read-only.
- mockito.when2(fn, *args, **kwargs)¶
Stub a function call with the given arguments
Exposes a more pythonic interface than
when(). Seewhen()for more documentation.Returns AnswerSelector interface which exposes thenReturn, thenRaise, thenAnswer, and thenCallOriginalImplementation as usual. Always strict.
Usage:
# Given `dog` is an instance of a `Dog` when2(dog.bark, 'Miau').thenReturn('Wuff')
Note
You must
unstub()after stubbing, or use with statement.
This looks like a plethora of verification functions, and especially since you often don’t need to verify at all.
- mockito.verify(obj, times=None, atleast=None, atmost=None, between=None, inorder=False, _factory=None)¶
Central interface to verify interactions.
verify uses a fluent interface:
verify(<obj>, times=2).<method_name>(<args>)
args can be as concrete as necessary. Often a catch-all is enough, especially if you’re working with strict mocks, bc they throw at call time on unwanted, unconfigured arguments:
from mockito import ANY, ARGS, KWARGS when(manager).add_tasks(1, 2, 3) ... # no need to duplicate the specification; every other argument pattern # would have raised anyway. verify(manager).add_tasks(1, 2, 3) # duplicates `when`call verify(manager).add_tasks(*ARGS) verify(manager).add_tasks(...) # Py3 verify(manager).add_tasks(Ellipsis) # Py2
- mockito.verifyZeroInteractions(*objs)¶
Verify that no methods have been called on given objs.
Rarely used because verify(…, times=0) is more explicit. Also: strict mocks usually throw early on unexpected, unstubbed invocations. For them, there may be no need to verify afterwards. expect(…, times=0) may also appropriate.
Partial mocks (‘monkeypatched’ objects or modules) only look at the stubbed invocations as the actual usage gets recorded only for them. However, you could use spy and inject it.
- mockito.verifyExpectedInteractions(*objs)¶
Verifies that expectations set via expect are met
E.g.:
expect(os.path, times=1).exists(...).thenReturn(True) os.path('/foo') verifyExpectedInteractions(os.path) # ok, called once
If you leave out the argument all registered objects will be checked.
Note
DANGERZONE: If you did not
unstub()correctly, it is possible that old registered mocks, from other tests leak.See related
expect()
In-order verification across one or multiple observed objects is provided by
InOrder.
- class mockito.InOrder(*objects: object)¶
Verify interactions in strict order across one or multiple objects.
This is the preferred API for order-sensitive verification. InOrder keeps one global queue of recorded invocations for all observed objects, then verifies against that queue from left to right.
Basic usage:
from mockito import mock, InOrder cat = mock() dog = mock() in_order = InOrder(cat, dog) cat.meow() dog.bark() in_order.verify(cat).meow() in_order.verify(dog).bark()
InOrder.verify uses the same fluent style and verification arguments as
verify(), includingtimes,atleast,atmostandbetween:in_order.verify(cat, times=2).meow(...) in_order.verify(dog, between=(1, 3)).bark()
Zero-lower-bound verifications (e.g.
times=0orbetween=(0, 2)) may pass without consuming the next queued invocation.InOrder can be used as a context manager:
with InOrder(cat, dog) as in_order: cat.meow() dog.bark() in_order.verify(cat).meow() in_order.verify(dog).bark()
Only the objects passed to InOrder are observed. Calls on other objects are ignored. Registration is dynamic: objects that are stubbed after InOrder(…) construction are still captured while the instance is active.
See related
verify(),expect(),ensureNoUnverifiedInteractions(), andverifyStubbedInvocationsAreUsed().
Note that verifyExpectedInteractions was named verifyNoUnwantedInteractions in v1. The usage of verifyNoUnwantedInteractions is deprecated.
- mockito.verifyStubbedInvocationsAreUsed(*objs)¶
Ensure stubs are actually used.
This functions just ensures that stubbed methods are actually used. Its purpose is to detect interface changes after refactorings. It is meant to be invoked usually without arguments just before
unstub().
- mockito.ensureNoUnverifiedInteractions(*objs)¶
Check if any given object has any unverified interaction.
You can use this after verify-ing to ensure no other interactions happened.
Can lead to over-specified tests.
Note that ensureNoUnverifiedInteractions was named verifyNoMoreInteractions in v1. The usage of verifyNoMoreInteractions is deprecated.