Skip to content

Commit

Permalink
fixes assertpy#92 - make soft_assertions() context manager reentrant
Browse files Browse the repository at this point in the history
  • Loading branch information
saturnboy committed Aug 1, 2019
1 parent 5ebbf63 commit bc70d53
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
11 changes: 6 additions & 5 deletions assertpy/assertpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@


### soft assertions ###
_soft_ctx = False
_soft_ctx = 0
_soft_err = []

@contextlib.contextmanager
Expand All @@ -67,16 +67,17 @@ def soft_assertions():
global _soft_err

# init ctx
_soft_ctx = True
_soft_err = []
if _soft_ctx == 0:
_soft_err = []
_soft_ctx += 1

try:
yield
finally:
# reset ctx
_soft_ctx = False
_soft_ctx -= 1

if _soft_err:
if _soft_err and _soft_ctx == 0:
out = 'soft assertion failures:'
for i,msg in enumerate(_soft_err):
out += '\n%d. %s' % (i+1, msg)
Expand Down
18 changes: 18 additions & 0 deletions tests/test_soft.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,3 +159,21 @@ def test_double_fail():
out = str(e)
assert_that(out).is_equal_to('Fail!')

def test_nested():
try:
with soft_assertions():
assert_that('a').is_equal_to('A')
with soft_assertions():
assert_that('b').is_equal_to('B')
with soft_assertions():
assert_that('c').is_equal_to('C')
assert_that('b').is_equal_to('B2')
assert_that('a').is_equal_to('A2')
fail('should have raised error')
except AssertionError as e:
out = str(e)
assert_that(out).contains('1. Expected <a> to be equal to <A>, but was not.')
assert_that(out).contains('2. Expected <b> to be equal to <B>, but was not.')
assert_that(out).contains('3. Expected <c> to be equal to <C>, but was not.')
assert_that(out).contains('4. Expected <b> to be equal to <B2>, but was not.')
assert_that(out).contains('5. Expected <a> to be equal to <A2>, but was not.')

0 comments on commit bc70d53

Please sign in to comment.