Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Spy exceptions #173

Merged
merged 6 commits into from
Dec 6, 2019
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
1.13.0
------

* The object returned by ``mocker.spy`` now also tracks any side effect
of the spied method/function.

1.12.1 (2019-11-20)
-------------------

Expand Down
3 changes: 3 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,9 @@ features with it, like retrieving call count. It also works for class and static
Since version ``1.11``, it is also possible to query the ``return_value`` attribute
to observe what the spied function/method returned.

Since version ``1.13``, it is also possible to query the ``side_effect`` attribute
to observe any exception thrown by the spied function/method.

Stub
----

Expand Down
9 changes: 7 additions & 2 deletions src/pytest_mock/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,13 @@ def spy(self, obj, name):

@w
def wrapper(*args, **kwargs):
r = method(*args, **kwargs)
result.return_value = r
try:
r = method(*args, **kwargs)
except Exception as e:
result.side_effect = e
raise
else:
result.return_value = r
return r

result = self.patch.object(obj, name, side_effect=wrapper, autospec=autospec)
Expand Down
19 changes: 19 additions & 0 deletions tests/test_pytest_mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,25 @@ def bar(self, arg):
assert spy.return_value == 20


def test_instance_method_spy_exception(mocker):
excepted_message = "foo"

class Foo(object):
def bar(self, arg):
raise Exception(excepted_message)

foo = Foo()
other = Foo()
spy = mocker.spy(foo, "bar")

with pytest.raises(Exception) as exc_info:
foo.bar(10)
assert str(exc_info.value) == excepted_message

foo.bar.assert_called_once_with(arg=10)
assert spy.side_effect == exc_info.value


@skip_pypy
def test_instance_method_by_class_spy(mocker):
class Foo(object):
Expand Down