mockito-python Documentation - Read the Docs

31
mockito-python Documentation Release 1.3.3 Szczepan Faber, Serhiy Oplakanets, herr.kaste Jun 23, 2022

Transcript of mockito-python Documentation - Read the Docs

mockito-python DocumentationRelease 1.3.3

Szczepan Faber, Serhiy Oplakanets, herr.kaste

Jun 23, 2022

Contents

1 Use 3

2 Features 5

3 Read 7

Python Module Index 25

Index 27

i

ii

mockito-python Documentation, Release 1.3.3

Mockito is a spying framework originally based on the Java library with the same name.

pip install mockito

If you already use pytest, consider using the plugin pytest-mockito.

Contents 1

mockito-python Documentation, Release 1.3.3

2 Contents

CHAPTER 1

Use

from mockito import when, mock, unstub

when(os.path).exists('/foo').thenReturn(True)

# or:import requests # the famous library# you actually want to return a Response-like obj, we'll fake itresponse = mock({'status_code': 200, 'text': 'Ok'})when(requests).get(...).thenReturn(response)

# use itrequests.get('http://google.com/')

# clean upunstub()

3

mockito-python Documentation, Release 1.3.3

4 Chapter 1. Use

CHAPTER 2

Features

Super easy to set up different answers.

# Well, you know the internetwhen(requests).get(...).thenReturn(mock({'status': 501})) \

.thenRaise(Timeout("I'm flaky")) \

.thenReturn(mock({'status': 200, 'text': 'Ok'}))

State-of-the-art, high-five argument matchers:

# Use the Ellipsis, if you don't carewhen(deferred).defer(...).thenRaise(Timeout)

# Or **kwargsfrom mockito import kwargs # or KWARGSwhen(requests).get('http://my-api.com/user', **kwargs)

# The usual matchersfrom mockito import ANY, or_, not_number = or_(ANY(int), ANY(float))when(math).sqrt(not_(number)).thenRaise(

TypeError('argument must be a number'))

No need to verify (assert_called_with) all the time:

# Different arguments, different answerswhen(foo).bar(1).thenReturn(2)when(foo).bar(2).thenReturn(3)

# but:foo.bar(3) # throws immediately: unexpected invocation

# because of that you just know that when# you get a `2`, you called it with `1`

Signature checking:

5

mockito-python Documentation, Release 1.3.3

# when stubbingwhen(requests).get() # throws immediately: TypeError url required

# when callingrequest.get(location='http://example.com/') # TypeError

6 Chapter 2. Features

CHAPTER 3

Read

3.1 The Walk-through

The 90% use case is that want to stub out a side effect. This is also known as (monkey-)patching. With mockito, it’s:

from mockito import when

# stub `os.path.exists`when(os.path).exists('/foo').thenReturn(True)

os.path.exists('/foo') # => Trueos.path.exists('/bar') # -> throws unexpected invocation

So in difference to traditional patching, in mockito you always specify concrete arguments (a call signature), and itsoutcome, usually a return value via thenReturn or a raised exception via thenRaise. That effectively turns functioncalls into constants for the time of the test.

There are of course reasons when you don’t want to overspecify specific tests. You _just_ want the desired stub answer.Here we go:

when(os.path).exists(...).thenReturn(True)

# now, obviously, you get the same answer, regardless of the argumentsos.path.exists('FooBar') # => True

You can combine both stubs. E.g. nothing exists, except one file:

when(os.path).exists(...).thenReturn(False)when(os.path).exists('.flake8').thenReturn(True)

And because it’s a similar pattern, we can introduce spy2() here. Spies call through the original implementation ofa given function. E.g. everything is as it is, except ‘.flake8’ is just not there:

7

mockito-python Documentation, Release 1.3.3

from mockito import spy2spy2(os.path.exists)when(os.path).exists('.flake8').thenReturn(False)

When patching, you MUST not forget to unstub() of course! You can do this explicitly

from mockito import unstubunstub() # restore os.path module

Usually you do this unconditionally in your teardown function. If you’re using pytest, you could define a fixtureinstead

:: # conftest.py import pytest

@pytest.fixture def unstub():

from mockito import unstub yield unstub()

# my_test.py import pytest pytestmark = pytest.mark.usefixtures(“unstub”)

