How it works...

In this example, the possible outcomes of a unit test by unittest are shown.

The possible outcomes are as follows:

  • ERROR: The test raises an exception other than AssertionError. There is no explicit way to pass a test, so the test status depends on the presence (or absence) of an exception.
  • FAILED: The test is not passed and an AssertionError exception is raised.
  • OK: The test is passed.

The output is as follows:

===========================================================
ERROR: testError (__main__.OutcomesTest)
-----------------------------------------------------------
Traceback (most recent call last):
File "unittest_outcomes.py", line 15, in testError
raise RuntimeError('Errore nel test!')
RuntimeError: Errore nel test!

===========================================================
FAIL: testFail (__main__.OutcomesTest)
-----------------------------------------------------------
Traceback (most recent call last):
File "unittest_outcomes.py", line 12, in testFail
self.failIf(True)
AssertionError

-----------------------------------------------------------
Ran 3 tests in 0.000s

FAILED (failures=1, errors=1)

Most tests affirm the truth of a condition. There are different ways of writing tests that verify a truth, depending on the perspective of the author of the test and whether the desired result of the code is verified. If the code produces a value that can be evaluated as true, then the failUnless () and assertTrue () methods should be used. If the code produces a false value, then it makes more sense to use the failIf () and assertFalse () methods:

import unittest

class TruthTest(unittest.TestCase):

def testFailUnless(self):
self.failUnless(True)

def testAssertTrue(self):
self.assertTrue(True)

def testFailIf(self):
self.assertFalse(False)

def testAssertFalse(self):
self.assertFalse(False)

if __name__ == '__main__':
unittest.main()

The result is as follows:

> python unittest_failwithmessage.py -v
testFail (__main__.FailureMessageTest) ... FAIL

===========================================================
FAIL: testFail (__main__.FailureMessageTest)
-----------------------------------------------------------
Traceback (most recent call last):
File "unittest_failwithmessage.py", line 9, in testFail
self.failIf(True, 'Il messaggio di fallimento va qui')
AssertionError: Il messaggio di fallimento va qui

-----------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)
robby@robby-desktop:~/pydev/pymotw-it/dumpscripts$ python unittest_truth.py -v
testAssertFalse (__main__.TruthTest) ... ok
testAssertTrue (__main__.TruthTest) ... ok
testFailIf (__main__.TruthTest) ... ok
testFailUnless (__main__.TruthTest) ... ok

-----------------------------------------------------------
Ran 4 tests in 0.000s

OK
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset