Skip to content

Commit 7bddcd5

Browse files
authored
Merge pull request #173 from inderpreet99/spy-exceptions
Spy exceptions
2 parents 2655441 + 895efb1 commit 7bddcd5

File tree

4 files changed

+35
-2
lines changed

4 files changed

+35
-2
lines changed

CHANGELOG.rst

+6
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
1.13.0 (2019-12-05)
2+
-------------------
3+
4+
* The object returned by ``mocker.spy`` now also tracks any side effect
5+
of the spied method/function.
6+
17
1.12.1 (2019-11-20)
28
-------------------
39

README.rst

+3
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,9 @@ features with it, like retrieving call count. It also works for class and static
103103
Since version ``1.11``, it is also possible to query the ``return_value`` attribute
104104
to observe what the spied function/method returned.
105105

106+
Since version ``1.13``, it is also possible to query the ``side_effect`` attribute
107+
to observe any exception thrown by the spied function/method.
108+
106109
Stub
107110
----
108111

src/pytest_mock/plugin.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -113,8 +113,13 @@ def spy(self, obj, name):
113113

114114
@w
115115
def wrapper(*args, **kwargs):
116-
r = method(*args, **kwargs)
117-
result.return_value = r
116+
try:
117+
r = method(*args, **kwargs)
118+
except Exception as e:
119+
result.side_effect = e
120+
raise
121+
else:
122+
result.return_value = r
118123
return r
119124

120125
result = self.patch.object(obj, name, side_effect=wrapper, autospec=autospec)

tests/test_pytest_mock.py

+19
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,25 @@ def bar(self, arg):
243243
assert spy.return_value == 20
244244

245245

246+
def test_instance_method_spy_exception(mocker):
247+
excepted_message = "foo"
248+
249+
class Foo(object):
250+
def bar(self, arg):
251+
raise Exception(excepted_message)
252+
253+
foo = Foo()
254+
other = Foo()
255+
spy = mocker.spy(foo, "bar")
256+
257+
with pytest.raises(Exception) as exc_info:
258+
foo.bar(10)
259+
assert str(exc_info.value) == excepted_message
260+
261+
foo.bar.assert_called_once_with(arg=10)
262+
assert spy.side_effect == exc_info.value
263+
264+
246265
@skip_pypy
247266
def test_instance_method_by_class_spy(mocker):
248267
class Foo(object):

0 commit comments

Comments
 (0)