But very often you just use context managers (aka with), and mockito will unstub on ‘exit’ automatically:

# E.g. test that `exists` gets never calledwith expect(os.path, times=0).exists('.flake8'):

# within the block `os.path.exists` is patchedcached_dir_lookup('.flake8')

# at the end of the block `os.path` gets unpatched

# Which is btw roughly the same as doingwith when(os.path).exists('.flake8'):

cached_dir_lookup('.flake8')verify(os.path, times=0).exists(...)

Now let’s mix global module patching with mocks. We want to test the following function using the fab requestslibrary:

import requests

def get_text(url):res = requests.get(url)if 200 <= res.status_code < 300:

return res.textreturn None

How, dare, we did not inject our dependencies! Obviously we can get over that by patching at the module level likebefore:

when(requests).get('https://example.com/api').thenReturn(...)

But what should we return? We know it’s a requests.Response object, (Actually I know this bc I typed this in theipython REPL first.) But how to construct such a Response, its __init__ doesn’t even take any arguments?

Should we actually use a ‘real’ response object? No, we fake it using mock().

# setupresponse = mock({

'status_code': 200,'text': 'Ok'

}, spec=requests.Response)

(continues on next page)

8 Chapter 3. Read

mockito-python Documentation, Release 1.3.3

(continued from previous page)

when(requests).get('https://example.com/api').thenReturn(response)

# runassert get_text('https://example.com/api') == 'Ok'

# done!

Say you want to mock the class Dog:

class Dog(object):def bark(self):

return 'Wuff'

# either mock the classwhen(Dog).bark().thenReturn('Miau!')# now all instances have a different behaviorrex = Dog()assert rex.bark() == 'Miau!'

# or mock a concrete instancewhen(rex).bark().thenReturn('Grrrr')assert rex.bark() == 'Grrrr'# a different dog will still 'Miau!'assert Dog().bark() == 'Miau!'

# be sure to call unstub() once in whileunstub()

Sure, you can verify your interactions:

from mockito import verify# once againrex = Dog()when(rex).bark().thenReturn('Grrrr')

rex.bark()rex.bark()

# `times` defaults to 1verify(rex, times=2).bark()

In general mockito is very picky:

# this will fail because `Dog` has no method named `waggle`when(rex).waggle().thenReturn('Nope')# this will fail because `bark` does not take any argumentswhen(rex).bark('Grrr').thenReturn('Nope')

# given this functiondef bark(sound, post='!'):

return sound + post

from mockito import kwargswhen(main).bark('Grrr', **kwargs).thenReturn('Nope')

(continues on next page)

3.1. The Walk-through 9

mockito-python Documentation, Release 1.3.3

(continued from previous page)

# now this one will failbark('Grrr') # because there are no keyword arguments used# this one will fail because `then` does not match the function signaturebark('Grrr', then='!!')# this one will gobark('Grrr', post='?')

# there is also an args matcherdef add_tasks(*tasks, verbose=False):

pass

from mockito import args# If you omit the `thenReturn` it will just return `None`when(main).add_tasks(*args)

add_tasks('task1', 'task2') # will goadd_tasks() # will failadd_tasks('task1', verbose=True) # will fail too

# On Python 3 you can also use `...`when(main).add_tasks(...)# when(main).add_tasks(Ellipsis) on Python 2

add_tasks('task1') # will goadd_tasks(verbose=True) # will goadd_tasks('task1', verbose=True) # will goadd_tasks() # will go

To start with an empty stub use mock():

from mockito import mock

obj = mock()

# pass it around, eventually it will be usedobj.say('Hi')

# back in the tests, verify the interactionsverify(obj).say('Hi')

# by default all invoked methods take any arguments and return None# you can configure your expected method calls with the ususal `when`when(obj).say('Hi').thenReturn('Ho')

# There is also a shortcut to set some attributesobj = mock({

'hi': 'ho'})

assert obj.hi == 'ho'

# This would work for methods as well; in this caseobj = mock({

'say': lambda _: 'Ho'})

# But you don't have any argument and signature matching(continues on next page)

10 Chapter 3. Read

mockito-python Documentation, Release 1.3.3

(continued from previous page)

assert obj.say('Anything') == 'Ho'

# At least you can verify your callsverify(obj).say(...)

