I want to add a custom assert method to a subclass of TestCase . I tried to copy my implementation from the unittest module unittest that it would match the behavior of the regular TestCase as much as possible. (I would rather just delegate self.assertEqual() , but this causes even more upstream noise, see below.) The unittest module seems to automatically hide some of the internal details of its implementation when reporting failed statements.
import unittest class MyTestCase(unittest.TestCase): def assertLengthIsOne(self, sequence, msg=None): if len(sequence) != 1: msg = self._formatMessage(msg, "length is not one") raise self.failureException(msg) class TestFoo(MyTestCase): seq = (1, 2, 3, 4, 5) def test_stock_unittest_assertion(self): self.assertEqual(len(self.seq), 1) def test_custom_assertion(self): self.assertLengthIsOne(self.seq) unittest.main()
The result of this as such:
amoe@vuurvlieg $ python unittest-demo.py FF ====================================================================== FAIL: test_custom_assertion (__main__.TestFoo) ---------------------------------------------------------------------- Traceback (most recent call last): File "unittest-demo.py", line 16, in test_custom_assertion self.assertLengthIsOne(self.seq) File "unittest-demo.py", line 7, in assertLengthIsOne raise self.failureException(msg) AssertionError: length is not one ====================================================================== FAIL: test_stock_unittest_assertion (__main__.TestFoo) ---------------------------------------------------------------------- Traceback (most recent call last): File "unittest-demo.py", line 13, in test_stock_unittest_assertion self.assertEqual(len(self.seq), 1) AssertionError: 5 != 1 ---------------------------------------------------------------------- Ran 2 tests in 0.000s FAILED (failures=2)
Note that the custom assert method invokes a stack trace with two frames, one inside the method itself, while the unittest stock unittest has only one frame, the corresponding line in the user code. How can I apply this behavior when hiding frames to my own method?
python stack-trace unit-testing testing subclass
amoe
source share