Skip to content

Commit

Permalink
Merge pull request #65 from sgissinger/master
Browse files Browse the repository at this point in the history
fixes #54 add message redirection to exceptions
  • Loading branch information
h2non committed Nov 21, 2020
2 parents b2c14fc + 449b71e commit 02a0eed
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 5 deletions.
13 changes: 8 additions & 5 deletions grappa/operators/raises.py
Expand Up @@ -55,6 +55,14 @@ def fn():
'an object of type "{type}" with reference "{value}"',
)

def after_success(self, obj, *keys):
message = getattr(self.value, 'message', None)

if not message:
message = ' '.join([str(item) for item in self.value.args])

self.ctx.subject = message

def match(self, fn, *errors):
if not callable(fn):
return False, ['subject must be a function or method']
Expand All @@ -64,11 +72,6 @@ def match(self, fn, *errors):
except Exception as err:
self.value = err

# If no errors present, just raise the exception
if not errors:
return True, []

# Otherwise match errors
return isinstance(err, *errors), ['invalid raised exception']
else:
return False, ['did not raise any exception']
48 changes: 48 additions & 0 deletions tests/operators/raises_test.py
Expand Up @@ -3,12 +3,16 @@


def test_raises(should):
def no_error():
pass

def error():
raise AssertionError('foo')

def error_with_params(foo_param):
raise AssertionError(foo_param)

error | should.raise_error(Exception)
error | should.raise_error(AssertionError)
error | should.do_not.raise_error(NotImplementedError)

Expand All @@ -24,3 +28,47 @@ def error_with_params(foo_param):

with pytest.raises(AssertionError):
None | should.raise_error(AssertionError)

with pytest.raises(AssertionError):
no_error | should.raise_error(AssertionError)


def test_raises_with_message_redirection(should):
def error():
raise AssertionError('foo')

def env_error():
raise EnvironmentError(3501, 'bar')

error | should.raise_error(AssertionError) > should.equal('foo')

error | should.raise_error(AssertionError) > should.contain('fo')

error | should.do_not.raise_error(NotImplementedError) \
> should.equal('foo')

env_error | should.raise_error(EnvironmentError) > should.contain('bar')

env_error | should.raise_error(EnvironmentError) > should.equal('3501 bar')

with pytest.raises(AssertionError):
error | should.raise_error(AssertionError) > should.equal('fooe')

with pytest.raises(AssertionError):
error | should.raise_error(NotImplementedError) > should.equal('foo')


def test_raises_custom_exception_message_redirection(should):
class CustomException(Exception):
message = 'foo'

def __init__(self, *args):
super(CustomException, self).__init__(self.message, *args)

def custom_error():
raise CustomException('bar')

custom_error | should.raise_error(CustomException) > should.equal('foo')

custom_error | should.raise_error(CustomException) \
> should.do_not.equal('foo bar')

0 comments on commit 02a0eed

Please sign in to comment.