Skip to content

Commit

Permalink
add assertDoesNotRaise contextmanager (pantsbuild#9113)
Browse files Browse the repository at this point in the history
### Problem

It would be nice to be explicit about the intent when we're trying to make sure something ran without an exception and we *really, really* don't care about, or don't have any meaningful return value.

### Solution

- Add a `self.assertDoesNotRaise()` contextmanager.
  • Loading branch information
cosmicexplorer authored Feb 15, 2020
1 parent 064a74a commit b14b7f5
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 9 deletions.
11 changes: 11 additions & 0 deletions src/python/pants/testutil/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -675,6 +675,17 @@ def assertRaisesWithMessageContaining(self, exception_type, error_text):
yield cm
self.assertIn(error_text, str(cm.exception))

@contextmanager
def assertDoesNotRaise(self, exc_class: Type[BaseException] = Exception):
"""Verifies that the block does not raise an exception of the specified type.
:API: public
"""
try:
yield
except exc_class as e:
raise AssertionError(f'section should not have raised, but did: {e}') from e

def get_bootstrap_options(self, cli_options=()):
"""Retrieves bootstrap options.
Expand Down
15 changes: 6 additions & 9 deletions tests/python/pants_test/engine/test_scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,22 +221,19 @@ def test_transitive_params(self):

# Test that an inner Get in transitive_coroutine_rule() is able to resolve B from C due to the
# existence of transitive_b_c().
result_d = self.request_single_product(D, Params(c))
# We don't need the inner B objects to be the same, and we know the arguments are type-checked,
# we're just testing transitively resolving products in this file.
self.assertTrue(isinstance(result_d, D))
with self.assertDoesNotRaise():
_ = self.request_single_product(D, Params(c))

@contextmanager
def _assert_execution_error(self, expected_msg):
with assert_execution_error(self, expected_msg):
yield

def test_union_rules(self):
a = self.request_single_product(A, Params(UnionWrapper(UnionA())))
# TODO: figure out what to assert here!
self.assertTrue(isinstance(a, A))
a = self.request_single_product(A, Params(UnionWrapper(UnionB())))
self.assertTrue(isinstance(a, A))
with self.assertDoesNotRaise():
_ = self.request_single_product(A, Params(UnionWrapper(UnionA())))
with self.assertDoesNotRaise():
_ = self.request_single_product(A, Params(UnionWrapper(UnionB())))
# Fails due to no union relationship from A -> UnionBase.
with self._assert_execution_error("Type A is not a member of the UnionBase @union"):
self.request_single_product(A, Params(UnionWrapper(A())))
Expand Down

0 comments on commit b14b7f5

Please sign in to comment.