@@ -65,6 +65,219 @@ \subsection{Mapping concepts to classes
6565\subsection {Organizing test code
6666 \label {organizing-tests } }
6767
68+ The basic building blocks of unit testing are \dfn {test cases} ---
69+ single scenarios that must be set up and checked for correctness. In
70+ PyUnit, test cases are represented by instances of the
71+ \class {TestCase} class in the \refmodule {unittest} module. To make
72+ your own test cases you must write subclasses of \class {TestCase}, or
73+ use \class {FunctionTestCase}.
74+
75+ An instance of a \class {TestCase}-derived class is an object that can
76+ completely run a single test method, together with optional set-up
77+ and tidy-up code.
78+
79+ The testing code of a \class {TestCase} instance should be entirely
80+ self contained, such that it can be run either in isolation or in
81+ arbitrary combination with any number of other test cases.
82+
83+ The simplest test case subclass will simply override the
84+ \method {runTest()} method in order to perform specific testing code:
85+
86+ \begin {verbatim }
87+ import unittest
88+
89+ class DefaultWidgetSizeTestCase(unittest.TestCase):
90+ def runTest(self):
91+ widget = Widget("The widget")
92+ assert widget.size() == (50,50), 'incorrect default size'
93+ \end {verbatim }
94+
95+ Note that in order to test something, we just use the built-in 'assert'
96+ statement of Python. If the test fails when the test case runs,
97+ \class {TestFailed} will be raised, and the testing framework
98+ will identify the test case as a \dfn {failure}. Other exceptions that
99+ do not arise from explicit 'assert' checks are identified by the testing
100+ framework as dfn{errors}.
101+
102+ The way to run a test case will be described later. For now, note
103+ that to construct an instance of such a test case, we call its
104+ constructor without arguments:
105+
106+ \begin {verbatim }
107+ testCase = DefaultWidgetSizeTestCase()
108+ \end {verbatim }
109+
110+ Now, such test cases can be numerous, and their set-up can be
111+ repetitive. In the above case, constructing a `` Widget'' in each of
112+ 100 Widget test case subclasses would mean unsightly duplication.
113+
114+ Luckily, we can factor out such set-up code by implementing a method
115+ called \method {setUp()}, which the testing framework will
116+ automatically call for us when we run the test:
117+
118+ \begin {verbatim }
119+ import unittest
120+
121+ class SimpleWidgetTestCase(unittest.TestCase):
122+ def setUp(self):
123+ self.widget = Widget("The widget")
124+
125+ class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
126+ def runTest(self):
127+ assert self.widget.size() == (50,50), 'incorrect default size'
128+
129+ class WidgetResizeTestCase(SimpleWidgetTestCase):
130+ def runTest(self):
131+ self.widget.resize(100,150)
132+ assert self.widget.size() == (100,150), \
133+ 'wrong size after resize'
134+ \end {verbatim }
135+
136+ If the \method {setUp()} method raises an exception while the test is
137+ running, the framework will consider the test to have suffered an
138+ error, and the \method {runTest()} method will not be executed.
139+
140+ Similarly, we can provide a \method {tearDown()} method that tidies up
141+ after the \method {runTest()} method has been run:
142+
143+ \begin {verbatim }
144+ import unittest
145+
146+ class SimpleWidgetTestCase(unittest.TestCase):
147+ def setUp(self):
148+ self.widget = Widget("The widget")
149+
150+ def tearDown(self):
151+ self.widget.dispose()
152+ self.widget = None
153+ \end {verbatim }
154+
155+ If \method {setUp()} succeeded, the \method {tearDown()} method will be
156+ run regardless of whether or not \method {runTest()} succeeded.
157+
158+ Such a working environment for the testing code is called a
159+ \dfn {fixture}.
160+
161+ Often, many small test cases will use the same fixture. In this case,
162+ we would end up subclassing \class {SimpleWidgetTestCase} into many
163+ small one-method classes such as
164+ \class {DefaultWidgetSizeTestCase}. This is time-consuming and
165+ discouraging, so in the same vein as JUnit, PyUnit provides a simpler
166+ mechanism:
167+
168+ \begin {verbatim }
169+ import unittest
170+
171+ class WidgetTestCase(unittest.TestCase):
172+ def setUp(self):
173+ self.widget = Widget("The widget")
174+
175+ def tearDown(self):
176+ self.widget.dispose()
177+ self.widget = None
178+
179+ def testDefaultSize(self):
180+ assert self.widget.size() == (50,50), \
181+ 'incorrect default size'
182+
183+ def testResize(self):
184+ self.widget.resize(100,150)
185+ assert self.widget.size() == (100,150), \
186+ 'wrong size after resize'
187+ \end {verbatim }
188+
189+ Here we have not provided a \method {runTest()} method, but have
190+ instead provided two different test methods. Class instances will now
191+ each run one of the \method {test*()} methods, with \code {self.widget}
192+ created and destroyed separately for each instance. When creating an
193+ instance we must specify the test method it is to run. We do this by
194+ passing the method name in the constructor:
195+
196+ \begin {verbatim }
197+ defaultSizeTestCase = WidgetTestCase("testDefaultSize")
198+ resizeTestCase = WidgetTestCase("testResize")
199+ \end {verbatim }
200+
201+ Test case instances are grouped together according to the features
202+ they test. PyUnit provides a mechanism for this: the \class {test
203+ suite}, represented by the class \class {TestSuite} in the
204+ \refmodule {unittest} module:
205+
206+ \begin {verbatim }
207+ widgetTestSuite = unittest.TestSuite()
208+ widgetTestSuite.addTest(WidgetTestCase("testDefaultSize"))
209+ widgetTestSuite.addTest(WidgetTestCase("testResize"))
210+ \end {verbatim }
211+
212+ For the ease of running tests, as we will see later, it is a good
213+ idea to provide in each test module a callable object that returns a
214+ pre-built test suite:
215+
216+ \begin {verbatim }
217+ def suite():
218+ suite = unittest.TestSuite()
219+ suite.addTest(WidgetTestCase("testDefaultSize"))
220+ suite.addTest(WidgetTestCase("testResize"))
221+ return suite
222+ \end {verbatim }
223+
224+ or even:
225+
226+ \begin {verbatim }
227+ class WidgetTestSuite(unittest.TestSuite):
228+ def __init__(self):
229+ unittest.TestSuite.__init__(self,map(WidgetTestCase,
230+ ("testDefaultSize",
231+ "testResize")))
232+ \end {verbatim }
233+
234+ (The latter is admittedly not for the faint-hearted!)
235+
236+ Since it is a common pattern to create a \class {TestCase} subclass
237+ with many similarly named test functions, there is a convenience
238+ function called \function {makeSuite()} provided in the
239+ \refmodule {unittest} module that constructs a test suite that
240+ comprises all of the test cases in a test case class:
241+
242+ \begin {verbatim }
243+ suite = unittest.makeSuite(WidgetTestCase,'test')
244+ \end {verbatim }
245+
246+ Note that when using the \function {makeSuite()} function, the order in
247+ which the various test cases will be run by the test suite is the
248+ order determined by sorting the test function names using the
249+ \function {cmp()} built-in function.
250+
251+ Often it is desirable to group suites of test cases together, so as to
252+ run tests for the whole system at once. This is easy, since
253+ \class {TestSuite} instances can be added to a \class {TestSuite} just
254+ as \class {TestCase} instances can be added to a \class {TestSuite}:
255+
256+ \begin {verbatim }
257+ suite1 = module1.TheTestSuite()
258+ suite2 = module2.TheTestSuite()
259+ alltests = unittest.TestSuite((suite1, suite2))
260+ \end {verbatim }
261+
262+ You can place the definitions of test cases and test suites in the
263+ same modules as the code they are to test (e.g.\ \file {widget.py}),
264+ but there are several advantages to placing the test code in a
265+ separate module, such as \file {widgettests.py}:
266+
267+ \begin {itemize }
268+ \item The test module can be run standalone from the command line.
269+ \item The test code can more easily be separated from shipped code.
270+ \item There is less temptation to change test code to fit the code.
271+ it tests without a good reason.
272+ \item Test code should be modified much less frequently than the
273+ code it tests.
274+ \item Tested code can be refactored more easily.
275+ \item Tests for modules written in C must be in separate modules
276+ anyway, so why not be consistent?
277+ \item If the testing strategy changes, there is no need to change
278+ the source code.
279+ \end {itemize }
280+
68281
69282\subsection {Re-using old test code
70283 \label {legacy-unit-tests } }
@@ -103,6 +316,11 @@ \subsection{Re-using old test code
103316\end {verbatim }
104317
105318
319+ \strong {Note:} PyUnit supports the use of \exception {AssertionError}
320+ as an indicator of test failure, but does not recommend it. Future
321+ versions may treat \exception {AssertionError} differently.
322+
323+
106324\subsection {Classes and functions
107325 \label {unittest-contents } }
108326
@@ -156,16 +374,22 @@ \subsection{Classes and functions
156374\begin {funcdesc }{main}{\optional {module\optional {,
157375 defaultTest\optional {, argv\optional {,
158376 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:
377+ A command-line program that runs a set of tests; this is primarily
378+ for making test modules conveniently executable. The simplest use
379+ for this function is:
162380
163381\begin {verbatim }
164382if __name__ == '__main__':
165383 unittest.main()
166384\end {verbatim }
167385\end {funcdesc }
168386
387+ \begin {excdesc }{TestFailed}
388+ Exception raised to indicate that a test failed. The
389+ \method {TestCase.fail()} method is responsible for creating and
390+ raising this exception.
391+ \end {excdesc }
392+
169393
170394\subsection {TestCase Objects
171395 \label {testcase-objects } }
@@ -213,46 +437,42 @@ \subsection{TestCase Objects
213437\end {methoddesc }
214438
215439
216- The test code can either raise \exception {AssertionError} or use any
217- of the following methods to check for and report failures:
440+ The test code can use any of the following methods to check for and
441+ report failures:
218442
219443\begin {methoddesc }[TestCase]{failUnless}{expr\optional {, msg}}
220- \methodline [TestCase]{assert_}{value\optional {, msg}}
221444 This method is similar to the \keyword {assert} statement, except it
222445 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
446+ \programopt {-O} command line switch), and raises the
447+ \exception {TestFailed} exception. If \var {expr} is false,
448+ \exception {TestFailed} will be raised with \var {msg} as the
225449 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 }
450+ message if \var {msg} is omitted.
231451\end {methoddesc }
232452
233- \begin {methoddesc }[TestCase]{assertEqual }{first, second\optional {, msg}}
453+ \begin {methoddesc }[TestCase]{failUnlessEqual }{first, second\optional {, msg}}
234454 Test that \var {first} and \var {second} are equal. If the values do
235455 not compare equal, the test will fail with the explanation given by
236- \var {msg}, or \code {None}. Note that using \method {assertEqual ()}
456+ \var {msg}, or \code {None}. Note that using \method {failUnlessEqual ()}
237457 improves upon doing the comparison as the first parameter to
238458 \method {failUnless()} is that the default value for \var {msg} can be
239459 computed to include representations of both \var {first} and
240460 \var {second}.
241461\end {methoddesc }
242462
243- \begin {methoddesc }[TestCase]{assertNotEqual }{first, second\optional {, msg}}
463+ \begin {methoddesc }[TestCase]{failIfEqual }{first, second\optional {, msg}}
244464 Test that \var {first} and \var {second} are not equal. If the values
245465 do compare equal, the test will fail with the explanation given by
246- \var {msg}, or \code {None}. Note that using \method {assertNotEqual ()}
466+ \var {msg}, or \code {None}. Note that using \method {failIfEqual ()}
247467 improves upon doing the comparison as the first parameter to
248468 \method {failUnless()} is that the default value for \var {msg} can be
249469 computed to include representations of both \var {first} and
250470 \var {second}.
251471\end {methoddesc }
252472
253473\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
474+ The inverse of the \method {failUnless ()} method is the
475+ \method {failIf()} method. This raises \exception {TestFailed } if
256476 \var {expr} is true, with \var {msg} or \code {None} for the error
257477 message.
258478\end {methoddesc }
@@ -337,13 +557,13 @@ \subsection{TestResult Objects
337557\begin {memberdesc }[TestResult]{errors}
338558 A list containing pairs of \class {TestCase} instances and the
339559 \function {sys.exc_info()} results for tests which raised exceptions
340- other than \exception {AssertionError}.
560+ other than \exception {AssertionError} and \exception {TestFailed} .
341561\end {memberdesc }
342562
343563\begin {memberdesc }[TestResult]{failures}
344564 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.
565+ \function {sys.exc_info()} results for tests which raised either
566+ \exception {TestFailed} or \ exception{AssertionError} .
347567\end {memberdesc }
348568
349569\begin {memberdesc }[TestResult]{testsRun}
@@ -373,18 +593,20 @@ \subsection{TestResult Objects
373593
374594\begin {methoddesc }[TestResult]{addError}{test, err}
375595 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})}.
596+ than \exception {TestFailed} or \exception {AssertionError}.
597+ \var {err} is a tuple of the form returned by
598+ \function {sys.exc_info()}: \code {(\var {type}, \var {value},
599+ \var {traceback})}.
379600\end {methoddesc }
380601
381602\begin {methoddesc }[TestResult]{addFailure}{test, err}
382603 Called when the test case \var {test} results in an
383604 \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})}.
605+ test raised either \exception {TestFailed} or
606+ \exception {AssertionError} and not the implementation being tested.
607+ \var {err} is a tuple of the form returned by
608+ \function {sys.exc_info()}: \code {(\var {type}, \var {value},
609+ \var {traceback})}.
388610\end {methoddesc }
389611
390612\begin {methoddesc }[TestResult]{addSuccess}{test}
0 commit comments