The unittest module

When writing user tests, it's helpful to use a pre-existing test engine to spare you the repetitive task of writing code to run your tests. Since version 2.1, Python has been distributed with the unittest module. The unittest module implements a test framework called PyUnit (a Tkinter based user interface for unittest and some other goodies are available at http://pyunit.sourceforge.net/). A PyUnit module is made up of tests, test cases, and test suites. Table 5.5 defines the three groups.

Table 5.5 The three levels of abstraction in the unittest module

Item

Definition

Test

An individual method called by the PyUnit engine. By convention, the name of a test method begins with test. A test method typically executes some code, then performs one or more assert statements to test whether the results are as expected.

TestCase

A class defining one or more individual tests that share a common setup. The class is defined in PyUnit to manage a group of such tests. The TestCase class has support for doing common setup before and tear down after each test, ensuring that each test runs separately from the others. The TestCase class also defines some special assert methods, such as assertEqual.

TestSuite

One or more test methods or TestCase objects grouped together for the purpose of being run at the same time. When you actually tell PyUnit to run tests, you pass it a TestSuite object to run.

A single PyUnit test can have one of three results: success, failure, or error. Success indicates that the test method ran to completion, all assertions were true, and no errors were triggered. That is, of course, the desirable outcome. Failure and error indicate different problems with the code. A failure result means that one of your assertions returned false, indicating that the code runs successfully, but is not doing what you expect. An error result means that a Python exception was triggered somewhere in the execution of the test, showing that your code is not running successfully. The first failure or error in a single test will end the execution of that test, even if there are more assertions to test in the code, and the test runner will move on to the next test.

Was this article helpful?

0 0

Post a comment