# 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 def log_of_sqrt(n): return math.log(math.sqrt(n)) def assert_raises(exception_type): ... def test_sqrt(): try: log_of_sqrt(-5) except Exception as e: if isinstance(e, ValueError): # what is Pythonic way # to check exception type? pass else: raise AssertionError('bad exception') finally: raise AssertionError('no expected exception') # Note: this is implemented by # pytest.raises, # unittest.TestCase.assertRaises.