# Btw, you can make screaming strict mocks::obj = mock(strict=True) # every unconfigured, unexpected call will raise

You can use an empty stub specced against a concrete class:

# Given the above `Dog`rex = mock(Dog)

# Now you can stub out any known method on `Dog` but other will throwwhen(rex).bark().thenReturn('Miau')# this one will failwhen(rex).waggle()

# These mocks are in general very strict, so even this will failrex.health # unconfigured attribute

# Of course you can just set it in a setup routinerex.health = 121

# Or again preconfigurerex = mock({'health': 121}, spec=Dog)

# preconfigure stubbed methodrex = mock({'bark': lambda sound: 'Miau'}, spec=Dog)

# as you specced the mock, you get at least function signature matching# `bark` does not take any arguments sorex.bark('sound') # will throw TypeError

# Btw, you can make loose specced mocks::rex = mock(Dog, strict=False)

3.2 Recipes

3.2.1 Classes as factories

We want to test the following code:

import requests

def fetch(url):session = requests.Session()return session.get(url)

In a traditional sense this code is not designed for testability. But we don’t care here.

Python has no new keyword to get fresh instances from classes. Man, that was a good decision, Guido! So theuppercase S in requests.Session() doesn’t have to stop us in any way. It looks like a function call, and we treat it likesuch: The plan is to replace Session with a factory function that returns a (mocked) session:

3.2. Recipes 11

mockito-python Documentation, Release 1.3.3

from mockito import when, mock, verifyStubbedInvocationsAreUsed

def test_fetch(unstub):url = 'http://example.com/'response = mock({'text': 'Ok'}, spec=requests.Response)# remember: `mock` here just creates an empty object specced after# requests.Sessionsession = mock(requests.Session)# `when` here configures the mockwhen(session).get(url).thenReturn(response)# `when` *patches* the globally available *requests* modulewhen(requests).Session().thenReturn(session) # <=

res = fetch(url)assert res.text == 'Ok'

# no need to verify anything here, if we get the expected response# back, `url` must have been passed through the system, otherwise# mockito would have thrown.# We *could* ensure that our mocks are actually used, if we want:verifyStubbedInvocationsAreUsed()

3.2.2 Faking magic methods

We want to test the following code:

import requests

def fetch_2(url):with requests.Session() as session:

return session.get(url)

It’s basically the same problem, but we need to add support for the context manager, the with interface:

from mockito import when, mock, args

def test_fetch_with(unstub):url = 'http://example.com/'response = mock({'text': 'Ok'}, spec=requests.Response)

session = mock(requests.Session)when(session).get(url).thenReturn(response)when(session).__enter__().thenReturn(session) # <=when(session).__exit__(*args) # <=

when(requests).Session().thenReturn(session)

res = fetch_2(url)assert res.text == 'Ok'

3.3 The functions

Stable entrypoints are: when(), mock(), unstub(), verify(), spy(). Experimental or newfunction introduces with v1.0.x are: when2(), expect(), verifyNoUnwantedInteractions(),

12 Chapter 3. Read

mockito-python Documentation, Release 1.3.3

verifyStubbedInvocationsAreUsed(), patch()

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 conrete args for which the stub willanswer 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 turnfunction 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 TypeErrordog.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 verifiesthe return value by evaluating it. See verify() if you need to, see also expect() to setup expected callcounts up front.

If your function is pure side effect and does not return something, you can omit the specific answer. The defaultthen is None:

when(manager).do_work()

