unittest.mock
— mock object library¶
Added in version 3.3.
Source code:Lib/unittest/mock.py
unittest.mock
is a library for testing in Python. It allows you toreplace parts of your system under test with mock objects and make assertionsabout how they have been used.
unittest.mock
provides a coreMock
class removing the need tocreate a host of stubs throughout your test suite. After performing anaction, you can make assertions about which methods / attributes were usedand arguments they were called with. You can also specify return values andset needed attributes in the normal way.
Additionally, mock provides apatch()
decorator that handles patchingmodule and class level attributes within the scope of a test, along withsentinel
for creating unique objects. See thequick guide forsome examples of how to useMock
,MagicMock
andpatch()
.
Mock is designed for use withunittest
andis based on the ‘action -> assertion’ pattern instead of ‘record -> replay’used by many mocking frameworks.
There is a backport ofunittest.mock
for earlier versions of Python,available asmock on PyPI.
Quick Guide¶
Mock
andMagicMock
objects create all attributes andmethods as you access them and store details of how they have been used. Youcan configure them, to specify return values or limit what attributes areavailable, and then make assertions about how they have been used:
>>>fromunittest.mockimportMagicMock>>>thing=ProductionClass()>>>thing.method=MagicMock(return_value=3)>>>thing.method(3,4,5,key='value')3>>>thing.method.assert_called_with(3,4,5,key='value')
side_effect
allows you to perform side effects, including raising anexception when a mock is called:
>>>fromunittest.mockimportMock>>>mock=Mock(side_effect=KeyError('foo'))>>>mock()Traceback (most recent call last):...KeyError:'foo'
>>>values={'a':1,'b':2,'c':3}>>>defside_effect(arg):...returnvalues[arg]...>>>mock.side_effect=side_effect>>>mock('a'),mock('b'),mock('c')(1, 2, 3)>>>mock.side_effect=[5,4,3,2,1]>>>mock(),mock(),mock()(5, 4, 3)
Mock has many other ways you can configure it and control its behaviour. Forexample thespec argument configures the mock to take its specificationfrom another object. Attempting to access attributes or methods on the mockthat don’t exist on the spec will fail with anAttributeError
.
Thepatch()
decorator / context manager makes it easy to mock classes orobjects in a module under test. The object you specify will be replaced with amock (or other object) during the test and restored when the test ends:
>>>fromunittest.mockimportpatch>>>@patch('module.ClassName2')...@patch('module.ClassName1')...deftest(MockClass1,MockClass2):...module.ClassName1()...module.ClassName2()...assertMockClass1ismodule.ClassName1...assertMockClass2ismodule.ClassName2...assertMockClass1.called...assertMockClass2.called...>>>test()
Note
When you nest patch decorators the mocks are passed in to the decoratedfunction in the same order they applied (the normalPython order thatdecorators are applied). This means from the bottom up, so in the exampleabove the mock formodule.ClassName1
is passed in first.
Withpatch()
it matters that you patch objects in the namespace where theyare looked up. This is normally straightforward, but for a quick guidereadwhere to patch.
As well as a decoratorpatch()
can be used as a context manager in a withstatement:
>>>withpatch.object(ProductionClass,'method',return_value=None)asmock_method:...thing=ProductionClass()...thing.method(1,2,3)...>>>mock_method.assert_called_once_with(1,2,3)
There is alsopatch.dict()
for setting values in a dictionary justduring a scope and restoring the dictionary to its original state when the testends:
>>>foo={'key':'value'}>>>original=foo.copy()>>>withpatch.dict(foo,{'newkey':'newvalue'},clear=True):...assertfoo=={'newkey':'newvalue'}...>>>assertfoo==original
Mock supports the mocking of Pythonmagic methods. Theeasiest way of using magic methods is with theMagicMock
class. Itallows you to do things like:
>>>mock=MagicMock()>>>mock.__str__.return_value='foobarbaz'>>>str(mock)'foobarbaz'>>>mock.__str__.assert_called_with()
Mock allows you to assign functions (or other Mock instances) to magic methodsand they will be called appropriately. TheMagicMock
class is just a Mockvariant that has all of the magic methods pre-created for you (well, all theuseful ones anyway).
The following is an example of using magic methods with the ordinary Mockclass:
>>>mock=Mock()>>>mock.__str__=Mock(return_value='wheeeeee')>>>str(mock)'wheeeeee'
For ensuring that the mock objects in your tests have the same api as theobjects they are replacing, you can useauto-speccing.Auto-speccing can be done through theautospec argument to patch, or thecreate_autospec()
function. Auto-speccing creates mock objects thathave the same attributes and methods as the objects they are replacing, andany functions and methods (including constructors) have the same callsignature as the real object.
This ensures that your mocks will fail in the same way as your productioncode if they are used incorrectly:
>>>fromunittest.mockimportcreate_autospec>>>deffunction(a,b,c):...pass...>>>mock_function=create_autospec(function,return_value='fishy')>>>mock_function(1,2,3)'fishy'>>>mock_function.assert_called_once_with(1,2,3)>>>mock_function('wrong arguments')Traceback (most recent call last):...TypeError:missing a required argument: 'b'
create_autospec()
can also be used on classes, where it copies the signature ofthe__init__
method, and on callable objects where it copies the signature ofthe__call__
method.
The Mock Class¶
Mock
is a flexible mock object intended to replace the use of stubs andtest doubles throughout your code. Mocks are callable and create attributes asnew mocks when you access them[1]. Accessing the same attribute will alwaysreturn the same mock. Mocks record how you use them, allowing you to makeassertions about what your code has done to them.
MagicMock
is a subclass ofMock
with all the magic methodspre-created and ready to use. There are also non-callable variants, usefulwhen you are mocking out objects that aren’t callable:NonCallableMock
andNonCallableMagicMock
Thepatch()
decorators makes it easy to temporarily replace classesin a particular module with aMock
object. By defaultpatch()
will createaMagicMock
for you. You can specify an alternative class ofMock
usingthenew_callable argument topatch()
.
- classunittest.mock.Mock(spec=None,side_effect=None,return_value=DEFAULT,wraps=None,name=None,spec_set=None,unsafe=False,**kwargs)¶
Create a new
Mock
object.Mock
takes several optional argumentsthat specify the behaviour of the Mock object:spec: This can be either a list of strings or an existing object (aclass or instance) that acts as the specification for the mock object. Ifyou pass in an object then a list of strings is formed by calling dir onthe object (excluding unsupported magic attributes and methods).Accessing any attribute not in this list will raise an
AttributeError
.Ifspec is an object (rather than a list of strings) then
__class__
returns the class of the spec object. Thisallows mocks to passisinstance()
tests.spec_set: A stricter variant ofspec. If used, attempting tosetor get an attribute on the mock that isn’t on the object passed asspec_set will raise an
AttributeError
.side_effect: A function to be called whenever the Mock is called. Seethe
side_effect
attribute. Useful for raising exceptions ordynamically changing return values. The function is called with the samearguments as the mock, and unless it returnsDEFAULT
, the returnvalue of this function is used as the return value.Alternativelyside_effect can be an exception class or instance. Inthis case the exception will be raised when the mock is called.
Ifside_effect is an iterable then each call to the mock will returnthe next value from the iterable.
Aside_effect can be cleared by setting it to
None
.return_value: The value returned when the mock is called. By defaultthis is a new Mock (created on first access). See the
return_value
attribute.unsafe: By default, accessing any attribute whose name starts withassert,assret,asert,aseert orassrt will raise an
AttributeError
. Passingunsafe=True
will allow access tothese attributes.Added in version 3.5.
wraps: Item for the mock object to wrap. Ifwraps is not
None
thencalling the Mock will pass the call through to the wrapped object(returning the real result). Attribute access on the mock will return aMock object that wraps the corresponding attribute of the wrappedobject (so attempting to access an attribute that doesn’t exist willraise anAttributeError
).If the mock has an explicitreturn_value set then calls are not passedto the wrapped object and thereturn_value is returned instead.
name: If the mock has a name then it will be used in the repr of themock. This can be useful for debugging. The name is propagated to childmocks.
Mocks can also be called with arbitrary keyword arguments. These will beused to set attributes on the mock after it is created. See the
configure_mock()
method for details.- assert_called()¶
Assert that the mock was called at least once.
>>>mock=Mock()>>>mock.method()<Mock name='mock.method()' id='...'>>>>mock.method.assert_called()
Added in version 3.6.
- assert_called_once()¶
Assert that the mock was called exactly once.
>>>mock=Mock()>>>mock.method()<Mock name='mock.method()' id='...'>>>>mock.method.assert_called_once()>>>mock.method()<Mock name='mock.method()' id='...'>>>>mock.method.assert_called_once()Traceback (most recent call last):...AssertionError:Expected 'method' to have been called once. Called 2 times.Calls: [call(), call()].
Added in version 3.6.
- assert_called_with(*args,**kwargs)¶
This method is a convenient way of asserting that the last call has beenmade in a particular way:
>>>mock=Mock()>>>mock.method(1,2,3,test='wow')<Mock name='mock.method()' id='...'>>>>mock.method.assert_called_with(1,2,3,test='wow')
- assert_called_once_with(*args,**kwargs)¶
Assert that the mock was called exactly once and that call was with thespecified arguments.
>>>mock=Mock(return_value=None)>>>mock('foo',bar='baz')>>>mock.assert_called_once_with('foo',bar='baz')>>>mock('other',bar='values')>>>mock.assert_called_once_with('other',bar='values')Traceback (most recent call last):...AssertionError:Expected 'mock' to be called once. Called 2 times.Calls: [call('foo', bar='baz'), call('other', bar='values')].
- assert_any_call(*args,**kwargs)¶
assert the mock has been called with the specified arguments.
The assert passes if the mock hasever been called, unlike
assert_called_with()
andassert_called_once_with()
thatonly pass if the call is the most recent one, and in the case ofassert_called_once_with()
it must also be the only call.>>>mock=Mock(return_value=None)>>>mock(1,2,arg='thing')>>>mock('some','thing','else')>>>mock.assert_any_call(1,2,arg='thing')
- assert_has_calls(calls,any_order=False)¶
assert the mock has been called with the specified calls.The
mock_calls
list is checked for the calls.Ifany_order is false then the calls must besequential. There can be extra calls before or after thespecified calls.
Ifany_order is true then the calls can be in any order, butthey must all appear in
mock_calls
.>>>mock=Mock(return_value=None)>>>mock(1)>>>mock(2)>>>mock(3)>>>mock(4)>>>calls=[call(2),call(3)]>>>mock.assert_has_calls(calls)>>>calls=[call(4),call(2),call(3)]>>>mock.assert_has_calls(calls,any_order=True)
- assert_not_called()¶
Assert the mock was never called.
>>>m=Mock()>>>m.hello.assert_not_called()>>>obj=m.hello()>>>m.hello.assert_not_called()Traceback (most recent call last):...AssertionError:Expected 'hello' to not have been called. Called 1 times.Calls: [call()].
Added in version 3.5.
- reset_mock(*,return_value=False,side_effect=False)¶
The reset_mock method resets all the call attributes on a mock object:
>>>mock=Mock(return_value=None)>>>mock('hello')>>>mock.calledTrue>>>mock.reset_mock()>>>mock.calledFalse
This can be useful where you want to make a series of assertions thatreuse the same object.
return_value parameter when set to
True
resetsreturn_value
:>>>mock=Mock(return_value=5)>>>mock('hello')5>>>mock.reset_mock(return_value=True)>>>mock('hello')<Mock name='mock()' id='...'>
side_effect parameter when set to
True
resetsside_effect
:>>>mock=Mock(side_effect=ValueError)>>>mock('hello')Traceback (most recent call last):...ValueError>>>mock.reset_mock(side_effect=True)>>>mock('hello')<Mock name='mock()' id='...'>
Note that
reset_mock()
doesn’t clear thereturn_value
,side_effect
or any child attributes you haveset using normal assignment by default.Child mocks are reset as well.
Changed in version 3.6:Added two keyword-only arguments to the reset_mock function.
- mock_add_spec(spec,spec_set=False)¶
Add a spec to a mock.spec can either be an object or alist of strings. Only attributes on thespec can be fetched asattributes from the mock.
Ifspec_set is true then only attributes on the spec can be set.
- attach_mock(mock,attribute)¶
Attach a mock as an attribute of this one, replacing its name andparent. Calls to the attached mock will be recorded in the
method_calls
andmock_calls
attributes of this one.
- configure_mock(**kwargs)¶
Set attributes on the mock through keyword arguments.
Attributes plus return values and side effects can be set on childmocks using standard dot notation and unpacking a dictionary in themethod call:
>>>mock=Mock()>>>attrs={'method.return_value':3,'other.side_effect':KeyError}>>>mock.configure_mock(**attrs)>>>mock.method()3>>>mock.other()Traceback (most recent call last):...KeyError
The same thing can be achieved in the constructor call to mocks:
>>>attrs={'method.return_value':3,'other.side_effect':KeyError}>>>mock=Mock(some_attribute='eggs',**attrs)>>>mock.some_attribute'eggs'>>>mock.method()3>>>mock.other()Traceback (most recent call last):...KeyError
configure_mock()
exists to make it easier to do configurationafter the mock has been created.
- __dir__()¶
Mock
objects limit the results ofdir(some_mock)
to useful results.For mocks with aspec this includes all the permitted attributesfor the mock.See
FILTER_DIR
for what this filtering does, and how toswitch it off.
- _get_child_mock(**kw)¶
Create the child mocks for attributes and return value.By default child mocks will be the same type as the parent.Subclasses of Mock may want to override this to customize the waychild mocks are made.
For non-callable mocks the callable variant will be used (rather thanany custom subclass).
- called¶
A boolean representing whether or not the mock object has been called:
>>>mock=Mock(return_value=None)>>>mock.calledFalse>>>mock()>>>mock.calledTrue
- call_count¶
An integer telling you how many times the mock object has been called:
>>>mock=Mock(return_value=None)>>>mock.call_count0>>>mock()>>>mock()>>>mock.call_count2
- return_value¶
Set this to configure the value returned by calling the mock:
>>>mock=Mock()>>>mock.return_value='fish'>>>mock()'fish'
The default return value is a mock object and you can configure it inthe normal way:
>>>mock=Mock()>>>mock.return_value.attribute=sentinel.Attribute>>>mock.return_value()<Mock name='mock()()' id='...'>>>>mock.return_value.assert_called_with()
return_value
can also be set in the constructor:>>>mock=Mock(return_value=3)>>>mock.return_value3>>>mock()3
- side_effect¶
This can either be a function to be called when the mock is called,an iterable or an exception (class or instance) to be raised.
If you pass in a function it will be called with same arguments as themock and unless the function returns the
DEFAULT
singleton thecall to the mock will then return whatever the function returns. If thefunction returnsDEFAULT
then the mock will return its normalvalue (from thereturn_value
).If you pass in an iterable, it is used to retrieve an iterator whichmust yield a value on every call. This value can either be an exceptioninstance to be raised, or a value to be returned from the call to themock (
DEFAULT
handling is identical to the function case).An example of a mock that raises an exception (to test exceptionhandling of an API):
>>>mock=Mock()>>>mock.side_effect=Exception('Boom!')>>>mock()Traceback (most recent call last):...Exception:Boom!
Using
side_effect
to return a sequence of values:>>>mock=Mock()>>>mock.side_effect=[3,2,1]>>>mock(),mock(),mock()(3, 2, 1)
Using a callable:
>>>mock=Mock(return_value=3)>>>defside_effect(*args,**kwargs):...returnDEFAULT...>>>mock.side_effect=side_effect>>>mock()3
side_effect
can be set in the constructor. Here’s an example thatadds one to the value the mock is called with and returns it:>>>side_effect=lambdavalue:value+1>>>mock=Mock(side_effect=side_effect)>>>mock(3)4>>>mock(-8)-7
Setting
side_effect
toNone
clears it:>>>m=Mock(side_effect=KeyError,return_value=3)>>>m()Traceback (most recent call last):...KeyError>>>m.side_effect=None>>>m()3
- call_args¶
This is either
None
(if the mock hasn’t been called), or thearguments that the mock was last called with. This will be in theform of a tuple: the first member, which can also be accessed throughtheargs
property, is any ordered arguments the mock wascalled with (or an empty tuple) and the second member, which canalso be accessed through thekwargs
property, is any keywordarguments (or an empty dictionary).>>>mock=Mock(return_value=None)>>>print(mock.call_args)None>>>mock()>>>mock.call_argscall()>>>mock.call_args==()True>>>mock(3,4)>>>mock.call_argscall(3, 4)>>>mock.call_args==((3,4),)True>>>mock.call_args.args(3, 4)>>>mock.call_args.kwargs{}>>>mock(3,4,5,key='fish',next='w00t!')>>>mock.call_argscall(3, 4, 5, key='fish', next='w00t!')>>>mock.call_args.args(3, 4, 5)>>>mock.call_args.kwargs{'key': 'fish', 'next': 'w00t!'}
call_args
, along with members of the listscall_args_list
,method_calls
andmock_calls
arecall
objects.These are tuples, so they can be unpacked to get at the individualarguments and make more complex assertions. Seecalls as tuples.Changed in version 3.8:Added
args
andkwargs
properties.
- call_args_list¶
This is a list of all the calls made to the mock object in sequence(so the length of the list is the number of times it has beencalled). Before any calls have been made it is an empty list. The
call
object can be used for conveniently constructing lists ofcalls to compare withcall_args_list
.>>>mock=Mock(return_value=None)>>>mock()>>>mock(3,4)>>>mock(key='fish',next='w00t!')>>>mock.call_args_list[call(), call(3, 4), call(key='fish', next='w00t!')]>>>expected=[(),((3,4),),({'key':'fish','next':'w00t!'},)]>>>mock.call_args_list==expectedTrue
Members of
call_args_list
arecall
objects. These can beunpacked as tuples to get at the individual arguments. Seecalls as tuples.
- method_calls¶
As well as tracking calls to themselves, mocks also track calls tomethods and attributes, andtheir methods and attributes:
>>>mock=Mock()>>>mock.method()<Mock name='mock.method()' id='...'>>>>mock.property.method.attribute()<Mock name='mock.property.method.attribute()' id='...'>>>>mock.method_calls[call.method(), call.property.method.attribute()]
Members of
method_calls
arecall
objects. These can beunpacked as tuples to get at the individual arguments. Seecalls as tuples.
- mock_calls¶
mock_calls
recordsall calls to the mock object, its methods,magic methodsand return value mocks.>>>mock=MagicMock()>>>result=mock(1,2,3)>>>mock.first(a=3)<MagicMock name='mock.first()' id='...'>>>>mock.second()<MagicMock name='mock.second()' id='...'>>>>int(mock)1>>>result(1)<MagicMock name='mock()()' id='...'>>>>expected=[call(1,2,3),call.first(a=3),call.second(),...call.__int__(),call()(1)]>>>mock.mock_calls==expectedTrue
Members of
mock_calls
arecall
objects. These can beunpacked as tuples to get at the individual arguments. Seecalls as tuples.Note
The way
mock_calls
are recorded means that where nestedcalls are made, the parameters of ancestor calls are not recordedand so will always compare equal:>>>mock=MagicMock()>>>mock.top(a=3).bottom()<MagicMock name='mock.top().bottom()' id='...'>>>>mock.mock_calls[call.top(a=3), call.top().bottom()]>>>mock.mock_calls[-1]==call.top(a=-1).bottom()True
- __class__¶
Normally the
__class__
attribute of an object will return its type.For a mock object with aspec
,__class__
returns the spec classinstead. This allows mock objects to passisinstance()
tests for theobject they are replacing / masquerading as:>>>mock=Mock(spec=3)>>>isinstance(mock,int)True
__class__
is assignable to, this allows a mock to pass anisinstance()
check without forcing you to use a spec:>>>mock=Mock()>>>mock.__class__=dict>>>isinstance(mock,dict)True
- classunittest.mock.NonCallableMock(spec=None,wraps=None,name=None,spec_set=None,**kwargs)¶
A non-callable version of
Mock
. The constructor parameters have the samemeaning ofMock
, with the exception ofreturn_value andside_effectwhich have no meaning on a non-callable mock.
Mock objects that use a class or an instance as aspec
orspec_set
are able to passisinstance()
tests:
>>>mock=Mock(spec=SomeClass)>>>isinstance(mock,SomeClass)True>>>mock=Mock(spec_set=SomeClass())>>>isinstance(mock,SomeClass)True
TheMock
classes have support for mocking magic methods. Seemagicmethods for the full details.
The mock classes and thepatch()
decorators all take arbitrary keywordarguments for configuration. For thepatch()
decorators the keywords arepassed to the constructor of the mock being created. The keyword argumentsare for configuring attributes of the mock:
>>>m=MagicMock(attribute=3,other='fish')>>>m.attribute3>>>m.other'fish'
The return value and side effect of child mocks can be set in the same way,using dotted notation. As you can’t use dotted names directly in a call youhave to create a dictionary and unpack it using**
:
>>>attrs={'method.return_value':3,'other.side_effect':KeyError}>>>mock=Mock(some_attribute='eggs',**attrs)>>>mock.some_attribute'eggs'>>>mock.method()3>>>mock.other()Traceback (most recent call last):...KeyError
A callable mock which was created with aspec (or aspec_set) willintrospect the specification object’s signature when matching calls tothe mock. Therefore, it can match the actual call’s arguments regardlessof whether they were passed positionally or by name:
>>>deff(a,b,c):pass...>>>mock=Mock(spec=f)>>>mock(1,2,c=3)<Mock name='mock()' id='140161580456576'>>>>mock.assert_called_with(1,2,3)>>>mock.assert_called_with(a=1,b=2,c=3)
This applies toassert_called_with()
,assert_called_once_with()
,assert_has_calls()
andassert_any_call()
. WhenAutospeccing, it will alsoapply to method calls on the mock object.
Changed in version 3.4:Added signature introspection on specced and autospecced mock objects.
- classunittest.mock.PropertyMock(*args,**kwargs)¶
A mock intended to be used as a
property
, or otherdescriptor, on a class.PropertyMock
provides__get__()
and__set__()
methodsso you can specify a return value when it is fetched.Fetching a
PropertyMock
instance from an object calls the mock, withno args. Setting it calls the mock with the value being set.>>>classFoo:...@property...deffoo(self):...return'something'...@foo.setter...deffoo(self,value):...pass...>>>withpatch('__main__.Foo.foo',new_callable=PropertyMock)asmock_foo:...mock_foo.return_value='mockity-mock'...this_foo=Foo()...print(this_foo.foo)...this_foo.foo=6...mockity-mock>>>mock_foo.mock_calls[call(), call(6)]
Because of the way mock attributes are stored you can’t directly attach aPropertyMock
to a mock object. Instead you can attach it to the mock typeobject:
>>>m=MagicMock()>>>p=PropertyMock(return_value=3)>>>type(m).foo=p>>>m.foo3>>>p.assert_called_once_with()
Caution
If anAttributeError
is raised byPropertyMock
,it will be interpreted as a missing descriptor and__getattr__()
will be called on the parent mock:
>>>m=MagicMock()>>>no_attribute=PropertyMock(side_effect=AttributeError)>>>type(m).my_property=no_attribute>>>m.my_property<MagicMock name='mock.my_property' id='140165240345424'>
See__getattr__()
for details.
- classunittest.mock.AsyncMock(spec=None,side_effect=None,return_value=DEFAULT,wraps=None,name=None,spec_set=None,unsafe=False,**kwargs)¶
An asynchronous version of
MagicMock
. TheAsyncMock
object willbehave so the object is recognized as an async function, and the result of acall is an awaitable.>>>mock=AsyncMock()>>>inspect.iscoroutinefunction(mock)True>>>inspect.isawaitable(mock())True
The result of
mock()
is an async function which will have the outcomeofside_effect
orreturn_value
after it has been awaited:if
side_effect
is a function, the async function will return theresult of that function,if
side_effect
is an exception, the async function will raise theexception,if
side_effect
is an iterable, the async function will return thenext value of the iterable, however, if the sequence of result isexhausted,StopAsyncIteration
is raised immediately,if
side_effect
is not defined, the async function will return thevalue defined byreturn_value
, hence, by default, the async functionreturns a newAsyncMock
object.
Setting thespec of a
Mock
orMagicMock
to an async functionwill result in a coroutine object being returned after calling.>>>asyncdefasync_func():pass...>>>mock=MagicMock(async_func)>>>mock<MagicMock spec='function' id='...'>>>>mock()<coroutine object AsyncMockMixin._mock_call at ...>
Setting thespec of a
Mock
,MagicMock
, orAsyncMock
to a class with asynchronous and synchronous functions will automaticallydetect the synchronous functions and set them asMagicMock
(if theparent mock isAsyncMock
orMagicMock
) orMock
(ifthe parent mock isMock
). All asynchronous functions will beAsyncMock
.>>>classExampleClass:...defsync_foo():...pass...asyncdefasync_foo():...pass...>>>a_mock=AsyncMock(ExampleClass)>>>a_mock.sync_foo<MagicMock name='mock.sync_foo' id='...'>>>>a_mock.async_foo<AsyncMock name='mock.async_foo' id='...'>>>>mock=Mock(ExampleClass)>>>mock.sync_foo<Mock name='mock.sync_foo' id='...'>>>>mock.async_foo<AsyncMock name='mock.async_foo' id='...'>
Added in version 3.8.
- assert_awaited()¶
Assert that the mock was awaited at least once. Note that this is separatefrom the object having been called, the
await
keyword must be used:>>>mock=AsyncMock()>>>asyncdefmain(coroutine_mock):...awaitcoroutine_mock...>>>coroutine_mock=mock()>>>mock.calledTrue>>>mock.assert_awaited()Traceback (most recent call last):...AssertionError:Expected mock to have been awaited.>>>asyncio.run(main(coroutine_mock))>>>mock.assert_awaited()
- assert_awaited_once()¶
Assert that the mock was awaited exactly once.
>>>mock=AsyncMock()>>>asyncdefmain():...awaitmock()...>>>asyncio.run(main())>>>mock.assert_awaited_once()>>>asyncio.run(main())>>>mock.assert_awaited_once()Traceback (most recent call last):...AssertionError:Expected mock to have been awaited once. Awaited 2 times.
- assert_awaited_with(*args,**kwargs)¶
Assert that the last await was with the specified arguments.
>>>mock=AsyncMock()>>>asyncdefmain(*args,**kwargs):...awaitmock(*args,**kwargs)...>>>asyncio.run(main('foo',bar='bar'))>>>mock.assert_awaited_with('foo',bar='bar')>>>mock.assert_awaited_with('other')Traceback (most recent call last):...AssertionError:expected await not found.Expected: mock('other')Actual: mock('foo', bar='bar')
- assert_awaited_once_with(*args,**kwargs)¶
Assert that the mock was awaited exactly once and with the specifiedarguments.
>>>mock=AsyncMock()>>>asyncdefmain(*args,**kwargs):...awaitmock(*args,**kwargs)...>>>asyncio.run(main('foo',bar='bar'))>>>mock.assert_awaited_once_with('foo',bar='bar')>>>asyncio.run(main('foo',bar='bar'))>>>mock.assert_awaited_once_with('foo',bar='bar')Traceback (most recent call last):...AssertionError:Expected mock to have been awaited once. Awaited 2 times.
- assert_any_await(*args,**kwargs)¶
Assert the mock has ever been awaited with the specified arguments.
>>>mock=AsyncMock()>>>asyncdefmain(*args,**kwargs):...awaitmock(*args,**kwargs)...>>>asyncio.run(main('foo',bar='bar'))>>>asyncio.run(main('hello'))>>>mock.assert_any_await('foo',bar='bar')>>>mock.assert_any_await('other')Traceback (most recent call last):...AssertionError:mock('other') await not found
- assert_has_awaits(calls,any_order=False)¶
Assert the mock has been awaited with the specified calls.The
await_args_list
list is checked for the awaits.Ifany_order is false then the awaits must besequential. There can be extra calls before or after thespecified awaits.
Ifany_order is true then the awaits can be in any order, butthey must all appear in
await_args_list
.>>>mock=AsyncMock()>>>asyncdefmain(*args,**kwargs):...awaitmock(*args,**kwargs)...>>>calls=[call("foo"),call("bar")]>>>mock.assert_has_awaits(calls)Traceback (most recent call last):...AssertionError:Awaits not found.Expected: [call('foo'), call('bar')]Actual: []>>>asyncio.run(main('foo'))>>>asyncio.run(main('bar'))>>>mock.assert_has_awaits(calls)
- assert_not_awaited()¶
Assert that the mock was never awaited.
>>>mock=AsyncMock()>>>mock.assert_not_awaited()
- reset_mock(*args,**kwargs)¶
See
Mock.reset_mock()
. Also setsawait_count
to 0,await_args
to None, and clears theawait_args_list
.
- await_count¶
An integer keeping track of how many times the mock object has been awaited.
>>>mock=AsyncMock()>>>asyncdefmain():...awaitmock()...>>>asyncio.run(main())>>>mock.await_count1>>>asyncio.run(main())>>>mock.await_count2
- await_args¶
This is either
None
(if the mock hasn’t been awaited), or the arguments thatthe mock was last awaited with. Functions the same asMock.call_args
.>>>mock=AsyncMock()>>>asyncdefmain(*args):...awaitmock(*args)...>>>mock.await_args>>>asyncio.run(main('foo'))>>>mock.await_argscall('foo')>>>asyncio.run(main('bar'))>>>mock.await_argscall('bar')
- await_args_list¶
This is a list of all the awaits made to the mock object in sequence (so thelength of the list is the number of times it has been awaited). Before anyawaits have been made it is an empty list.
>>>mock=AsyncMock()>>>asyncdefmain(*args):...awaitmock(*args)...>>>mock.await_args_list[]>>>asyncio.run(main('foo'))>>>mock.await_args_list[call('foo')]>>>asyncio.run(main('bar'))>>>mock.await_args_list[call('foo'), call('bar')]
- classunittest.mock.ThreadingMock(spec=None,side_effect=None,return_value=DEFAULT,wraps=None,name=None,spec_set=None,unsafe=False,*,timeout=UNSET,**kwargs)¶
A version of
MagicMock
for multithreading tests. TheThreadingMock
object provides extra methods to wait for a call tobe invoked, rather than assert on it immediately.The default timeout is specified by the
timeout
argument, or if unset by theThreadingMock.DEFAULT_TIMEOUT
attribute, which defaults to blocking (None
).You can configure the global default timeout by setting
ThreadingMock.DEFAULT_TIMEOUT
.- wait_until_called(*,timeout=UNSET)¶
Waits until the mock is called.
If a timeout was passed at the creation of the mock or if a timeoutargument is passed to this function, the function raises an
AssertionError
if the call is not performed in time.>>>mock=ThreadingMock()>>>thread=threading.Thread(target=mock)>>>thread.start()>>>mock.wait_until_called(timeout=1)>>>thread.join()
- wait_until_any_call_with(*args,**kwargs)¶
Waits until the mock is called with the specified arguments.
If a timeout was passed at the creation of the mockthe function raises an
AssertionError
if the call is not performed in time.>>>mock=ThreadingMock()>>>thread=threading.Thread(target=mock,args=("arg1","arg2",),kwargs={"arg":"thing"})>>>thread.start()>>>mock.wait_until_any_call_with("arg1","arg2",arg="thing")>>>thread.join()
- DEFAULT_TIMEOUT¶
Global default timeout in seconds to create instances of
ThreadingMock
.
Added in version 3.13.
Calling¶
Mock objects are callable. The call will return the value set as thereturn_value
attribute. The default return value is a new Mockobject; it is created the first time the return value is accessed (eitherexplicitly or by calling the Mock) - but it is stored and the same onereturned each time.
Calls made to the object will be recorded in the attributeslikecall_args
andcall_args_list
.
Ifside_effect
is set then it will be called after the call hasbeen recorded, so ifside_effect
raises an exception the call is stillrecorded.
The simplest way to make a mock raise an exception when called is to makeside_effect
an exception class or instance:
>>>m=MagicMock(side_effect=IndexError)>>>m(1,2,3)Traceback (most recent call last):...IndexError>>>m.mock_calls[call(1, 2, 3)]>>>m.side_effect=KeyError('Bang!')>>>m('two','three','four')Traceback (most recent call last):...KeyError:'Bang!'>>>m.mock_calls[call(1, 2, 3), call('two', 'three', 'four')]
Ifside_effect
is a function then whatever that function returns is whatcalls to the mock return. Theside_effect
function is called with thesame arguments as the mock. This allows you to vary the return value of thecall dynamically, based on the input:
>>>defside_effect(value):...returnvalue+1...>>>m=MagicMock(side_effect=side_effect)>>>m(1)2>>>m(2)3>>>m.mock_calls[call(1), call(2)]
If you want the mock to still return the default return value (a new mock), orany set return value, then there are two ways of doing this. Either returnreturn_value
from insideside_effect
, or returnDEFAULT
:
>>>m=MagicMock()>>>defside_effect(*args,**kwargs):...returnm.return_value...>>>m.side_effect=side_effect>>>m.return_value=3>>>m()3>>>defside_effect(*args,**kwargs):...returnDEFAULT...>>>m.side_effect=side_effect>>>m()3
To remove aside_effect
, and return to the default behaviour, set theside_effect
toNone
:
>>>m=MagicMock(return_value=6)>>>defside_effect(*args,**kwargs):...return3...>>>m.side_effect=side_effect>>>m()3>>>m.side_effect=None>>>m()6
Theside_effect
can also be any iterable object. Repeated calls to the mockwill return values from the iterable (until the iterable is exhausted andaStopIteration
is raised):
>>>m=MagicMock(side_effect=[1,2,3])>>>m()1>>>m()2>>>m()3>>>m()Traceback (most recent call last):...StopIteration
If any members of the iterable are exceptions they will be raised instead ofreturned:
>>>iterable=(33,ValueError,66)>>>m=MagicMock(side_effect=iterable)>>>m()33>>>m()Traceback (most recent call last):...ValueError>>>m()66
Deleting Attributes¶
Mock objects create attributes on demand. This allows them to pretend to beobjects of any type.
You may want a mock object to returnFalse
to ahasattr()
call, or raise anAttributeError
when an attribute is fetched. You can do this by providingan object as aspec
for a mock, but that isn’t always convenient.
You “block” attributes by deleting them. Once deleted, accessing an attributewill raise anAttributeError
.
>>>mock=MagicMock()>>>hasattr(mock,'m')True>>>delmock.m>>>hasattr(mock,'m')False>>>delmock.f>>>mock.fTraceback (most recent call last):...AttributeError:f
Mock names and the name attribute¶
Since “name” is an argument to theMock
constructor, if you want yourmock object to have a “name” attribute you can’t just pass it in at creationtime. There are two alternatives. One option is to useconfigure_mock()
:
>>>mock=MagicMock()>>>mock.configure_mock(name='my_name')>>>mock.name'my_name'
A simpler option is to simply set the “name” attribute after mock creation:
>>>mock=MagicMock()>>>mock.name="foo"
Attaching Mocks as Attributes¶
When you attach a mock as an attribute of another mock (or as the returnvalue) it becomes a “child” of that mock. Calls to the child are recorded inthemethod_calls
andmock_calls
attributes of theparent. This is useful for configuring child mocks and then attaching them tothe parent, or for attaching mocks to a parent that records all calls to thechildren and allows you to make assertions about the order of calls betweenmocks:
>>>parent=MagicMock()>>>child1=MagicMock(return_value=None)>>>child2=MagicMock(return_value=None)>>>parent.child1=child1>>>parent.child2=child2>>>child1(1)>>>child2(2)>>>parent.mock_calls[call.child1(1), call.child2(2)]
The exception to this is if the mock has a name. This allows you to preventthe “parenting” if for some reason you don’t want it to happen.
>>>mock=MagicMock()>>>not_a_child=MagicMock(name='not-a-child')>>>mock.attribute=not_a_child>>>mock.attribute()<MagicMock name='not-a-child()' id='...'>>>>mock.mock_calls[]
Mocks created for you bypatch()
are automatically given names. Toattach mocks that have names to a parent you use theattach_mock()
method:
>>>thing1=object()>>>thing2=object()>>>parent=MagicMock()>>>withpatch('__main__.thing1',return_value=None)aschild1:...withpatch('__main__.thing2',return_value=None)aschild2:...parent.attach_mock(child1,'child1')...parent.attach_mock(child2,'child2')...child1('one')...child2('two')...>>>parent.mock_calls[call.child1('one'), call.child2('two')]
The only exceptions are magic methods and attributes (those that haveleading and trailing double underscores). Mock doesn’t create these butinstead raises anAttributeError
. This is because the interpreterwill often implicitly request these methods, and getsvery confused toget a new Mock object when it expects a magic method. If you need magicmethod support seemagic methods.
The patchers¶
The patch decorators are used for patching objects only within the scope ofthe function they decorate. They automatically handle the unpatching for you,even if exceptions are raised. All of these functions can also be used in withstatements or as class decorators.
patch¶
Note
The key is to do the patching in the right namespace. See the sectionwhere to patch.
- unittest.mock.patch(target,new=DEFAULT,spec=None,create=False,spec_set=None,autospec=None,new_callable=None,**kwargs)¶
patch()
acts as a function decorator, class decorator or a contextmanager. Inside the body of the function or with statement, thetargetis patched with anew object. When the function/with statement exitsthe patch is undone.Ifnew is omitted, then the target is replaced with an
AsyncMock
if the patched object is an async function oraMagicMock
otherwise.Ifpatch()
is used as a decorator andnew isomitted, the created mock is passed in as an extra argument to thedecorated function. Ifpatch()
is used as a context manager the createdmock is returned by the context manager.target should be a string in the form
'package.module.ClassName'
. Thetarget is imported and the specified object replaced with thenewobject, so thetarget must be importable from the environment you arecallingpatch()
from. The target is imported when the decorated functionis executed, not at decoration time.Thespec andspec_set keyword arguments are passed to the
MagicMock
if patch is creating one for you.In addition you can pass
spec=True
orspec_set=True
, which causespatch to pass in the object being mocked as the spec/spec_set object.new_callable allows you to specify a different class, or callable object,that will be called to create thenew object. By default
AsyncMock
is used for async functions andMagicMock
for the rest.A more powerful form ofspec isautospec. If you set
autospec=True
then the mock will be created with a spec from the object being replaced.All attributes of the mock will also have the spec of the correspondingattribute of the object being replaced. Methods and functions being mockedwill have their arguments checked and will raise aTypeError
if they arecalled with the wrong signature. For mocksreplacing a class, their return value (the ‘instance’) will have the samespec as the class. See thecreate_autospec()
function andAutospeccing.Instead of
autospec=True
you can passautospec=some_object
to use anarbitrary object as the spec instead of the one being replaced.By default
patch()
will fail to replace attributes that don’t exist.If you pass increate=True
, and the attribute doesn’t exist, patch willcreate the attribute for you when the patched function is called, and deleteit again after the patched function has exited. This is useful for writingtests against attributes that your production code creates at runtime. It isoff by default because it can be dangerous. With it switched on you canwrite passing tests against APIs that don’t actually exist!Note
Changed in version 3.5:If you are patching builtins in a module then you don’tneed to pass
create=True
, it will be added by default.Patch can be used as a
TestCase
class decorator. It works bydecorating each test method in the class. This reduces the boilerplatecode when your test methods share a common patchings set.patch()
findstests by looking for method names that start withpatch.TEST_PREFIX
.By default this is'test'
, which matches the wayunittest
finds tests.You can specify an alternative prefix by settingpatch.TEST_PREFIX
.Patch can be used as a context manager, with the with statement. Here thepatching applies to the indented block after the with statement. If youuse “as” then the patched object will be bound to the name after the“as”; very useful if
patch()
is creating a mock object for you.patch()
takes arbitrary keyword arguments. These will be passed toAsyncMock
if the patched object is asynchronous, toMagicMock
otherwise or tonew_callable if specified.patch.dict(...)
,patch.multiple(...)
andpatch.object(...)
areavailable for alternate use-cases.
patch()
as function decorator, creating the mock for you and passing it intothe decorated function:
>>>@patch('__main__.SomeClass')...deffunction(normal_argument,mock_class):...print(mock_classisSomeClass)...>>>function(None)True
Patching a class replaces the class with aMagicMock
instance. If theclass is instantiated in the code under test then it will be thereturn_value
of the mock that will be used.
If the class is instantiated multiple times you could useside_effect
to return a new mock each time. Alternatively youcan set thereturn_value to be anything you want.
To configure return values on methods ofinstances on the patched classyou must do this on thereturn_value
. For example:
>>>classClass:...defmethod(self):...pass...>>>withpatch('__main__.Class')asMockClass:...instance=MockClass.return_value...instance.method.return_value='foo'...assertClass()isinstance...assertClass().method()=='foo'...
If you usespec orspec_set andpatch()
is replacing aclass, then thereturn value of the created mock will have the same spec.
>>>Original=Class>>>patcher=patch('__main__.Class',spec=True)>>>MockClass=patcher.start()>>>instance=MockClass()>>>assertisinstance(instance,Original)>>>patcher.stop()
Thenew_callable argument is useful where you want to use an alternativeclass to the defaultMagicMock
for the created mock. For example, ifyou wanted aNonCallableMock
to be used:
>>>thing=object()>>>withpatch('__main__.thing',new_callable=NonCallableMock)asmock_thing:...assertthingismock_thing...thing()...Traceback (most recent call last):...TypeError:'NonCallableMock' object is not callable
Another use case might be to replace an object with anio.StringIO
instance:
>>>fromioimportStringIO>>>deffoo():...print('Something')...>>>@patch('sys.stdout',new_callable=StringIO)...deftest(mock_stdout):...foo()...assertmock_stdout.getvalue()=='Something\n'...>>>test()
Whenpatch()
is creating a mock for you, it is common that the first thingyou need to do is to configure the mock. Some of that configuration can be donein the call to patch. Any arbitrary keywords you pass into the call will beused to set attributes on the created mock:
>>>patcher=patch('__main__.thing',first='one',second='two')>>>mock_thing=patcher.start()>>>mock_thing.first'one'>>>mock_thing.second'two'
As well as attributes on the created mock attributes, like thereturn_value
andside_effect
, of child mocks canalso be configured. These aren’t syntactically valid to pass in directly askeyword arguments, but a dictionary with these as keys can still be expandedinto apatch()
call using**
:
>>>config={'method.return_value':3,'other.side_effect':KeyError}>>>patcher=patch('__main__.thing',**config)>>>mock_thing=patcher.start()>>>mock_thing.method()3>>>mock_thing.other()Traceback (most recent call last):...KeyError
By default, attempting to patch a function in a module (or a method or anattribute in a class) that does not exist will fail withAttributeError
:
>>>@patch('sys.non_existing_attribute',42)...deftest():...assertsys.non_existing_attribute==42...>>>test()Traceback (most recent call last):...AttributeError:<module 'sys' (built-in)> does not have the attribute 'non_existing_attribute'
but addingcreate=True
in the call topatch()
will make the previous examplework as expected:
>>>@patch('sys.non_existing_attribute',42,create=True)...deftest(mock_stdout):...assertsys.non_existing_attribute==42...>>>test()
patch.object¶
- patch.object(target,attribute,new=DEFAULT,spec=None,create=False,spec_set=None,autospec=None,new_callable=None,**kwargs)¶
patch the named member (attribute) on an object (target) with a mockobject.
patch.object()
can be used as a decorator, class decorator or a contextmanager. Argumentsnew,spec,create,spec_set,autospec andnew_callable have the same meaning as forpatch()
. Likepatch()
,patch.object()
takes arbitrary keyword arguments for configuring the mockobject it creates.When used as a class decorator
patch.object()
honourspatch.TEST_PREFIX
for choosing which methods to wrap.
You can either callpatch.object()
with three arguments or two arguments. Thethree argument form takes the object to be patched, the attribute name and theobject to replace the attribute with.
When calling with the two argument form you omit the replacement object, and amock is created for you and passed in as an extra argument to the decoratedfunction:
>>>@patch.object(SomeClass,'class_method')...deftest(mock_method):...SomeClass.class_method(3)...mock_method.assert_called_with(3)...>>>test()
spec,create and the other arguments topatch.object()
have the samemeaning as they do forpatch()
.
patch.dict¶
- patch.dict(in_dict,values=(),clear=False,**kwargs)¶
Patch a dictionary, or dictionary like object, and restore the dictionaryto its original state after the test, where the restored dictionary is acopy of the dictionary as it was before the test.
in_dict can be a dictionary or a mapping like container. If it is amapping then it must at least support getting, setting and deleting itemsplus iterating over keys.
in_dict can also be a string specifying the name of the dictionary, whichwill then be fetched by importing it.
values can be a dictionary of values to set in the dictionary.valuescan also be an iterable of
(key,value)
pairs.Ifclear is true then the dictionary will be cleared before the newvalues are set.
patch.dict()
can also be called with arbitrary keyword arguments to setvalues in the dictionary.Changed in version 3.8:
patch.dict()
now returns the patched dictionary when used as a contextmanager.
patch.dict()
can be used as a context manager, decorator or classdecorator:
>>>foo={}>>>@patch.dict(foo,{'newkey':'newvalue'})...deftest():...assertfoo=={'newkey':'newvalue'}...>>>test()>>>assertfoo=={}
When used as a class decoratorpatch.dict()
honourspatch.TEST_PREFIX
(default to'test'
) for choosing which methods to wrap:
>>>importos>>>importunittest>>>fromunittest.mockimportpatch>>>@patch.dict('os.environ',{'newkey':'newvalue'})...classTestSample(unittest.TestCase):...deftest_sample(self):...self.assertEqual(os.environ['newkey'],'newvalue')
If you want to use a different prefix for your test, you can inform thepatchers of the different prefix by settingpatch.TEST_PREFIX
. Formore details about how to change the value of seeTEST_PREFIX.
patch.dict()
can be used to add members to a dictionary, or simply let a testchange a dictionary, and ensure the dictionary is restored when the testends.
>>>foo={}>>>withpatch.dict(foo,{'newkey':'newvalue'})aspatched_foo:...assertfoo=={'newkey':'newvalue'}...assertpatched_foo=={'newkey':'newvalue'}...# You can add, update or delete keys of foo (or patched_foo, it's the same dict)...patched_foo['spam']='eggs'...>>>assertfoo=={}>>>assertpatched_foo=={}
>>>importos>>>withpatch.dict('os.environ',{'newkey':'newvalue'}):...print(os.environ['newkey'])...newvalue>>>assert'newkey'notinos.environ
Keywords can be used in thepatch.dict()
call to set values in the dictionary:
>>>mymodule=MagicMock()>>>mymodule.function.return_value='fish'>>>withpatch.dict('sys.modules',mymodule=mymodule):...importmymodule...mymodule.function('some','args')...'fish'
patch.dict()
can be used with dictionary like objects that aren’t actuallydictionaries. At the very minimum they must support item getting, setting,deleting and either iteration or membership test. This corresponds to themagic methods__getitem__()
,__setitem__()
,__delitem__()
and either__iter__()
or__contains__()
.
>>>classContainer:...def__init__(self):...self.values={}...def__getitem__(self,name):...returnself.values[name]...def__setitem__(self,name,value):...self.values[name]=value...def__delitem__(self,name):...delself.values[name]...def__iter__(self):...returniter(self.values)...>>>thing=Container()>>>thing['one']=1>>>withpatch.dict(thing,one=2,two=3):...assertthing['one']==2...assertthing['two']==3...>>>assertthing['one']==1>>>assertlist(thing)==['one']
patch.multiple¶
- patch.multiple(target,spec=None,create=False,spec_set=None,autospec=None,new_callable=None,**kwargs)¶
Perform multiple patches in a single call. It takes the object to bepatched (either as an object or a string to fetch the object by importing)and keyword arguments for the patches:
withpatch.multiple(settings,FIRST_PATCH='one',SECOND_PATCH='two'):...
Use
DEFAULT
as the value if you wantpatch.multiple()
to createmocks for you. In this case the created mocks are passed into a decoratedfunction by keyword, and a dictionary is returned whenpatch.multiple()
isused as a context manager.patch.multiple()
can be used as a decorator, class decorator or a contextmanager. The argumentsspec,spec_set,create,autospec andnew_callable have the same meaning as forpatch()
. These arguments willbe applied toall patches done bypatch.multiple()
.When used as a class decorator
patch.multiple()
honourspatch.TEST_PREFIX
for choosing which methods to wrap.
If you wantpatch.multiple()
to create mocks for you, then you can useDEFAULT
as the value. If you usepatch.multiple()
as a decoratorthen the created mocks are passed into the decorated function by keyword.
>>>thing=object()>>>other=object()>>>@patch.multiple('__main__',thing=DEFAULT,other=DEFAULT)...deftest_function(thing,other):...assertisinstance(thing,MagicMock)...assertisinstance(other,MagicMock)...>>>test_function()
patch.multiple()
can be nested with otherpatch
decorators, but put argumentspassed by keywordafter any of the standard arguments created bypatch()
:
>>>@patch('sys.exit')...@patch.multiple('__main__',thing=DEFAULT,other=DEFAULT)...deftest_function(mock_exit,other,thing):...assert'other'inrepr(other)...assert'thing'inrepr(thing)...assert'exit'inrepr(mock_exit)...>>>test_function()
Ifpatch.multiple()
is used as a context manager, the value returned by thecontext manager is a dictionary where created mocks are keyed by name:
>>>withpatch.multiple('__main__',thing=DEFAULT,other=DEFAULT)asvalues:...assert'other'inrepr(values['other'])...assert'thing'inrepr(values['thing'])...assertvalues['thing']isthing...assertvalues['other']isother...
patch methods: start and stop¶
All the patchers havestart()
andstop()
methods. These make it simpler to dopatching insetUp
methods or where you want to do multiple patches withoutnesting decorators or with statements.
To use them callpatch()
,patch.object()
orpatch.dict()
asnormal and keep a reference to the returnedpatcher
object. You can thencallstart()
to put the patch in place andstop()
to undo it.
If you are usingpatch()
to create a mock for you then it will be returned bythe call topatcher.start
.
>>>patcher=patch('package.module.ClassName')>>>frompackageimportmodule>>>original=module.ClassName>>>new_mock=patcher.start()>>>assertmodule.ClassNameisnotoriginal>>>assertmodule.ClassNameisnew_mock>>>patcher.stop()>>>assertmodule.ClassNameisoriginal>>>assertmodule.ClassNameisnotnew_mock
A typical use case for this might be for doing multiple patches in thesetUp
method of aTestCase
:
>>>classMyTest(unittest.TestCase):...defsetUp(self):...self.patcher1=patch('package.module.Class1')...self.patcher2=patch('package.module.Class2')...self.MockClass1=self.patcher1.start()...self.MockClass2=self.patcher2.start()......deftearDown(self):...self.patcher1.stop()...self.patcher2.stop()......deftest_something(self):...assertpackage.module.Class1isself.MockClass1...assertpackage.module.Class2isself.MockClass2...>>>MyTest('test_something').run()
Caution
If you use this technique you must ensure that the patching is “undone” bycallingstop
. This can be fiddlier than you might think, because if anexception is raised in thesetUp
thentearDown
is not called.unittest.TestCase.addCleanup()
makes this easier:
>>>classMyTest(unittest.TestCase):...defsetUp(self):...patcher=patch('package.module.Class')...self.MockClass=patcher.start()...self.addCleanup(patcher.stop)......deftest_something(self):...assertpackage.module.Classisself.MockClass...
As an added bonus you no longer need to keep a reference to thepatcher
object.
It is also possible to stop all patches which have been started by usingpatch.stopall()
.
- patch.stopall()¶
Stop all active patches. Only stops patches started with
start
.
patch builtins¶
You can patch any builtins within a module. The following example patchesbuiltinord()
:
>>>@patch('__main__.ord')...deftest(mock_ord):...mock_ord.return_value=101...print(ord('c'))...>>>test()101
TEST_PREFIX¶
All of the patchers can be used as class decorators. When used in this waythey wrap every test method on the class. The patchers recognise methods thatstart with'test'
as being test methods. This is the same way that theunittest.TestLoader
finds test methods by default.
It is possible that you want to use a different prefix for your tests. You caninform the patchers of the different prefix by settingpatch.TEST_PREFIX
:
>>>patch.TEST_PREFIX='foo'>>>value=3>>>>>>@patch('__main__.value','not three')...classThing:...deffoo_one(self):...print(value)...deffoo_two(self):...print(value)...>>>>>>Thing().foo_one()not three>>>Thing().foo_two()not three>>>value3
Nesting Patch Decorators¶
If you want to perform multiple patches then you can simply stack up thedecorators.
You can stack up multiple patch decorators using this pattern:
>>>@patch.object(SomeClass,'class_method')...@patch.object(SomeClass,'static_method')...deftest(mock1,mock2):...assertSomeClass.static_methodismock1...assertSomeClass.class_methodismock2...SomeClass.static_method('foo')...SomeClass.class_method('bar')...returnmock1,mock2...>>>mock1,mock2=test()>>>mock1.assert_called_once_with('foo')>>>mock2.assert_called_once_with('bar')
Note that the decorators are applied from the bottom upwards. This is thestandard way that Python applies decorators. The order of the created mockspassed into your test function matches this order.
Where to patch¶
patch()
works by (temporarily) changing the object that aname points to withanother one. There can be many names pointing to any individual object, sofor patching to work you must ensure that you patch the name used by the systemunder test.
The basic principle is that you patch where an object islooked up, whichis not necessarily the same place as where it is defined. A couple ofexamples will help to clarify this.
Imagine we have a project that we want to test with the following structure:
a.py->DefinesSomeClassb.py->fromaimportSomeClass->some_functioninstantiatesSomeClass
Now we want to testsome_function
but we want to mock outSomeClass
usingpatch()
. The problem is that when we import module b, which we will have todo when it importsSomeClass
from module a. If we usepatch()
to mock outa.SomeClass
then it will have no effect on our test; module b already has areference to therealSomeClass
and it looks like our patching had noeffect.
The key is to patch outSomeClass
where it is used (or where it is looked up).In this casesome_function
will actually look upSomeClass
in module b,where we have imported it. The patching should look like:
@patch('b.SomeClass')
However, consider the alternative scenario where instead offromaimportSomeClass
module b doesimporta
andsome_function
usesa.SomeClass
. Bothof these import forms are common. In this case the class we want to patch isbeing looked up in the module and so we have to patcha.SomeClass
instead:
@patch('a.SomeClass')
Patching Descriptors and Proxy Objects¶
Bothpatch andpatch.object correctly patch and restore descriptors: classmethods, static methods and properties. You should patch these on theclassrather than an instance. They also work withsome objectsthat proxy attribute access, like thedjango settings object.
MagicMock and magic method support¶
Mocking Magic Methods¶
Mock
supports mocking the Python protocol methods, also known as“magic methods”. This allows mock objects to replacecontainers or other objects that implement Python protocols.
Because magic methods are looked up differently from normal methods[2], thissupport has been specially implemented. This means that only specific magicmethods are supported. The supported list includesalmost all of them. Ifthere are any missing that you need please let us know.
You mock magic methods by setting the method you are interested in to a functionor a mock instance. If you are using a function then itmust takeself
asthe first argument[3].
>>>def__str__(self):...return'fooble'...>>>mock=Mock()>>>mock.__str__=__str__>>>str(mock)'fooble'
>>>mock=Mock()>>>mock.__str__=Mock()>>>mock.__str__.return_value='fooble'>>>str(mock)'fooble'
>>>mock=Mock()>>>mock.__iter__=Mock(return_value=iter([]))>>>list(mock)[]
One use case for this is for mocking objects used as context managers in awith
statement:
>>>mock=Mock()>>>mock.__enter__=Mock(return_value='foo')>>>mock.__exit__=Mock(return_value=False)>>>withmockasm:...assertm=='foo'...>>>mock.__enter__.assert_called_with()>>>mock.__exit__.assert_called_with(None,None,None)
Calls to magic methods do not appear inmethod_calls
, but theyare recorded inmock_calls
.
Note
If you use thespec keyword argument to create a mock then attempting toset a magic method that isn’t in the spec will raise anAttributeError
.
The full list of supported magic methods is:
__hash__
,__sizeof__
,__repr__
and__str__
__dir__
,__format__
and__subclasses__
__round__
,__floor__
,__trunc__
and__ceil__
Comparisons:
__lt__
,__gt__
,__le__
,__ge__
,__eq__
and__ne__
Container methods:
__getitem__
,__setitem__
,__delitem__
,__contains__
,__len__
,__iter__
,__reversed__
and__missing__
Context manager:
__enter__
,__exit__
,__aenter__
and__aexit__
Unary numeric methods:
__neg__
,__pos__
and__invert__
The numeric methods (including right hand and in-place variants):
__add__
,__sub__
,__mul__
,__matmul__
,__truediv__
,__floordiv__
,__mod__
,__divmod__
,__lshift__
,__rshift__
,__and__
,__xor__
,__or__
, and__pow__
Numeric conversion methods:
__complex__
,__int__
,__float__
and__index__
Descriptor methods:
__get__
,__set__
and__delete__
Pickling:
__reduce__
,__reduce_ex__
,__getinitargs__
,__getnewargs__
,__getstate__
and__setstate__
File system path representation:
__fspath__
Asynchronous iteration methods:
__aiter__
and__anext__
Changed in version 3.8:Added support foros.PathLike.__fspath__()
.
Changed in version 3.8:Added support for__aenter__
,__aexit__
,__aiter__
and__anext__
.
The following methods exist but arenot supported as they are either in useby mock, can’t be set dynamically, or can cause problems:
__getattr__
,__setattr__
,__init__
and__new__
__prepare__
,__instancecheck__
,__subclasscheck__
,__del__
Magic Mock¶
There are twoMagicMock
variants:MagicMock
andNonCallableMagicMock
.
- classunittest.mock.MagicMock(*args,**kw)¶
MagicMock
is a subclass ofMock
with default implementationsof most of themagic methods. You can useMagicMock
without having to configure the magic methods yourself.The constructor parameters have the same meaning as for
Mock
.If you use thespec orspec_set arguments thenonly magic methodsthat exist in the spec will be created.
- classunittest.mock.NonCallableMagicMock(*args,**kw)¶
A non-callable version of
MagicMock
.The constructor parameters have the same meaning as for
MagicMock
, with the exception ofreturn_value andside_effect which have no meaning on a non-callable mock.
The magic methods are setup withMagicMock
objects, so you can configure themand use them in the usual way:
>>>mock=MagicMock()>>>mock[3]='fish'>>>mock.__setitem__.assert_called_with(3,'fish')>>>mock.__getitem__.return_value='result'>>>mock[2]'result'
By default many of the protocol methods are required to return objects of aspecific type. These methods are preconfigured with a default return value, sothat they can be used without you having to do anything if you aren’t interestedin the return value. You can stillset the return value manually if you wantto change the default.
Methods and their defaults:
__lt__
:NotImplemented
__gt__
:NotImplemented
__le__
:NotImplemented
__ge__
:NotImplemented
__int__
:1
__contains__
:False
__len__
:0
__iter__
:iter([])
__exit__
:False
__aexit__
:False
__complex__
:1j
__float__
:1.0
__bool__
:True
__index__
:1
__hash__
: default hash for the mock__str__
: default str for the mock__sizeof__
: default sizeof for the mock
For example:
>>>mock=MagicMock()>>>int(mock)1>>>len(mock)0>>>list(mock)[]>>>object()inmockFalse
The two equality methods,__eq__()
and__ne__()
, are special.They do the default equality comparison on identity, using theside_effect
attribute, unless you change their return value toreturn something else:
>>>MagicMock()==3False>>>MagicMock()!=3True>>>mock=MagicMock()>>>mock.__eq__.return_value=True>>>mock==3True
The return value ofMagicMock.__iter__()
can be any iterable object and isn’trequired to be an iterator:
>>>mock=MagicMock()>>>mock.__iter__.return_value=['a','b','c']>>>list(mock)['a', 'b', 'c']>>>list(mock)['a', 'b', 'c']
If the return valueis an iterator, then iterating over it once will consumeit and subsequent iterations will result in an empty list:
>>>mock.__iter__.return_value=iter(['a','b','c'])>>>list(mock)['a', 'b', 'c']>>>list(mock)[]
MagicMock
has all of the supported magic methods configured except for someof the obscure and obsolete ones. You can still set these up if you want.
Magic methods that are supported but not setup by default inMagicMock
are:
__subclasses__
__dir__
__format__
__get__
,__set__
and__delete__
__reversed__
and__missing__
__reduce__
,__reduce_ex__
,__getinitargs__
,__getnewargs__
,__getstate__
and__setstate__
__getformat__
Magic methodsshould be looked up on the class rather than theinstance. Different versions of Python are inconsistent about applying thisrule. The supported protocol methods should work with all supported versionsof Python.
[3]The function is basically hooked up to the class, but eachMock
instance is kept isolated from the others.
Helpers¶
sentinel¶
- unittest.mock.sentinel¶
The
sentinel
object provides a convenient way of providing uniqueobjects for your tests.Attributes are created on demand when you access them by name. Accessingthe same attribute will always return the same object. The objectsreturned have a sensible repr so that test failure messages are readable.
Sometimes when testing you need to test that a specific object is passed as anargument to another method, or returned. It can be common to create namedsentinel objects to test this.sentinel
provides a convenient way ofcreating and testing the identity of objects like this.
In this example we monkey patchmethod
to returnsentinel.some_object
:
>>>real=ProductionClass()>>>real.method=Mock(name="method")>>>real.method.return_value=sentinel.some_object>>>result=real.method()>>>assertresultissentinel.some_object>>>resultsentinel.some_object
DEFAULT¶
- unittest.mock.DEFAULT¶
The
DEFAULT
object is a pre-created sentinel (actuallysentinel.DEFAULT
). It can be used byside_effect
functions to indicate that the normal return value should be used.
call¶
- unittest.mock.call(*args,**kwargs)¶
call()
is a helper object for making simpler assertions, for comparing withcall_args
,call_args_list
,mock_calls
andmethod_calls
.call()
can also beused withassert_has_calls()
.>>>m=MagicMock(return_value=None)>>>m(1,2,a='foo',b='bar')>>>m()>>>m.call_args_list==[call(1,2,a='foo',b='bar'),call()]True
- call.call_list()¶
For a call object that represents multiple calls,
call_list()
returns a list of all the intermediate calls as well as thefinal call.
call_list
is particularly useful for making assertions on “chained calls”. Achained call is multiple calls on a single line of code. This results inmultiple entries inmock_calls
on a mock. Manually constructingthe sequence of calls can be tedious.
call_list()
can construct the sequence of calls from the samechained call:
>>>m=MagicMock()>>>m(1).method(arg='foo').other('bar')(2.0)<MagicMock name='mock().method().other()()' id='...'>>>>kall=call(1).method(arg='foo').other('bar')(2.0)>>>kall.call_list()[call(1), call().method(arg='foo'), call().method().other('bar'), call().method().other()(2.0)]>>>m.mock_calls==kall.call_list()True
Acall
object is either a tuple of (positional args, keyword args) or(name, positional args, keyword args) depending on how it was constructed. Whenyou construct them yourself this isn’t particularly interesting, but thecall
objects that are in theMock.call_args
,Mock.call_args_list
andMock.mock_calls
attributes can be introspected to get at the individualarguments they contain.
Thecall
objects inMock.call_args
andMock.call_args_list
are two-tuples of (positional args, keyword args) whereas thecall
objectsinMock.mock_calls
, along with ones you construct yourself, arethree-tuples of (name, positional args, keyword args).
You can use their “tupleness” to pull out the individual arguments for morecomplex introspection and assertions. The positional arguments are a tuple(an empty tuple if there are no positional arguments) and the keywordarguments are a dictionary:
>>>m=MagicMock(return_value=None)>>>m(1,2,3,arg='one',arg2='two')>>>kall=m.call_args>>>kall.args(1, 2, 3)>>>kall.kwargs{'arg': 'one', 'arg2': 'two'}>>>kall.argsiskall[0]True>>>kall.kwargsiskall[1]True
>>>m=MagicMock()>>>m.foo(4,5,6,arg='two',arg2='three')<MagicMock name='mock.foo()' id='...'>>>>kall=m.mock_calls[0]>>>name,args,kwargs=kall>>>name'foo'>>>args(4, 5, 6)>>>kwargs{'arg': 'two', 'arg2': 'three'}>>>nameism.mock_calls[0][0]True
create_autospec¶
- unittest.mock.create_autospec(spec,spec_set=False,instance=False,**kwargs)¶
Create a mock object using another object as a spec. Attributes on themock will use the corresponding attribute on thespec object as theirspec.
Functions or methods being mocked will have their arguments checked toensure that they are called with the correct signature.
Ifspec_set is
True
then attempting to set attributes that don’t existon the spec object will raise anAttributeError
.If a class is used as a spec then the return value of the mock (theinstance of the class) will have the same spec. You can use a class as thespec for an instance object by passing
instance=True
. The returned mockwill only be callable if instances of the mock are callable.create_autospec()
also takes arbitrary keyword arguments that are passed tothe constructor of the created mock.
SeeAutospeccing for examples of how to use auto-speccing withcreate_autospec()
and theautospec argument topatch()
.
Changed in version 3.8:create_autospec()
now returns anAsyncMock
if the target isan async function.
ANY¶
- unittest.mock.ANY¶
Sometimes you may need to make assertions aboutsome of the arguments in acall to mock, but either not care about some of the arguments or want to pullthem individually out ofcall_args
and make more complexassertions on them.
To ignore certain arguments you can pass in objects that compare equal toeverything. Calls toassert_called_with()
andassert_called_once_with()
will then succeed no matter what waspassed in.
>>>mock=Mock(return_value=None)>>>mock('foo',bar=object())>>>mock.assert_called_once_with('foo',bar=ANY)
ANY
can also be used in comparisons with call lists likemock_calls
:
>>>m=MagicMock(return_value=None)>>>m(1)>>>m(1,2)>>>m(object())>>>m.mock_calls==[call(1),call(1,2),ANY]True
ANY
is not limited to comparisons with call objects and socan also be used in test assertions:
classTestStringMethods(unittest.TestCase):deftest_split(self):s='hello world'self.assertEqual(s.split(),['hello',ANY])
FILTER_DIR¶
- unittest.mock.FILTER_DIR¶
FILTER_DIR
is a module level variable that controls the way mock objectsrespond todir()
. The default isTrue
,which uses the filtering described below, to only show useful members. If youdislike this filtering, or need to switch it off for diagnostic purposes, thensetmock.FILTER_DIR=False
.
With filtering on,dir(some_mock)
shows only useful attributes and willinclude any dynamically created attributes that wouldn’t normally be shown.If the mock was created with aspec (orautospec of course) then all theattributes from the original are shown, even if they haven’t been accessedyet:
>>>dir(Mock())['assert_any_call', 'assert_called', 'assert_called_once', 'assert_called_once_with', 'assert_called_with', 'assert_has_calls', 'assert_not_called', 'attach_mock', ...>>>fromurllibimportrequest>>>dir(Mock(spec=request))['AbstractBasicAuthHandler', 'AbstractDigestAuthHandler', 'AbstractHTTPHandler', 'BaseHandler', ...
Many of the not-very-useful (private toMock
rather than the thing beingmocked) underscore and double underscore prefixed attributes have beenfiltered from the result of callingdir()
on aMock
. If you dislike thisbehaviour you can switch it off by setting the module level switchFILTER_DIR
:
>>>fromunittestimportmock>>>mock.FILTER_DIR=False>>>dir(mock.Mock())['_NonCallableMock__get_return_value', '_NonCallableMock__get_side_effect', '_NonCallableMock__return_value_doc', '_NonCallableMock__set_return_value', '_NonCallableMock__set_side_effect', '__call__', '__class__', ...
Alternatively you can just usevars(my_mock)
(instance members) anddir(type(my_mock))
(type members) to bypass the filtering irrespective ofFILTER_DIR
.
mock_open¶
- unittest.mock.mock_open(mock=None,read_data=None)¶
A helper function to create a mock to replace the use of
open()
. It worksforopen()
called directly or used as a context manager.Themock argument is the mock object to configure. If
None
(thedefault) then aMagicMock
will be created for you, with the API limitedto methods or attributes available on standard file handles.read_data is a string for the
read()
,readline()
, andreadlines()
methodsof the file handle to return. Calls to those methods will take data fromread_data until it is depleted. The mock of these methods is prettysimplistic: every time themock is called, theread_data is rewound tothe start. If you need more control over the data that you are feeding tothe tested code you will need to customize this mock for yourself. When thatis insufficient, one of the in-memory filesystem packages onPyPI can offer a realistic filesystem for testing.Changed in version 3.4:Added
readline()
andreadlines()
support.The mock ofread()
changed to consumeread_data ratherthan returning it on each call.Changed in version 3.5:read_data is now reset on each call to themock.
Changed in version 3.8:Added
__iter__()
to implementation so that iteration(such as in for loops) correctly consumesread_data.
Usingopen()
as a context manager is a great way to ensure your file handlesare closed properly and is becoming common:
withopen('/some/path','w')asf:f.write('something')
The issue is that even if you mock out the call toopen()
it is thereturned object that is used as a context manager (and has__enter__()
and__exit__()
called).
Mocking context managers with aMagicMock
is common enough and fiddlyenough that a helper function is useful.
>>>m=mock_open()>>>withpatch('__main__.open',m):...withopen('foo','w')ash:...h.write('some stuff')...>>>m.mock_calls[call('foo', 'w'), call().__enter__(), call().write('some stuff'), call().__exit__(None, None, None)]>>>m.assert_called_once_with('foo','w')>>>handle=m()>>>handle.write.assert_called_once_with('some stuff')
And for reading files:
>>>withpatch('__main__.open',mock_open(read_data='bibble'))asm:...withopen('foo')ash:...result=h.read()...>>>m.assert_called_once_with('foo')>>>assertresult=='bibble'
Autospeccing¶
Autospeccing is based on the existingspec
feature of mock. It limits theapi of mocks to the api of an original object (the spec), but it is recursive(implemented lazily) so that attributes of mocks only have the same api asthe attributes of the spec. In addition mocked functions / methods have thesame call signature as the original so they raise aTypeError
if they arecalled incorrectly.
Before I explain how auto-speccing works, here’s why it is needed.
Mock
is a very powerful and flexible object, but it suffers from a flaw whichis general to mocking. If you refactor some of your code, rename members and so on, anytests for code that is still using theold api but uses mocks instead of the realobjects will still pass. This means your tests can all pass even though your code isbroken.
Changed in version 3.5:Before 3.5, tests with a typo in the word assert would silently pass when they shouldraise an error. You can still achieve this behavior by passingunsafe=True
to Mock.
Note that this is another reason why you need integration tests as well asunit tests. Testing everything in isolation is all fine and dandy, but if youdon’t test how your units are “wired together” there is still lots of roomfor bugs that tests might have caught.
unittest.mock
already provides a feature to help with this, called speccing. If youuse a class or instance as thespec
for a mock then you can only accessattributes on the mock that exist on the real class:
>>>fromurllibimportrequest>>>mock=Mock(spec=request.Request)>>>mock.assret_called_with# Intentional typo!Traceback (most recent call last):...AttributeError:Mock object has no attribute 'assret_called_with'
The spec only applies to the mock itself, so we still have the same issuewith any methods on the mock:
>>>mock.header_items()<mock.Mock object at 0x...>>>>mock.header_items.assret_called_with()# Intentional typo!
Auto-speccing solves this problem. You can either passautospec=True
topatch()
/patch.object()
or use thecreate_autospec()
function to create amock with a spec. If you use theautospec=True
argument topatch()
then theobject that is being replaced will be used as the spec object. Because thespeccing is done “lazily” (the spec is created as attributes on the mock areaccessed) you can use it with very complex or deeply nested objects (likemodules that import modules that import modules) without a big performancehit.
Here’s an example of it in use:
>>>fromurllibimportrequest>>>patcher=patch('__main__.request',autospec=True)>>>mock_request=patcher.start()>>>requestismock_requestTrue>>>mock_request.Request<MagicMock name='request.Request' spec='Request' id='...'>
You can see thatrequest.Request
has a spec.request.Request
takes twoarguments in the constructor (one of which isself). Here’s what happens ifwe try to call it incorrectly:
>>>req=request.Request()Traceback (most recent call last):...TypeError:<lambda>() takes at least 2 arguments (1 given)
The spec also applies to instantiated classes (i.e. the return value ofspecced mocks):
>>>req=request.Request('foo')>>>req<NonCallableMagicMock name='request.Request()' spec='Request' id='...'>
Request
objects are not callable, so the return value of instantiating ourmocked outrequest.Request
is a non-callable mock. With the spec in placeany typos in our asserts will raise the correct error:
>>>req.add_header('spam','eggs')<MagicMock name='request.Request().add_header()' id='...'>>>>req.add_header.assret_called_with# Intentional typo!Traceback (most recent call last):...AttributeError:Mock object has no attribute 'assret_called_with'>>>req.add_header.assert_called_with('spam','eggs')
In many cases you will just be able to addautospec=True
to your existingpatch()
calls and then be protected against bugs due to typos and apichanges.
As well as usingautospec throughpatch()
there is acreate_autospec()
for creating autospecced mocks directly:
>>>fromurllibimportrequest>>>mock_request=create_autospec(request)>>>mock_request.Request('foo','bar')<NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>
This isn’t without caveats and limitations however, which is why it is notthe default behaviour. In order to know what attributes are available on thespec object, autospec has to introspect (access attributes) the spec. As youtraverse attributes on the mock a corresponding traversal of the originalobject is happening under the hood. If any of your specced objects haveproperties or descriptors that can trigger code execution then you may not beable to use autospec. On the other hand it is much better to design yourobjects so that introspection is safe[4].
A more serious problem is that it is common for instance attributes to becreated in the__init__()
method and not to exist on the class at all.autospec can’t know about any dynamically created attributes and restrictsthe api to visible attributes.
>>>classSomething:...def__init__(self):...self.a=33...>>>withpatch('__main__.Something',autospec=True):...thing=Something()...thing.a...Traceback (most recent call last):...AttributeError:Mock object has no attribute 'a'
There are a few different ways of resolving this problem. The easiest, butnot necessarily the least annoying, way is to simply set the requiredattributes on the mock after creation. Just becauseautospec doesn’t allowyou to fetch attributes that don’t exist on the spec it doesn’t prevent yousetting them:
>>>withpatch('__main__.Something',autospec=True):...thing=Something()...thing.a=33...
There is a more aggressive version of bothspec andautospec thatdoesprevent you setting non-existent attributes. This is useful if you want toensure your code onlysets valid attributes too, but obviously it preventsthis particular scenario:
>>>withpatch('__main__.Something',autospec=True,spec_set=True):...thing=Something()...thing.a=33...Traceback (most recent call last):...AttributeError:Mock object has no attribute 'a'
Probably the best way of solving the problem is to add class attributes asdefault values for instance members initialised in__init__()
.Note that ifyou are only setting default attributes in__init__()
then providing them viaclass attributes (shared between instances of course) is faster too. e.g.
classSomething:a=33
This brings up another issue. It is relatively common to provide a defaultvalue ofNone
for members that will later be an object of a different type.None
would be useless as a spec because it wouldn’t let you accessanyattributes or methods on it. AsNone
isnever going to be useful as aspec, and probably indicates a member that will normally of some other type,autospec doesn’t use a spec for members that are set toNone
. These willjust be ordinary mocks (well - MagicMocks):
>>>classSomething:...member=None...>>>mock=create_autospec(Something)>>>mock.member.foo.bar.baz()<MagicMock name='mock.member.foo.bar.baz()' id='...'>
If modifying your production classes to add defaults isn’t to your likingthen there are more options. One of these is simply to use an instance as thespec rather than the class. The other is to create a subclass of theproduction class and add the defaults to the subclass without affecting theproduction class. Both of these require you to use an alternative object asthe spec. Thankfullypatch()
supports this - you can simply pass thealternative object as theautospec argument:
>>>classSomething:...def__init__(self):...self.a=33...>>>classSomethingForTest(Something):...a=33...>>>p=patch('__main__.Something',autospec=SomethingForTest)>>>mock=p.start()>>>mock.a<NonCallableMagicMock name='Something.a' spec='int' id='...'>
This only applies to classes or already instantiated objects. Callinga mocked class to create a mock instancedoes not create a real instance.It is only attribute lookups - along with calls todir()
- that are done.
Sealing mocks¶
- unittest.mock.seal(mock)¶
Seal will disable the automatic creation of mocks when accessing an attribute ofthe mock being sealed or any of its attributes that are already mocks recursively.
If a mock instance with a name or a spec is assigned to an attributeit won’t be considered in the sealing chain. This allows one to prevent seal fromfixing part of the mock object.
>>>mock=Mock()>>>mock.submock.attribute1=2>>>mock.not_submock=mock.Mock(name="sample_name")>>>seal(mock)>>>mock.new_attribute# This will raise AttributeError.>>>mock.submock.attribute2# This will raise AttributeError.>>>mock.not_submock.attribute2# This won't raise.
Added in version 3.7.
Order of precedence ofside_effect
,return_value
andwraps¶
The order of their precedence is:
If all three are set, mock will return the value fromside_effect
,ignoringreturn_value
and the wrapped object altogether. If anytwo are set, the one with the higher precedence will return the value.Regardless of the order of which was set first, the order of precedenceremains unchanged.
>>>fromunittest.mockimportMock>>>classOrder:...@staticmethod...defget_value():...return"third"...>>>order_mock=Mock(spec=Order,wraps=Order)>>>order_mock.get_value.side_effect=["first"]>>>order_mock.get_value.return_value="second">>>order_mock.get_value()'first'
AsNone
is the default value ofside_effect
, if you reassignits value back toNone
, the order of precedence will be checked betweenreturn_value
and the wrapped object, ignoringside_effect
.
>>>order_mock.get_value.side_effect=None>>>order_mock.get_value()'second'
If the value being returned byside_effect
isDEFAULT
,it is ignored and the order of precedence moves to the successor to obtain thevalue to return.
>>>fromunittest.mockimportDEFAULT>>>order_mock.get_value.side_effect=[DEFAULT]>>>order_mock.get_value()'second'
WhenMock
wraps an object, the default value ofreturn_value
will beDEFAULT
.
>>>order_mock=Mock(spec=Order,wraps=Order)>>>order_mock.return_valuesentinel.DEFAULT>>>order_mock.get_value.return_valuesentinel.DEFAULT
The order of precedence will ignore this value and it will move to the lastsuccessor which is the wrapped object.
As the real call is being made to the wrapped object, creating an instance ofthis mock will return the real instance of the class. The positional arguments,if any, required by the wrapped object must be passed.
>>>order_mock_instance=order_mock()>>>isinstance(order_mock_instance,Order)True>>>order_mock_instance.get_value()'third'
>>>order_mock.get_value.return_value=DEFAULT>>>order_mock.get_value()'third'
>>>order_mock.get_value.return_value="second">>>order_mock.get_value()'second'
But if you assignNone
to it, this will not be ignored as it is anexplicit assignment. So, the order of precedence will not move to the wrappedobject.
>>>order_mock.get_value.return_value=None>>>order_mock.get_value()isNoneTrue
Even if you set all three at once when initializing the mock, the order ofprecedence remains the same:
>>>order_mock=Mock(spec=Order,wraps=Order,...**{"get_value.side_effect":["first"],..."get_value.return_value":"second"}...)...>>>order_mock.get_value()'first'>>>order_mock.get_value.side_effect=None>>>order_mock.get_value()'second'>>>order_mock.get_value.return_value=DEFAULT>>>order_mock.get_value()'third'
Ifside_effect
is exhausted, the order of precedence will notcause a value to be obtained from the successors. Instead,StopIteration
exception is raised.
>>>order_mock=Mock(spec=Order,wraps=Order)>>>order_mock.get_value.side_effect=["first side effect value",..."another side effect value"]>>>order_mock.get_value.return_value="second"
>>>order_mock.get_value()'first side effect value'>>>order_mock.get_value()'another side effect value'
>>>order_mock.get_value()Traceback (most recent call last):...StopIteration