Skip to content

Instantly share code, notes, and snippets.

@rene-armida
Last active December 11, 2015 03:58
Show Gist options
  • Save rene-armida/4541594 to your computer and use it in GitHub Desktop.
Save rene-armida/4541594 to your computer and use it in GitHub Desktop.
Example of asserting properties of an exception caught by assertRaises / assert_raises. Run with `python -m unittest2 -v exception_attrs` from the same dir as the file.
import unittest2
# some code under test
def raise_msg(x):
raise ValueError('hello: %s' % x)
class SomeError(ValueError):
def __init__(self, x):
self.x = x
def raise_attr(x):
raise SomeError(x)
# two methods of asserting properties of an exception
class ExampleTest(unittest2.TestCase):
def test_assert_message(self):
with self.assertRaises(ValueError) as cm:
raise_msg(42)
# passing assertion
self.assertEqual('hello: 42', cm.exception.args[0])
# failing assertion
self.assertEqual('hello: 43', cm.exception.args[0])
def test_assert_attr(self):
with self.assertRaises(ValueError) as cm:
raise_attr(42)
# passing assertion
self.assertEqual(cm.exception.x, 42)
# failing assertion
self.assertEqual(cm.exception.x, 43)
(venv)marmida@monolith:~/develop/example-exception-cm$ python -m unittest2 -v fixture1
test_assert_attr (fixture1.ExampleTest) ... FAIL
test_assert_message (fixture1.ExampleTest) ... FAIL
======================================================================
FAIL: test_assert_attr (fixture1.ExampleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "fixture1.py", line 31, in test_assert_attr
self.assertEqual(cm.exception.x, 43)
AssertionError: 42 != 43
======================================================================
FAIL: test_assert_message (fixture1.ExampleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "fixture1.py", line 23, in test_assert_message
self.assertEqual('hello: 43', cm.exception.args[0])
AssertionError: 'hello: 43' != 'hello: 42'
----------------------------------------------------------------------
Ran 2 tests in 0.001s
FAILED (failures=2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment