# This happens most often in testing. We would like to make sure that # a block of code raises an exception of the certain type. # If it does not raise an exception, *we* raise an error. # If it raises an unexpected exception, we raise an error *too*. # Write a context manager which does checks that an exception is # raised properly and convert the example below. Make things # less ugly too. import math import contextlib def log_of_sqrt(n): return math.log(math.sqrt(n)) @contextlib.contextmanager def assert_raises(exception_type): try: yield except exception_type: pass except Exception as e: raise ValueError('unexpected exception ' + e.__class__.__name__) else: raise ValueError('no expected exception') def test_sqrt(): with assert_raises(ValueError): log_of_sqrt(1/0) # Note: this is implemented by # pytest.raises, # unittest.TestCase.assertRaises.