when verifies the method name, the expected argument signature, and the actual, factual arguments your codeunder 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, KWARGSwhen(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=False to bypass the function signature checks.

See related when2() which has a more pythonic interface.

3.3. The functions 13

mockito-python Documentation, Release 1.3.3

mockito.when2(fn, *args, **kwargs)Stub a function call with the given arguments

Exposes a more pythonic interface than when(). See when() for more documentation.

Returns AnswerSelector interface which exposes thenReturn, thenRaise, and thenAnswer as usual. Alwaysstrict.

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.

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# ORpatch(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.expect(obj, strict=None, 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 allverifyNoUnwantedInteractions()

Note: You must unstub() after stubbing, or use with statement.

See when(), when2(), verifyNoUnwantedInteractions()

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 berecorded 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.

14 Chapter 3. Read

mockito-python Documentation, Release 1.3.3

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() or expect(). You can also very conveniently just pass in adict 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.unstub(*objs)Unstubs all stubbed methods and functions

If you don’t pass in any argument, all registered mocks and patched modules, classes etc. will be unstubbed.

Note that additionally, the underlying registry will be cleaned. After an unstub you can’t verify() anymorebecause 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_invocations at the end ofyour setup, and have a clean ‘recording’ for your actual test code. T.i. you don’t have to count the invocationsfrom your setup code anymore when using verify() 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 beverified 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 verifiedas usual. T.i. the original object will not be patched, and has no further knowledge as before.

E.g.:

import timetime = spy(time)# inject time

(continues on next page)

3.3. The functions 15

mockito-python Documentation, Release 1.3.3

(continued from previous page)

do_work(..., time)verify(time).time()

mockito.spy2(fn)Spy usage of given fn.

Patches the module, class or object fn lives in, so that all interactions can be recorded; otherwise executes fn asbefore, so that all side effects happen as before.

E.g.:

import timespy2(time.time)do_work(...) # nothing injected, uses global patched `time` moduleverify(time).time()

Note that builtins often cannot be patched because they’re read-only.

This looks like a plethora of verification functions, and especially since you often don’t need to verify at all.

mockito.verify(obj, times=1, atleast=None, atmost=None, between=None, inorder=False)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, KWARGSwhen(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`callverify(manager).add_tasks(*ARGS)verify(manager).add_tasks(...) # Py3verify(manager).add_tasks(Ellipsis) # Py2

mockito.verifyNoMoreInteractions(*objs)

mockito.verifyZeroInteractions(*objs)Verify that no methods have been called on given objs.

Note that strict mocks usually throw early on unexpected, unstubbed invocations. Partial mocks (‘monkey-patched’ objects or modules) do not support this functionality at all, bc only for the stubbed invocations theactual usage gets recorded. So this function is of limited use, nowadays.

mockito.verifyNoUnwantedInteractions(*objs)Verifies that expectations set via expect are met

E.g.:

expect(os.path, times=1).exists(...).thenReturn(True)os.path('/foo')verifyNoUnwantedInteractions(os.path) # ok, called once

If you leave out the argument all registered objects will be checked.

16 Chapter 3. Read

mockito-python Documentation, Release 1.3.3

Note: DANGERZONE: If you did not unstub() correctly, it is possible that old registered mocks, fromother tests leak.

See related expect()

mockito.verifyStubbedInvocationsAreUsed(*objs)Ensure stubs are actually used.

This functions just ensures that stubbed methods are actually used. Its purpose is to detect interface changesafter refactorings. It is meant to be invoked usually without arguments just before unstub().

3.4 The matchers

Argument matchers for stubbing and verifications.

In general the call signature you specify when stubbing or verifying in mockito is as concrete as possible: it consistsof values only:

when(os.path).exists('/foo/bar.txt').thenReturn(True)

This is for a reason. In controlled test environments, for the scope of a single test, you should usually know exactlyhow you use a function, and what you expect its outcome to be. In mockito usually (in strict mode) all invocationsyou did not specify upfront will throw at call time.

If you reason about your code, the above when tirade turns - for the time of the test - the specific stubbed function intoa constant.

You can use so called argument matchers below if you can’t or don’t want to specify a single concrete value for anargument, but a type or class of possible values. E.g.:

when(os.path).exists(...).thenReturn(True)when(os.path).exists(ANY).thenReturn(True)when(os.path).exists(ANY(str)).thenReturn(True)

when(requests).get(ANY(str), **kwargs)when(requests).get('https://example.com', ...)

when(math).sqrt(not_(_or(ANY(float), ANY(int)))).thenRaise(TypeError)

Now what you get each time is a function that up to a degree takes various arguments and responds with the sameoutcome each time. Now that’s a weird thing. So use the matchers for a reason, they’re powerful.

The one usage you should not care about is a loose signature when using verify(). Since mockito will throw forunexpected calls, a very loose verify should be ok:

verify(requests, times=1).get(...)

mockito.matchers.and_(*matchers)Matches if all given matchers match

Example:

when(mock).foo(and_(ANY(str), contains('foo')))

mockito.matchers.or_(*matchers)Matches if any given matcher match

3.4. The matchers 17

mockito-python Documentation, Release 1.3.3

Example:

when(mock).foo(or_(ANY(int), ANY(float)))

mockito.matchers.not_(matcher)Matches if given matcher does not match

Example:

when(mock).foo(not_(ANY(str))).thenRaise(TypeError)

mockito.matchers.eq(value)Matches particular value (==)

mockito.matchers.neq(value)Matches any but given value (!=)

mockito.matchers.lt(value)Matches any value that is less than given value (<)

mockito.matchers.lte(value)Matches any value that is less than or equal to given value (<=)

mockito.matchers.gt(value)Matches any value that is greater than given value (>)

mockito.matchers.gte(value)Matches any value that is greater than or equal to given value (>=)

mockito.matchers.any(wanted_type=None)Matches against type of argument (isinstance).

If you want to match any type, use either ANY or ANY().

Examples:

when(mock).foo(any).thenReturn(1)verify(mock).foo(any(int))

mockito.matchers.any_(wanted_type=None)Matches against type of argument (isinstance).

If you want to match any type, use either ANY or ANY().

Examples:

when(mock).foo(any).thenReturn(1)verify(mock).foo(any(int))

mockito.matchers.ANY(wanted_type=None)Matches against type of argument (isinstance).

If you want to match any type, use either ANY or ANY().

Examples:

when(mock).foo(any).thenReturn(1)verify(mock).foo(any(int))

mockito.matchers.arg_that(predicate)Matches any argument for which predicate returns True

Example:

18 Chapter 3. Read

mockito-python Documentation, Release 1.3.3

verify(mock).foo(arg_that(lambda arg: arg > 3 and arg < 7))

mockito.matchers.contains(sub)Matches any string containing given substring

Example:

mock.foo([120, 121, 122, 123])verify(mock).foo(contains(123))

mockito.matchers.matches(regex, flags=0)Matches any string that matches given regex

mockito.matchers.captor(matcher=None)Returns argument captor that captures values for further assertions

Example:

arg = captor()mock.do_something(123)mock.do_something(456)verify(mock).do_something(arg)assert arg.value == 456assert arg.all_values == [123, 456]

You can restrict what the captor captures using the other matchers shown herein:

arg = captor(any(str))arg = captor(contains("foo"))

3.5 MOCKITO CHANGE LOG

3.5.1 Release 1.3.3 (June 23, 2022)

• Hotfix: Correctly unstub methods extracted to the module level, for example random.randint() et.al. fromthe standard library. See #53

3.5.2 Release 1.3.2 (June 23, 2022)

• Let mock(spec=SomeClass) work just as mock(SomeClass)

3.5.3 Release 1.3.1 (June 14, 2022)

• Reimplement captor to capture only during execution phase of a test.

3.5.4 Release 1.3.0 (December 3, 2021)

• Teach captor to remember all used values (@shashankrnr32). E.g.

3.5. MOCKITO CHANGE LOG 19

mockito-python Documentation, Release 1.3.3

arg = captor()mock.do_something(123)mock.do_something(456)verify(mock).do_something(arg)assert arg.all_values == [123, 456]

3.5.5 Release 1.2.2 (September 9, 2020)

• Fix typo in spy2 doc

3.5.6 Release 1.2.1 (February 19, 2020)

• @nielsvaneck fixed how we can lookup inherited classmethods.

3.5.7 Release 1.2.0 (November 25, 2019)

• Code base now is python 3 compatible. No 2to3 anymore.

• Fine tune error messages on unexpected calls or verifications. E.g. if you expect when(dog).bark('Wuff') but on call time do dog.bark('Wufff'). Likewise, if you call dog.bark('Miau')and then verify(dog).bark('Maui').

• @felixonmars fixed a small compatibility issue with python 3.8

• Mocking properties has become a bit easier. (#26) E.g.

prop = mock()when(prop).__get__(...).thenReturn(23)m = mock({'name': prop})

3.5.8 Release 1.1.1 (August 28, 2018)

• Fix: The context manager (with) has now a proper implementation

• Fix: Calling patch with two arguments can now be used with with

• Fix: Do not treat the placeholder arguments (Ellipsis, args, kwargs) as special on call time anymore. (T.i. theyonly have a meaning when stubbing or verifying.)

• Enhancement: Changed some truthy or equality tests to identity (is) tests. This reduces edge-cases where someuser object defines __eq__ or __bool__. (Hello _numpy_!)

3.5.9 Release 1.1.0 (May 2, 2018)

• Added forget_invocations function. Thanks to @maximkulkin

This is generally useful if you already call mocks during your setup routine. Now you could callforget_invocations at the end of your setup, and have a clean ‘recording’ for your actual test code. T.i. youdon’t have to count the invocations from your setup code anymore.

20 Chapter 3. Read

mockito-python Documentation, Release 1.3.3

3.5.10 Release 1.0.12 (June 3, 2017)

• Better error messages for failed verifications. By @lwoydziak

3.5.11 Release 1.0.7 - 1.0.10 (January 31 - February 2, 2017)

• verifyZeroInteractions implemented. This is actually a breaking change, becauseverifyZeroInteractions was an alias for verifyNoMoreInteractions (sic!). If you usedit, just call the other function.

• verifyStubbedInvocationsAreUsed implemented. This is meant to be called right before an unstuband should improve long time maintenance. It doesn’t help during design time. Note that pytest-mockito auto-matically calls this for you.

• All verify* functions now warn you if you pass in an object which was never stubbed.

3.5.12 Release 1.0.0 - 1.0.5 (January 24 - 27, 2017)

This is a major update; mostly because of internal code reorganization (imports) it cannot be guaranteed that this willnot break for you. Though if you just used the public API you should be fine. None of the vintage old tests have beenremoved and they at least pass.

In general unclassified imports (from mocktio import *) are not recommended. But if you did, we do notexport Mock anymore. Mock has been deprecated long ago and is now for internal use only. You must use mock.

Another important change is, that mockito’s strict mode is far more strict than before. We now generally try to matchthe signature of the target method with your usage. Usually this should help you find bugs in your code, because itwill make it easier to spot changing interfaces.

• mock, when, verify return mostly empty objects. It is unlikely to have a method_name clash.

• Specced mocks instance = mock(Class) will pass isinstance tests like isinstance(instance,Class)

• For when and verify the function signature or argument matchers can be greatly simplified. E.g.when(requests).get(...).thenReturn('OK') will match any argument you pass in. There areargs and kwargs matchers as well. So when(requests).get('https://...', **kwargs).thenReturn(...) will make an exact match on the first argument, the url, and ignore all the headers andother stuff.

• Mocks can be preconfigured: mock({'text': 'OK'}). For specced mocks this would be e.g.mock({'text': 'OK'}, spec=requests.Response).

• If you mock or patch an object, the function signatures will be matched. So:

def foo(a, b=1): ...

when(main).foo(12) # will passwhen(main).foo(c=13) # will raise immediately

• Mock Dummies are now callable:

m = mock()m(1, 2)verify(m).__call__(...)

• Mock() is now an implementation detail; it is not exported anymore. Use mock().

3.5. MOCKITO CHANGE LOG 21

mockito-python Documentation, Release 1.3.3

• You can unstub individual patched objects unstub(obj). (Before it was all or nothing.)

• Added basic context manager support when using when. Note that verify has to be called within the withcontext.

with when(rex).waggle().thenReturn('Yup'):assert rex.waggle() == 'Yup'verify(rex).waggle()

• Aliased any_ to ANY, args to ARGS and kwargs to KWARGS. You can use python’s builtin any as a standin for ANY.

• As a convenience you can use our any_ matcher like a type instead of any_():

dummy(1)verify(dummy).__call__(ANY)

• Added when2, expect, spy2

• Make the mocked function (replacement) more inspectable. Copy __doc__, __name__ etc.

• You can configure magic methods on mocks:

dummy = mock()when(dummy).__getitem__(1).thenReturn(2)assert dummy[1] == 2

3.5.13 Release 0.7.1 (December 27, 2016)

• Fix: Allow verifyNoMoreInteractions call for real (stubbed) objects

3.5.14 Release 0.7.0 (July 15, 2016)

• Added a ton of new argument matchers. Namely:

'and_', 'or_', 'not_', 'eq', 'neq', 'lt', 'lte', 'gt', 'gte','arg_that', 'matches', 'captor'

• Aliases any matcher to any_ because it’s a builtin.

• Fixes an issue where mockito could not correctly verify your function invocations, if you grabbed a methodfrom its object and used it (‘detached’) as a plain function:

m = mock()f = m.foo # detachf(1, 2) # pass it around and use it like a functionf(2, 3)verify(m).foo(...) # finally verify interactions

Thank you @maximkulkin

3.5.15 Release 0.6.1 (May 20, 2016)

• Added thenAnswer(callable). The callable will be called to compute the answer the stubbed methodwill return. For that it will receive the arguments of the caller:

22 Chapter 3. Read

mockito-python Documentation, Release 1.3.3

m = mock()when(m).do_times(any(), any()).thenAnswer(lambda one, two: one * two)self.assertEquals(20, m.do_times(5, 4))

Thank you @stubbsd

3.5.16 Release 0.6.0 (April 25, 2016)

• Print keyword arguments nicely.

• Be very forgiving about return values and assume None as default. T.i. when(Dog).bark('Miau').thenReturn() is enough to return None.

• Make keyword argument order unimportant.

• BREAKING CHANGE: Throw early when calling not expected methods in strict mode.

3.5.17 Release 0.5.3 (April 23, 2016)

• Remove hard coded distribute setup files.

3.5.18 Release 0.5.1 (August 4, 2010)

BUG Fixes:

• Fixed issue #9 [http://bitbucket.org/szczepiq/mockito-python/issue/9] : Generating stubs from classescaused method to be replaced in original classes.

3.5.19 Release 0.5.0 (July 26, 2010)

API Changes:

• Added possibility to spy on real objects.

• Added “never” syntactic sugar for verifications.

BUG Fixes:

• Fixed issue with named arguments matching.

Other Changes:

• Python 2.7 support

• Deprecated APIs now generate deprecation warnings.

3.5.20 Release 0.4.0 (July 2, 2010)

API Changes:

• Added possibility to verify invocations in order.

BUG Fixes:

• Fixed issue with installing mockito from egg without distribute installed.

3.5. MOCKITO CHANGE LOG 23

mockito-python Documentation, Release 1.3.3

3.5.21 Release 0.3.1

Bug-fix release.

Bug Fixes:

• Fixed annoying issue #8 [http://bitbucket.org/szczepiq/mockito-python/issue/8]

3.5.22 Release 0.3.0

API Changes:

• Renamed mock creation method from “Mock” (upper “M”) to “mock”. Old name stays for compatibilityuntil 1.0 release.

Other Changes:

• Official Python3 support via distutils + 2to3.

Report issues, contribute more documentation or give feedback at Github!

24 Chapter 3. Read

Python Module Index

mmockito, 12mockito.matchers, 17

25

mockito-python Documentation, Release 1.3.3

26 Python Module Index

Index

Aand_() (in module mockito.matchers), 17ANY() (in module mockito.matchers), 18any() (in module mockito.matchers), 18any_() (in module mockito.matchers), 18arg_that() (in module mockito.matchers), 18

Ccaptor() (in module mockito.matchers), 19contains() (in module mockito.matchers), 19

Eeq() (in module mockito.matchers), 18expect() (in module mockito), 14

Fforget_invocations() (in module mockito), 15

Ggt() (in module mockito.matchers), 18gte() (in module mockito.matchers), 18

Llt() (in module mockito.matchers), 18lte() (in module mockito.matchers), 18

Mmatches() (in module mockito.matchers), 19mock() (in module mockito), 14mockito (module), 1, 11, 12mockito.matchers (module), 17

Nneq() (in module mockito.matchers), 18not_() (in module mockito.matchers), 18

Oor_() (in module mockito.matchers), 17

Ppatch() (in module mockito), 14

Sspy() (in module mockito), 15spy2() (in module mockito), 16

Uunstub() (in module mockito), 15

Vverify() (in module mockito), 16verifyNoMoreInteractions() (in module mock-

ito), 16verifyNoUnwantedInteractions() (in module

mockito), 16verifyStubbedInvocationsAreUsed() (in

module mockito), 17verifyZeroInteractions() (in module mockito),

16

Wwhen() (in module mockito), 13when2() (in module mockito), 13

27