Skip to content

Commit

Permalink
Merge d06bace into 10fb2ca
Browse files Browse the repository at this point in the history
  • Loading branch information
dnathe4th committed Mar 7, 2016
2 parents 10fb2ca + d06bace commit bf592a2
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 3 deletions.
19 changes: 19 additions & 0 deletions docs/source/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,25 @@ Both stubs and mocks allow a method call to raise an exception instead of return
else:
raise AssertionError('Expected test to raise StandardError.')

If the exception to be raised requires arguments, they can be passed to ``and_raises`` directly::

from doubles import allow

from myapp import User


def test_raising_an_exception():
user = User('Carl')

allow(user).get_name.and_raise(NonStandardError, 'an argument', arg2='another arg')

try:
user.get_name()
except NonStandardError:
pass
else:
raise AssertionError('Expected test to raise NonStandardError.')

Call counts
-----------

Expand Down
9 changes: 6 additions & 3 deletions doubles/allowance.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,16 @@ def __init__(self, target, method_name, caller):

self._return_value = lambda *args, **kwargs: None

def and_raise(self, exception):
def and_raise(self, exception, *args, **kwargs):
"""Causes the double to raise the provided exception when called.
If provided, additional arguments (positional and keyword) passed to
`and_raise` are used in the exception instantiation.
:param Exception exception: The exception to raise.
"""
def proxy_exception(*args, **kwargs):
raise exception
def proxy_exception(*proxy_args, **proxy_kwargs):
raise exception(*args, **kwargs)

self._return_value = proxy_exception
return self
Expand Down
14 changes: 14 additions & 0 deletions test/return_values_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ class UserDefinedException(Exception):
pass


class UserDefinedExceptionWithArgs(Exception):
def __init__(self, msg, arg1, arg2=None):
pass


@mark.parametrize('stubber', [allow, expect])
class TestReturnValues(object):
def test_returns_result_of_a_callable(self, stubber):
Expand Down Expand Up @@ -48,6 +53,15 @@ def test_raises_provided_exception(self, stubber):
with raises(UserDefinedException):
subject.instance_method()

def test_raises_provided_exception_with_complex_signature(self, stubber):
subject = InstanceDouble('doubles.testing.User')

stubber(subject).instance_method.and_raise(
UserDefinedExceptionWithArgs, 'msg', 'arg1', arg2='arg2')

with raises(UserDefinedExceptionWithArgs):
subject.instance_method()

def test_chaining_result_methods_gives_the_last_one_precedence(self, stubber):
subject = InstanceDouble('doubles.testing.User')

Expand Down

0 comments on commit bf592a2

Please sign in to comment.