Fred Drake | b9ad228 | 2001-04-07 05:41:39 +0000 | [diff] [blame] | 1 | \section{\module{unittest} --- |
| 2 | Unit testing framework} |
| 3 | |
| 4 | \declaremodule{standard}{unittest} |
| 5 | \moduleauthor{Steve Purcell}{stephen\textunderscore{}purcell@yahoo.com} |
| 6 | \sectionauthor{Steve Purcell}{stephen\textunderscore{}purcell@yahoo.com} |
| 7 | \sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org} |
| 8 | |
| 9 | |
| 10 | The Python unit testing framework, often referred to as ``PyUnit,'' is |
| 11 | a Python language version of JUnit, by Kent Beck and Erich Gamma. |
| 12 | JUnit is, in turn, a Java version of Kent's Smalltalk testing |
| 13 | framework. Each is the de facto standard unit testing framework for |
| 14 | its respective language. |
| 15 | |
| 16 | PyUnit supports test automation, sharing of setup and shutdown code |
| 17 | for tests, aggregation of tests into collections, and independence of |
| 18 | the tests from the reporting framework. The \module{unittest} module |
| 19 | provides classes that make it easy to support these qualities for a |
| 20 | set of tests. |
| 21 | |
| 22 | To achieve this, PyUnit supports three major concepts: |
| 23 | |
| 24 | \begin{definitions} |
Fred Drake | 29be701 | 2001-04-10 22:25:06 +0000 | [diff] [blame] | 25 | \term{test fixture} |
| 26 | A \dfn{test fixture} represents the preparation needed to perform one |
| 27 | or more tests, and any associate cleanup actions. This may involve, |
| 28 | for example, creating temporary or proxy databases, directories, or |
| 29 | starting a server process. |
| 30 | |
Fred Drake | b9ad228 | 2001-04-07 05:41:39 +0000 | [diff] [blame] | 31 | \term{test case} |
| 32 | A \dfn{test case} is the smallest unit of testing. It checks for a |
| 33 | specific response to a particular set of inputs. PyUnit provides a |
| 34 | base class, \class{TestCase}, which may be used to create new test |
| 35 | cases. |
| 36 | |
| 37 | \term{test suite} |
| 38 | A \dfn{test suite} is a collection of test cases, test suites, or |
| 39 | both. It is used to aggregate tests that should be executed |
| 40 | together. |
| 41 | |
| 42 | \term{test runner} |
| 43 | A \dfn{test runner} is a component which orchestrates the execution of |
| 44 | tests and provides the outcome to the user. The runner may use a |
| 45 | graphical interface, a textual interface, or return a special value to |
| 46 | indicate the results of executing the tests. |
| 47 | \end{definitions} |
| 48 | |
| 49 | |
| 50 | |
| 51 | \begin{seealso} |
| 52 | \seetitle[http://pyunit.sourceforge.net/]{PyUnit Web Site}{The |
| 53 | source for further information on PyUnit.} |
| 54 | \seetitle[http://www.XProgramming.com/testfram.htm]{Simple Smalltalk |
| 55 | Testing: With Patterns}{Kent Beck's original paper on |
| 56 | testing frameworks using the pattern shared by |
| 57 | \module{unittest}.} |
| 58 | \end{seealso} |
| 59 | |
| 60 | |
| 61 | \subsection{Mapping concepts to classes |
| 62 | \label{test-concept-classes}} |
| 63 | |
| 64 | |
| 65 | \subsection{Organizing test code |
| 66 | \label{organizing-tests}} |
| 67 | |
| 68 | |
| 69 | \subsection{Re-using old test code |
| 70 | \label{legacy-unit-tests}} |
| 71 | |
| 72 | Some users will find that they have existing test code that they would |
| 73 | like to run from PyUnit, without converting every old test function to |
| 74 | a \class{TestCase} subclass. |
| 75 | |
| 76 | For this reason, PyUnit provides a \class{FunctionTestCase} class. |
| 77 | This subclass of \class{TestCase} can be used to wrap an existing test |
| 78 | function. Set-up and tear-down functions can also optionally be |
| 79 | wrapped. |
| 80 | |
| 81 | Given the following test function: |
| 82 | |
| 83 | \begin{verbatim} |
| 84 | def testSomething(): |
| 85 | something = makeSomething() |
| 86 | assert something.name is not None |
| 87 | # ... |
| 88 | \end{verbatim} |
| 89 | |
| 90 | one can create an equivalent test case instance as follows: |
| 91 | |
| 92 | \begin{verbatim} |
| 93 | testcase = unittest.FunctionTestCase(testSomething) |
| 94 | \end{verbatim} |
| 95 | |
| 96 | If there are additional set-up and tear-down methods that should be |
| 97 | called as part of the test case's operation, they can also be provided: |
| 98 | |
| 99 | \begin{verbatim} |
| 100 | testcase = unittest.FunctionTestCase(testSomething, |
| 101 | setUp=makeSomethingDB, |
| 102 | tearDown=deleteSomethingDB) |
| 103 | \end{verbatim} |
| 104 | |
| 105 | |
| 106 | \subsection{Classes and functions |
| 107 | \label{unittest-contents}} |
| 108 | |
| 109 | \begin{classdesc}{TestCase}{} |
| 110 | Instances of the \class{TestCase} class represent the smallest |
| 111 | testable units in a set of tests. This class is intended to be used |
| 112 | as a base class, with specific tests being implemented by concrete |
| 113 | subclasses. This class implements the interface needed by the test |
| 114 | runner to allow it to drive the test, and methods that the test code |
| 115 | can use to check for and report various kinds of failures. |
| 116 | \end{classdesc} |
| 117 | |
| 118 | \begin{classdesc}{FunctionTestCase}{testFunc\optional{, |
| 119 | setup\optional{, tearDown\optional{, description}}}} |
| 120 | This class implements the portion of the \class{TestCase} interface |
| 121 | which allows the test runner to drive the test, but does not provide |
| 122 | the methods which test code can use to check and report errors. |
| 123 | This is used to create test cases using legacy test code, allowing |
| 124 | it to be integrated into a \refmodule{unittest}-based test |
| 125 | framework. |
| 126 | \end{classdesc} |
| 127 | |
Fred Drake | 29be701 | 2001-04-10 22:25:06 +0000 | [diff] [blame] | 128 | \begin{classdesc}{TestSuite}{\optional{tests}} |
Fred Drake | b9ad228 | 2001-04-07 05:41:39 +0000 | [diff] [blame] | 129 | This class represents an aggregation of individual tests cases and |
| 130 | test suites. The class presents the interface needed by the test |
| 131 | runner to allow it to be run as any other test case, but all the |
| 132 | contained tests and test suites are executed. Additional methods |
Fred Drake | 29be701 | 2001-04-10 22:25:06 +0000 | [diff] [blame] | 133 | are provided to add test cases and suites to the aggregation. If |
| 134 | \var{tests} is given, it must be a sequence of individual tests that |
| 135 | will be added to the suite. |
Fred Drake | b9ad228 | 2001-04-07 05:41:39 +0000 | [diff] [blame] | 136 | \end{classdesc} |
| 137 | |
| 138 | \begin{classdesc}{TestLoader}{} |
Fred Drake | 29be701 | 2001-04-10 22:25:06 +0000 | [diff] [blame] | 139 | This class is responsible for loading tests according to various |
| 140 | criteria and returning them wrapped in a \class{TestSuite}. |
| 141 | It can load all tests within a given module or \class{TestCase} |
| 142 | class. When loading from a module, it considers all |
| 143 | \class{TestCase}-derived classes. For each such class, it creates |
| 144 | an instance for each method with a name beginning with the string |
| 145 | \samp{test}. |
Fred Drake | b9ad228 | 2001-04-07 05:41:39 +0000 | [diff] [blame] | 146 | \end{classdesc} |
| 147 | |
| 148 | \begin{classdesc}{TextTestRunner}{\optional{stream\optional{, |
| 149 | descriptions\optional{, verbosity}}}} |
Fred Drake | 29be701 | 2001-04-10 22:25:06 +0000 | [diff] [blame] | 150 | A basic test runner implementation which prints results on standard |
| 151 | output. It has a few configurable parameters, but is essentially |
| 152 | very simple. Graphical applications which run test suites should |
| 153 | provide alternate implementations. |
Fred Drake | b9ad228 | 2001-04-07 05:41:39 +0000 | [diff] [blame] | 154 | \end{classdesc} |
| 155 | |
| 156 | \begin{funcdesc}{main}{\optional{module\optional{, |
| 157 | defaultTest\optional{, argv\optional{, |
| 158 | testRunner\optional{, testRunner}}}}}} |
| 159 | A command-line program that runs a set of tests; this is primarily |
| 160 | for making test modules conveniently executable. The simplest use for |
| 161 | this function is: |
| 162 | |
| 163 | \begin{verbatim} |
| 164 | if __name__ == '__main__': |
| 165 | unittest.main() |
| 166 | \end{verbatim} |
| 167 | \end{funcdesc} |
| 168 | |
| 169 | |
| 170 | \subsection{TestCase Objects |
| 171 | \label{testcase-objects}} |
| 172 | |
Fred Drake | 29be701 | 2001-04-10 22:25:06 +0000 | [diff] [blame] | 173 | Each \class{TestCase} instance represents a single test, but each |
| 174 | concrete subclass may be used to define multiple tests --- the |
| 175 | concrete class represents a single test fixture. The fixture is |
| 176 | created and cleaned up for each test case. |
| 177 | |
| 178 | \class{TestCase} instances provide three groups of methods: one group |
| 179 | used to run the test, another used by the test implementation to |
| 180 | check conditions and report failures, and some inquiry methods |
| 181 | allowing information about the test itself to be gathered. |
| 182 | |
| 183 | Methods in the first group are: |
| 184 | |
| 185 | \begin{methoddesc}[TestCase]{setUp}{} |
| 186 | Method called to prepare the test fixture. This is called |
| 187 | immediately before calling the test method; any exception raised by |
| 188 | this method will be considered an error rather than a test failure. |
| 189 | The default implementation does nothing. |
| 190 | \end{methoddesc} |
| 191 | |
| 192 | \begin{methoddesc}[TestCase]{run}{\optional{result}} |
| 193 | Run the test, collecting the result into the test result object |
| 194 | passed as \var{result}. If \var{result} is omitted or \code{None}, |
| 195 | a temporary result object is created and used, but is not made |
| 196 | available to the caller. This is equivalent to simply calling the |
| 197 | \class{TestCase} instance. |
| 198 | \end{methoddesc} |
| 199 | |
| 200 | \begin{methoddesc}[TestCase]{tearDown}{} |
| 201 | Method called immediately after the test method has been called and |
| 202 | the result recorded. This is called even if the test method raised |
| 203 | an exception, so the implementation in subclasses may need to be |
| 204 | particularly careful about checking internal state. Any exception |
| 205 | raised by this method will be considered an error rather than a test |
| 206 | failure. The default implementation does nothing. |
| 207 | \end{methoddesc} |
| 208 | |
| 209 | \begin{methoddesc}[TestCase]{debug}{} |
| 210 | Run the test without collecting the result. This allows exceptions |
| 211 | raised by the test to be propogated to the caller, and can be used |
| 212 | to support running tests under a debugger. |
| 213 | \end{methoddesc} |
| 214 | |
| 215 | |
| 216 | The test code can either raise \exception{AssertionError} or use any |
| 217 | of the following methods to check for and report failures: |
| 218 | |
| 219 | \begin{methoddesc}[TestCase]{failUnless}{expr\optional{, msg}} |
| 220 | \methodline[TestCase]{assert_}{value\optional{, msg}} |
| 221 | This method is similar to the \keyword{assert} statement, except it |
| 222 | works even when Python is executed in ``optimizing'' mode (using the |
| 223 | \programopt{-O} command line switch). If \var{expr} is false, |
| 224 | \exception{AssertionError} will be raised with \var{msg} as the |
| 225 | message describing the failure; \code{None} will be used for the |
| 226 | message if \var{msg} is omitted. This method is equivalent to |
| 227 | |
| 228 | \begin{alltt} |
| 229 | assert \var{expr}, \var{msg} |
| 230 | \end{alltt} |
| 231 | \end{methoddesc} |
| 232 | |
| 233 | \begin{methoddesc}[TestCase]{assertEqual}{first, second\optional{, msg}} |
| 234 | Test that \var{first} and \var{second} are equal. If the values do |
| 235 | not compare equal, the test will fail with the explanation given by |
| 236 | \var{msg}, or \code{None}. Note that using \method{assertEqual()} |
| 237 | improves upon doing the comparison as the first parameter to |
| 238 | \method{failUnless()} is that the default value for \var{msg} can be |
| 239 | computed to include representations of both \var{first} and |
| 240 | \var{second}. |
| 241 | \end{methoddesc} |
| 242 | |
| 243 | \begin{methoddesc}[TestCase]{assertNotEqual}{first, second\optional{, msg}} |
| 244 | Test that \var{first} and \var{second} are not equal. If the values |
| 245 | do compare equal, the test will fail with the explanation given by |
| 246 | \var{msg}, or \code{None}. Note that using \method{assertNotEqual()} |
| 247 | improves upon doing the comparison as the first parameter to |
| 248 | \method{failUnless()} is that the default value for \var{msg} can be |
| 249 | computed to include representations of both \var{first} and |
| 250 | \var{second}. |
| 251 | \end{methoddesc} |
| 252 | |
| 253 | \begin{methoddesc}[TestCase]{failIf}{expr\optional{, msg}} |
| 254 | The inverse of the \method{assert_()} method is the |
| 255 | \method{failIf()} method. This raises \exception{AssertionError} if |
| 256 | \var{expr} is true, with \var{msg} or \code{None} for the error |
| 257 | message. |
| 258 | \end{methoddesc} |
| 259 | |
| 260 | \begin{methoddesc}[TestCase]{fail}{\optional{msg}} |
| 261 | Fail unconditionally, with \var{msg} or \code{None} for the error |
| 262 | message. |
| 263 | \end{methoddesc} |
| 264 | |
| 265 | |
| 266 | Testing frameworks can use the following methods to collect |
| 267 | information on the test: |
| 268 | |
| 269 | \begin{methoddesc}[TestCase]{countTestCases}{} |
| 270 | Return the number of tests represented by the this test object. For |
| 271 | \class{TestCase} instances, this will always be \code{1}, but this |
| 272 | method is also implemented by the \class{TestSuite} class, which can |
| 273 | return larger values. |
| 274 | \end{methoddesc} |
| 275 | |
| 276 | \begin{methoddesc}[TestCase]{defaultTestResult}{} |
| 277 | Return the default type of test result object to be used to run this |
| 278 | test. |
| 279 | \end{methoddesc} |
| 280 | |
| 281 | \begin{methoddesc}[TestCase]{id}{} |
| 282 | Return a string identifying the specific test case. This is usually |
| 283 | the full name of the test method, including the module and class |
| 284 | names. |
| 285 | \end{methoddesc} |
| 286 | |
| 287 | \begin{methoddesc}[TestCase]{shortDescription}{} |
| 288 | Returns a one-line description of the test, or \code{None} if no |
| 289 | description has been provided. The default implementation of this |
| 290 | method returns the first line of the test method's docstring, if |
| 291 | available, or \code{None}. |
| 292 | \end{methoddesc} |
| 293 | |
Fred Drake | b9ad228 | 2001-04-07 05:41:39 +0000 | [diff] [blame] | 294 | |
| 295 | \subsection{TestSuite Objects |
| 296 | \label{testsuite-objects}} |
| 297 | |
| 298 | \class{TestSuite} objects behave much like \class{TestCase} objects, |
| 299 | except they do not actually implement a test. Instead, they are used |
| 300 | to aggregate tests into groups that should be run together. Some |
| 301 | additional methods are available to add tests to \class{TestSuite} |
| 302 | instances: |
| 303 | |
| 304 | \begin{methoddesc}[TestSuite]{addTest}{test} |
| 305 | Add a \class{TestCase} or \class{TestSuite} to the set of tests that |
| 306 | make up the suite. |
| 307 | \end{methoddesc} |
| 308 | |
| 309 | \begin{methoddesc}[TestSuite]{addTests}{tests} |
| 310 | Add all the tests from a sequence of \class{TestCase} and |
| 311 | \class{TestSuite} instances to this test suite. |
| 312 | \end{methoddesc} |
| 313 | |
| 314 | |
| 315 | \subsection{TestResult Objects |
| 316 | \label{testresult-objects}} |
| 317 | |
| 318 | A \class{TestResult} object stores the results of a set of tests. The |
| 319 | \class{TestCase} and \class{TestSuite} classes ensure that results are |
| 320 | properly stored; test authors do not need to worry about recording the |
| 321 | outcome of tests. |
| 322 | |
| 323 | Testing frameworks built on top of \refmodule{unittest} may want |
| 324 | access to the \class{TestResult} object generated by running a set of |
| 325 | tests for reporting purposes; a \class{TestResult} instance is |
| 326 | returned by the \method{TestRunner.run()} method for this purpose. |
| 327 | |
| 328 | Each instance holds the total number of tests run, and collections of |
| 329 | failures and errors that occurred among those test runs. The |
| 330 | collections contain tuples of \code{(\var{testcase}, |
| 331 | \var{exceptioninfo})}, where \var{exceptioninfo} is a tuple as |
| 332 | returned by \function{sys.exc_info()}. |
| 333 | |
| 334 | \class{TestResult} instances have the following attributes that will |
| 335 | be of interest when inspecting the results of running a set of tests: |
| 336 | |
| 337 | \begin{memberdesc}[TestResult]{errors} |
| 338 | A list containing pairs of \class{TestCase} instances and the |
| 339 | \function{sys.exc_info()} results for tests which raised exceptions |
| 340 | other than \exception{AssertionError}. |
| 341 | \end{memberdesc} |
| 342 | |
| 343 | \begin{memberdesc}[TestResult]{failures} |
| 344 | A list containing pairs of \class{TestCase} instances and the |
| 345 | \function{sys.exc_info()} results for tests which raised the |
| 346 | \exception{AssertionError} exception. |
| 347 | \end{memberdesc} |
| 348 | |
| 349 | \begin{memberdesc}[TestResult]{testsRun} |
| 350 | The number of tests which have been started. |
| 351 | \end{memberdesc} |
| 352 | |
| 353 | \begin{methoddesc}[TestResult]{wasSuccessful}{} |
| 354 | Returns true if all tests run so far have passed, otherwise returns |
| 355 | false. |
| 356 | \end{methoddesc} |
| 357 | |
| 358 | |
| 359 | The following methods of the \class{TestResult} class are used to |
| 360 | maintain the internal data structures, and mmay be extended in |
| 361 | subclasses to support additional reporting requirements. This is |
| 362 | particularly useful in building GUI tools which support interactive |
| 363 | reporting while tests are being run. |
| 364 | |
| 365 | \begin{methoddesc}[TestResult]{startTest}{test} |
| 366 | Called when the test case \var{test} is about to be run. |
| 367 | \end{methoddesc} |
| 368 | |
| 369 | \begin{methoddesc}[TestResult]{stopTest}{test} |
| 370 | Called when the test case \var{test} has been executed, regardless |
| 371 | of the outcome. |
| 372 | \end{methoddesc} |
| 373 | |
| 374 | \begin{methoddesc}[TestResult]{addError}{test, err} |
| 375 | Called when the test case \var{test} results in an exception other |
| 376 | than \exception{AssertionError}. \var{err} is a tuple of the form |
| 377 | returned by \function{sys.exc_info()}: \code{(\var{type}, |
| 378 | \var{value}, \var{traceback})}. |
| 379 | \end{methoddesc} |
| 380 | |
| 381 | \begin{methoddesc}[TestResult]{addFailure}{test, err} |
| 382 | Called when the test case \var{test} results in an |
| 383 | \exception{AssertionError} exception; the assumption is that the |
| 384 | test raised the \exception{AssertionError} and not the |
| 385 | implementation being tested. \var{err} is a tuple of the form |
| 386 | returned by \function{sys.exc_info()}: \code{(\var{type}, |
| 387 | \var{value}, \var{traceback})}. |
| 388 | \end{methoddesc} |
| 389 | |
| 390 | \begin{methoddesc}[TestResult]{addSuccess}{test} |
| 391 | This method is called for a test that does not fail; \var{test} is |
| 392 | the test case object. |
| 393 | \end{methoddesc} |
| 394 | |
| 395 | |
| 396 | One additional method is available for \class{TestResult} objects: |
| 397 | |
| 398 | \begin{methoddesc}[TestResult]{stop}{} |
| 399 | This method can be called to signal that the set of tests being run |
| 400 | should be aborted. Once this has been called, the |
| 401 | \class{TestRunner} object return to its caller without running any |
| 402 | additional tests. This is used by the \class{TextTestRunner} class |
| 403 | to stop the test framework when the user signals an interrupt from |
| 404 | the keyboard. GUI tools which provide runners can use this in a |
| 405 | similar manner. |
| 406 | \end{methoddesc} |