Reputation: 15
assert
doesn't raise an exception when called in an instance of a class:
class TestCaseTest(TestCase):
...
def testFailedResutFormatted(self):
...
assert False # This doesn't work at all
TestCaseTest("testFailedResutFormatted").run()
assert False # But this works just fine
Full code can be seen here: http://pastebin.com/Hc9CTTxH
I am obviously doing something wrong, because these are examples from the book and they should work. I just can't figure out what is the matter.
Upvotes: 0
Views: 309
Reputation: 1124718
The assert False
works just fine, but the AssertionError
is caught by the TestCase.run()
method, to be collected later.
You didn't pass in a TestResult
instance, so in Python 3 the TestCase.run()
function returns a new result object for you:
>>> from unittest import TestCase
>>> class TestCaseTest(TestCase):
... def testFailedResutFormatted(self):
... assert False
...
>>> tc = TestCaseTest("testFailedResutFormatted")
>>> tc.run()
<unittest.result.TestResult run=1 errors=0 failures=1>
There you see a failure has been recorded.
Pass in a TestResult
instance to the TestCase.run()
method and it'll be used instead; the result.failures
attribute shows the assertion fired and was recorded:
>>> from unittest import TestResult
>>> result = TestResult()
>>> tc.run(result)
>>> result
<unittest.result.TestResult run=1 errors=0 failures=1>
>>> result.failures
[(<__main__.TestCaseTest testMethod=testFailedResutFormatted>, 'Traceback (most recent call last):\n File "<stdin>", line 3, in testFailedResutFormatted\nAssertionError\n')]
>>> print result.failures[0][1]
Traceback (most recent call last):
File "<stdin>", line 3, in testFailedResutFormatted
AssertionError
Upvotes: 1