@@ -120,11 +120,11 @@ Spy
120
120
---
121
121
122
122
The ``mocker.spy `` object acts exactly like the original method in all cases, except the spy
123
- also tracks method calls, return values and exceptions raised.
123
+ also tracks function/ method calls, return values and exceptions raised.
124
124
125
125
.. code-block :: python
126
126
127
- def test_spy (mocker ):
127
+ def test_spy_method (mocker ):
128
128
class Foo (object ):
129
129
def bar (self , v ):
130
130
return v * 2
@@ -136,16 +136,25 @@ also tracks method calls, return values and exceptions raised.
136
136
spy.assert_called_once_with(21 )
137
137
assert spy.spy_return == 42
138
138
139
+ def test_spy_function (mocker ):
140
+ # mymodule declares `myfunction` which just returns 42
141
+ import mymodule
142
+
143
+ spy = mocker.spy(mymodule, " myfunction" )
144
+ assert mymodule.myfunction() == 42
145
+ assert spy.call_count == 1
146
+ assert spy.spy_return == 42
147
+
139
148
The object returned by ``mocker.spy `` is a ``MagicMock `` object, so all standard checking functions
140
- are available (like ``assert_called_once_with `` in the example above).
149
+ are available (like ``assert_called_once_with `` or `` call_count `` in the examples above).
141
150
142
151
In addition, spy objects contain two extra attributes:
143
152
144
153
* ``spy_return ``: contains the returned value of the spied function.
145
154
* ``spy_exception ``: contain the last exception value raised by the spied function/method when
146
155
it was last called, or ``None `` if no exception was raised.
147
156
148
- ``mocker.spy `` also works for class and static methods.
157
+ Besides functions and normal methods, ``mocker.spy `` also works for class and static methods.
149
158
150
159
As of version 3.0.0, ``mocker.spy `` also works with ``async def `` functions.
151
160
0 commit comments