blob: c73e23e6498e9a39a26ce35e0394a42f2fb88a8a [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2:mod:`test` --- Regression tests package for Python
3===================================================
4
5.. module:: test
6 :synopsis: Regression tests package containing the testing suite for Python.
7.. sectionauthor:: Brett Cannon <brett@python.org>
8
Georg Brandl5c367462010-08-01 22:26:02 +00009.. note::
10 The :mod:`test` package is meant for internal use by Python only. It is
11 documented for the benefit of the core developers of Python. Any use of
12 this package outside of Python's standard library is discouraged as code
13 mentioned here can change or be removed without notice between releases of
14 Python.
15
Georg Brandl8ec7f652007-08-15 14:28:01 +000016
17The :mod:`test` package contains all regression tests for Python as well as the
18modules :mod:`test.test_support` and :mod:`test.regrtest`.
19:mod:`test.test_support` is used to enhance your tests while
20:mod:`test.regrtest` drives the testing suite.
21
22Each module in the :mod:`test` package whose name starts with ``test_`` is a
23testing suite for a specific module or feature. All new tests should be written
24using the :mod:`unittest` or :mod:`doctest` module. Some older tests are
25written using a "traditional" testing style that compares output printed to
26``sys.stdout``; this style of test is considered deprecated.
27
28
29.. seealso::
30
31 Module :mod:`unittest`
32 Writing PyUnit regression tests.
33
34 Module :mod:`doctest`
35 Tests embedded in documentation strings.
36
37
38.. _writing-tests:
39
40Writing Unit Tests for the :mod:`test` package
41----------------------------------------------
42
Georg Brandl8ec7f652007-08-15 14:28:01 +000043It is preferred that tests that use the :mod:`unittest` module follow a few
44guidelines. One is to name the test module by starting it with ``test_`` and end
45it with the name of the module being tested. The test methods in the test module
46should start with ``test_`` and end with a description of what the method is
47testing. This is needed so that the methods are recognized by the test driver as
48test methods. Also, no documentation string for the method should be included. A
49comment (such as ``# Tests function returns only True or False``) should be used
50to provide documentation for test methods. This is done because documentation
51strings get printed out if they exist and thus what test is being run is not
52stated.
53
54A basic boilerplate is often used::
55
56 import unittest
57 from test import test_support
58
59 class MyTestCase1(unittest.TestCase):
60
61 # Only use setUp() and tearDown() if necessary
62
63 def setUp(self):
64 ... code to execute in preparation for tests ...
65
66 def tearDown(self):
67 ... code to execute to clean up after tests ...
68
69 def test_feature_one(self):
70 # Test feature one.
71 ... testing code ...
72
73 def test_feature_two(self):
74 # Test feature two.
75 ... testing code ...
76
77 ... more test methods ...
78
79 class MyTestCase2(unittest.TestCase):
80 ... same structure as MyTestCase1 ...
81
82 ... more test classes ...
83
84 def test_main():
85 test_support.run_unittest(MyTestCase1,
86 MyTestCase2,
87 ... list other tests ...
88 )
89
90 if __name__ == '__main__':
91 test_main()
92
93This boilerplate code allows the testing suite to be run by :mod:`test.regrtest`
94as well as on its own as a script.
95
96The goal for regression testing is to try to break code. This leads to a few
97guidelines to be followed:
98
99* The testing suite should exercise all classes, functions, and constants. This
100 includes not just the external API that is to be presented to the outside world
101 but also "private" code.
102
103* Whitebox testing (examining the code being tested when the tests are being
104 written) is preferred. Blackbox testing (testing only the published user
105 interface) is not complete enough to make sure all boundary and edge cases are
106 tested.
107
108* Make sure all possible values are tested including invalid ones. This makes
109 sure that not only all valid values are acceptable but also that improper values
110 are handled correctly.
111
112* Exhaust as many code paths as possible. Test where branching occurs and thus
113 tailor input to make sure as many different paths through the code are taken.
114
115* Add an explicit test for any bugs discovered for the tested code. This will
116 make sure that the error does not crop up again if the code is changed in the
117 future.
118
119* Make sure to clean up after your tests (such as close and remove all temporary
120 files).
121
122* If a test is dependent on a specific condition of the operating system then
123 verify the condition already exists before attempting the test.
124
125* Import as few modules as possible and do it as soon as possible. This
126 minimizes external dependencies of tests and also minimizes possible anomalous
127 behavior from side-effects of importing a module.
128
129* Try to maximize code reuse. On occasion, tests will vary by something as small
130 as what type of input is used. Minimize code duplication by subclassing a basic
131 test class with a class that specifies the input::
132
133 class TestFuncAcceptsSequences(unittest.TestCase):
134
135 func = mySuperWhammyFunction
136
137 def test_func(self):
138 self.func(self.arg)
139
140 class AcceptLists(TestFuncAcceptsSequences):
141 arg = [1,2,3]
142
143 class AcceptStrings(TestFuncAcceptsSequences):
144 arg = 'abc'
145
146 class AcceptTuples(TestFuncAcceptsSequences):
147 arg = (1,2,3)
148
149
150.. seealso::
151
152 Test Driven Development
153 A book by Kent Beck on writing tests before code.
154
155
156.. _regrtest:
157
158Running tests using :mod:`test.regrtest`
159----------------------------------------
160
161:mod:`test.regrtest` can be used as a script to drive Python's regression test
162suite. Running the script by itself automatically starts running all regression
163tests in the :mod:`test` package. It does this by finding all modules in the
164package whose name starts with ``test_``, importing them, and executing the
165function :func:`test_main` if present. The names of tests to execute may also be
166passed to the script. Specifying a single regression test (:program:`python
167regrtest.py` :option:`test_spam.py`) will minimize output and only print whether
168the test passed or failed and thus minimize output.
169
170Running :mod:`test.regrtest` directly allows what resources are available for
171tests to use to be set. You do this by using the :option:`-u` command-line
172option. Run :program:`python regrtest.py` :option:`-uall` to turn on all
173resources; specifying :option:`all` as an option for :option:`-u` enables all
174possible resources. If all but one resource is desired (a more common case), a
175comma-separated list of resources that are not desired may be listed after
176:option:`all`. The command :program:`python regrtest.py`
177:option:`-uall,-audio,-largefile` will run :mod:`test.regrtest` with all
178resources except the :option:`audio` and :option:`largefile` resources. For a
179list of all resources and more command-line options, run :program:`python
180regrtest.py` :option:`-h`.
181
182Some other ways to execute the regression tests depend on what platform the
183tests are being executed on. On Unix, you can run :program:`make` :option:`test`
184at the top-level directory where Python was built. On Windows, executing
185:program:`rt.bat` from your :file:`PCBuild` directory will run all regression
186tests.
187
188
189:mod:`test.test_support` --- Utility functions for tests
190========================================================
191
192.. module:: test.test_support
193 :synopsis: Support for Python regression tests.
194
Brett Cannone76e4d72008-05-20 22:08:20 +0000195.. note::
196
197 The :mod:`test.test_support` module has been renamed to :mod:`test.support`
Benjamin Petersone210be52010-05-28 03:23:52 +0000198 in Python 3.x.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000199
200The :mod:`test.test_support` module provides support for Python's regression
201tests.
202
203This module defines the following exceptions:
204
205
206.. exception:: TestFailed
207
208 Exception to be raised when a test fails. This is deprecated in favor of
209 :mod:`unittest`\ -based tests and :class:`unittest.TestCase`'s assertion
210 methods.
211
212
213.. exception:: TestSkipped
214
215 Subclass of :exc:`TestFailed`. Raised when a test is skipped. This occurs when a
216 needed resource (such as a network connection) is not available at the time of
217 testing.
218
219
220.. exception:: ResourceDenied
221
222 Subclass of :exc:`TestSkipped`. Raised when a resource (such as a network
223 connection) is not available. Raised by the :func:`requires` function.
224
225The :mod:`test.test_support` module defines the following constants:
226
227
228.. data:: verbose
229
230 :const:`True` when verbose output is enabled. Should be checked when more
231 detailed information is desired about a running test. *verbose* is set by
232 :mod:`test.regrtest`.
233
234
235.. data:: have_unicode
236
237 :const:`True` when Unicode support is available.
238
239
240.. data:: is_jython
241
242 :const:`True` if the running interpreter is Jython.
243
244
245.. data:: TESTFN
246
247 Set to the path that a temporary file may be created at. Any temporary that is
248 created should be closed and unlinked (removed).
249
250The :mod:`test.test_support` module defines the following functions:
251
252
253.. function:: forget(module_name)
254
255 Removes the module named *module_name* from ``sys.modules`` and deletes any
256 byte-compiled files of the module.
257
258
259.. function:: is_resource_enabled(resource)
260
261 Returns :const:`True` if *resource* is enabled and available. The list of
262 available resources is only set when :mod:`test.regrtest` is executing the
263 tests.
264
265
266.. function:: requires(resource[, msg])
267
268 Raises :exc:`ResourceDenied` if *resource* is not available. *msg* is the
269 argument to :exc:`ResourceDenied` if it is raised. Always returns true if called
270 by a function whose ``__name__`` is ``'__main__'``. Used when tests are executed
271 by :mod:`test.regrtest`.
272
273
274.. function:: findfile(filename)
275
276 Return the path to the file named *filename*. If no match is found *filename* is
277 returned. This does not equal a failure since it could be the path to the file.
278
279
280.. function:: run_unittest(*classes)
281
282 Execute :class:`unittest.TestCase` subclasses passed to the function. The
283 function scans the classes for methods starting with the prefix ``test_`` and
284 executes the tests individually.
285
286 It is also legal to pass strings as parameters; these should be keys in
287 ``sys.modules``. Each associated module will be scanned by
288 ``unittest.TestLoader.loadTestsFromModule()``. This is usually seen in the
289 following :func:`test_main` function::
290
291 def test_main():
292 test_support.run_unittest(__name__)
293
294 This will run all tests defined in the named module.
295
Georg Brandl8ec7f652007-08-15 14:28:01 +0000296
Nick Coghland2e09382008-09-11 12:11:06 +0000297.. function:: check_warnings()
Georg Brandld558f672007-08-24 18:27:43 +0000298
Nick Coghland2e09382008-09-11 12:11:06 +0000299 A convenience wrapper for ``warnings.catch_warnings()`` that makes
300 it easier to test that a warning was correctly raised with a single
301 assertion. It is approximately equivalent to calling
302 ``warnings.catch_warnings(record=True)``.
303
304 The main difference is that on entry to the context manager, a
305 :class:`WarningRecorder` instance is returned instead of a simple list.
306 The underlying warnings list is available via the recorder object's
307 :attr:`warnings` attribute, while the attributes of the last raised
308 warning are also accessible directly on the object. If no warning has
309 been raised, then the latter attributes will all be :const:`None`.
310
311 A :meth:`reset` method is also provided on the recorder object. This
312 method simply clears the warning list.
Georg Brandld558f672007-08-24 18:27:43 +0000313
Nick Coghlan38469e22008-07-13 12:23:47 +0000314 The context manager is used like this::
Georg Brandld558f672007-08-24 18:27:43 +0000315
Nick Coghland2e09382008-09-11 12:11:06 +0000316 with check_warnings() as w:
Nick Coghlan38469e22008-07-13 12:23:47 +0000317 warnings.simplefilter("always")
Georg Brandld558f672007-08-24 18:27:43 +0000318 warnings.warn("foo")
Nick Coghlan12c86602008-07-13 12:36:42 +0000319 assert str(w.message) == "foo"
Nick Coghlan38469e22008-07-13 12:23:47 +0000320 warnings.warn("bar")
Nick Coghlan12c86602008-07-13 12:36:42 +0000321 assert str(w.message) == "bar"
Nick Coghlan38469e22008-07-13 12:23:47 +0000322 assert str(w.warnings[0].message) == "foo"
323 assert str(w.warnings[1].message) == "bar"
Nick Coghland2e09382008-09-11 12:11:06 +0000324 w.reset()
325 assert len(w.warnings) == 0
Georg Brandld558f672007-08-24 18:27:43 +0000326
327 .. versionadded:: 2.6
328
329
330.. function:: captured_stdout()
331
Senthil Kumaran50706eb2010-05-18 03:23:43 +0000332 This is a context manager that runs the :keyword:`with` statement body using
Georg Brandld558f672007-08-24 18:27:43 +0000333 a :class:`StringIO.StringIO` object as sys.stdout. That object can be
Andrew M. Kuchlingf15ff462008-01-15 01:29:44 +0000334 retrieved using the ``as`` clause of the :keyword:`with` statement.
Georg Brandld558f672007-08-24 18:27:43 +0000335
336 Example use::
337
338 with captured_stdout() as s:
339 print "hello"
340 assert s.getvalue() == "hello"
341
342 .. versionadded:: 2.6
343
344
345The :mod:`test.test_support` module defines the following classes:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000346
347.. class:: TransientResource(exc[, **kwargs])
348
349 Instances are a context manager that raises :exc:`ResourceDenied` if the
350 specified exception type is raised. Any keyword arguments are treated as
351 attribute/value pairs to be compared against any exception raised within the
352 :keyword:`with` statement. Only if all pairs match properly against
353 attributes on the exception is :exc:`ResourceDenied` raised.
354
355 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000356.. class:: EnvironmentVarGuard()
357
358 Class used to temporarily set or unset environment variables. Instances can be
359 used as a context manager.
360
361 .. versionadded:: 2.6
362
363
364.. method:: EnvironmentVarGuard.set(envvar, value)
365
366 Temporarily set the environment variable ``envvar`` to the value of ``value``.
367
368
369.. method:: EnvironmentVarGuard.unset(envvar)
370
371 Temporarily unset the environment variable ``envvar``.
Nick Coghlan38469e22008-07-13 12:23:47 +0000372
Nick Coghland2e09382008-09-11 12:11:06 +0000373.. class:: WarningsRecorder()
374
375 Class used to record warnings for unit tests. See documentation of
376 :func:`check_warnings` above for more details.
377
378 .. versionadded:: 2.6
Nick Coghlan38469e22008-07-13 12:23:47 +0000379