blob: cc7ff4de0d305b5329fef15c7a6a557f9d68fce1 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`test` --- Regression tests package for Python
2===================================================
3
4.. module:: test
5 :synopsis: Regression tests package containing the testing suite for Python.
6.. sectionauthor:: Brett Cannon <brett@python.org>
7
8
9The :mod:`test` package contains all regression tests for Python as well as the
Nick Coghlan47384702009-04-22 16:13:36 +000010modules :mod:`test.support` and :mod:`test.regrtest`.
11:mod:`test.support` is used to enhance your tests while
Georg Brandl116aa622007-08-15 14:28:22 +000012:mod:`test.regrtest` drives the testing suite.
13
14Each module in the :mod:`test` package whose name starts with ``test_`` is a
15testing suite for a specific module or feature. All new tests should be written
16using the :mod:`unittest` or :mod:`doctest` module. Some older tests are
17written using a "traditional" testing style that compares output printed to
18``sys.stdout``; this style of test is considered deprecated.
19
20
21.. seealso::
22
23 Module :mod:`unittest`
24 Writing PyUnit regression tests.
25
26 Module :mod:`doctest`
27 Tests embedded in documentation strings.
28
29
30.. _writing-tests:
31
32Writing Unit Tests for the :mod:`test` package
33----------------------------------------------
34
Georg Brandl116aa622007-08-15 14:28:22 +000035It is preferred that tests that use the :mod:`unittest` module follow a few
36guidelines. One is to name the test module by starting it with ``test_`` and end
37it with the name of the module being tested. The test methods in the test module
38should start with ``test_`` and end with a description of what the method is
39testing. This is needed so that the methods are recognized by the test driver as
40test methods. Also, no documentation string for the method should be included. A
41comment (such as ``# Tests function returns only True or False``) should be used
42to provide documentation for test methods. This is done because documentation
43strings get printed out if they exist and thus what test is being run is not
44stated.
45
46A basic boilerplate is often used::
47
48 import unittest
Nick Coghlan47384702009-04-22 16:13:36 +000049 from test import support
Georg Brandl116aa622007-08-15 14:28:22 +000050
51 class MyTestCase1(unittest.TestCase):
52
53 # Only use setUp() and tearDown() if necessary
54
55 def setUp(self):
56 ... code to execute in preparation for tests ...
57
58 def tearDown(self):
59 ... code to execute to clean up after tests ...
60
61 def test_feature_one(self):
62 # Test feature one.
63 ... testing code ...
64
65 def test_feature_two(self):
66 # Test feature two.
67 ... testing code ...
68
69 ... more test methods ...
70
71 class MyTestCase2(unittest.TestCase):
72 ... same structure as MyTestCase1 ...
73
74 ... more test classes ...
75
76 def test_main():
Nick Coghlan47384702009-04-22 16:13:36 +000077 support.run_unittest(MyTestCase1,
Georg Brandl116aa622007-08-15 14:28:22 +000078 MyTestCase2,
79 ... list other tests ...
80 )
81
82 if __name__ == '__main__':
83 test_main()
84
85This boilerplate code allows the testing suite to be run by :mod:`test.regrtest`
86as well as on its own as a script.
87
88The goal for regression testing is to try to break code. This leads to a few
89guidelines to be followed:
90
91* The testing suite should exercise all classes, functions, and constants. This
92 includes not just the external API that is to be presented to the outside world
93 but also "private" code.
94
95* Whitebox testing (examining the code being tested when the tests are being
96 written) is preferred. Blackbox testing (testing only the published user
97 interface) is not complete enough to make sure all boundary and edge cases are
98 tested.
99
100* Make sure all possible values are tested including invalid ones. This makes
101 sure that not only all valid values are acceptable but also that improper values
102 are handled correctly.
103
104* Exhaust as many code paths as possible. Test where branching occurs and thus
105 tailor input to make sure as many different paths through the code are taken.
106
107* Add an explicit test for any bugs discovered for the tested code. This will
108 make sure that the error does not crop up again if the code is changed in the
109 future.
110
111* Make sure to clean up after your tests (such as close and remove all temporary
112 files).
113
114* If a test is dependent on a specific condition of the operating system then
115 verify the condition already exists before attempting the test.
116
117* Import as few modules as possible and do it as soon as possible. This
118 minimizes external dependencies of tests and also minimizes possible anomalous
119 behavior from side-effects of importing a module.
120
121* Try to maximize code reuse. On occasion, tests will vary by something as small
122 as what type of input is used. Minimize code duplication by subclassing a basic
123 test class with a class that specifies the input::
124
125 class TestFuncAcceptsSequences(unittest.TestCase):
126
127 func = mySuperWhammyFunction
128
129 def test_func(self):
130 self.func(self.arg)
131
132 class AcceptLists(TestFuncAcceptsSequences):
133 arg = [1,2,3]
134
135 class AcceptStrings(TestFuncAcceptsSequences):
136 arg = 'abc'
137
138 class AcceptTuples(TestFuncAcceptsSequences):
139 arg = (1,2,3)
140
141
142.. seealso::
143
144 Test Driven Development
145 A book by Kent Beck on writing tests before code.
146
147
148.. _regrtest:
149
150Running tests using :mod:`test.regrtest`
151----------------------------------------
152
153:mod:`test.regrtest` can be used as a script to drive Python's regression test
154suite. Running the script by itself automatically starts running all regression
155tests in the :mod:`test` package. It does this by finding all modules in the
156package whose name starts with ``test_``, importing them, and executing the
157function :func:`test_main` if present. The names of tests to execute may also be
158passed to the script. Specifying a single regression test (:program:`python
159regrtest.py` :option:`test_spam.py`) will minimize output and only print whether
160the test passed or failed and thus minimize output.
161
162Running :mod:`test.regrtest` directly allows what resources are available for
163tests to use to be set. You do this by using the :option:`-u` command-line
164option. Run :program:`python regrtest.py` :option:`-uall` to turn on all
165resources; specifying :option:`all` as an option for :option:`-u` enables all
166possible resources. If all but one resource is desired (a more common case), a
167comma-separated list of resources that are not desired may be listed after
168:option:`all`. The command :program:`python regrtest.py`
169:option:`-uall,-audio,-largefile` will run :mod:`test.regrtest` with all
170resources except the :option:`audio` and :option:`largefile` resources. For a
171list of all resources and more command-line options, run :program:`python
172regrtest.py` :option:`-h`.
173
174Some other ways to execute the regression tests depend on what platform the
175tests are being executed on. On Unix, you can run :program:`make` :option:`test`
176at the top-level directory where Python was built. On Windows, executing
177:program:`rt.bat` from your :file:`PCBuild` directory will run all regression
178tests.
179
180
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000181:mod:`test.support` --- Utility functions for tests
Georg Brandl7f01a132009-09-16 15:58:14 +0000182===================================================
Georg Brandl116aa622007-08-15 14:28:22 +0000183
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000184.. module:: test.support
Georg Brandl116aa622007-08-15 14:28:22 +0000185 :synopsis: Support for Python regression tests.
186
187
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000188The :mod:`test.support` module provides support for Python's regression
Georg Brandl116aa622007-08-15 14:28:22 +0000189tests.
190
191This module defines the following exceptions:
192
193
194.. exception:: TestFailed
195
196 Exception to be raised when a test fails. This is deprecated in favor of
197 :mod:`unittest`\ -based tests and :class:`unittest.TestCase`'s assertion
198 methods.
199
200
201.. exception:: TestSkipped
202
203 Subclass of :exc:`TestFailed`. Raised when a test is skipped. This occurs when a
204 needed resource (such as a network connection) is not available at the time of
205 testing.
206
207
208.. exception:: ResourceDenied
209
210 Subclass of :exc:`TestSkipped`. Raised when a resource (such as a network
211 connection) is not available. Raised by the :func:`requires` function.
212
Nick Coghlanb1304932008-07-13 12:25:08 +0000213The :mod:`test.support` module defines the following constants:
Georg Brandl116aa622007-08-15 14:28:22 +0000214
215
216.. data:: verbose
217
218 :const:`True` when verbose output is enabled. Should be checked when more
219 detailed information is desired about a running test. *verbose* is set by
220 :mod:`test.regrtest`.
221
222
Georg Brandl116aa622007-08-15 14:28:22 +0000223.. data:: is_jython
224
225 :const:`True` if the running interpreter is Jython.
226
227
228.. data:: TESTFN
229
230 Set to the path that a temporary file may be created at. Any temporary that is
231 created should be closed and unlinked (removed).
232
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000233The :mod:`test.support` module defines the following functions:
Georg Brandl116aa622007-08-15 14:28:22 +0000234
235
236.. function:: forget(module_name)
237
238 Removes the module named *module_name* from ``sys.modules`` and deletes any
239 byte-compiled files of the module.
240
241
242.. function:: is_resource_enabled(resource)
243
244 Returns :const:`True` if *resource* is enabled and available. The list of
245 available resources is only set when :mod:`test.regrtest` is executing the
246 tests.
247
248
Georg Brandl7f01a132009-09-16 15:58:14 +0000249.. function:: requires(resource, msg=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000250
251 Raises :exc:`ResourceDenied` if *resource* is not available. *msg* is the
252 argument to :exc:`ResourceDenied` if it is raised. Always returns true if called
253 by a function whose ``__name__`` is ``'__main__'``. Used when tests are executed
254 by :mod:`test.regrtest`.
255
256
257.. function:: findfile(filename)
258
259 Return the path to the file named *filename*. If no match is found *filename* is
260 returned. This does not equal a failure since it could be the path to the file.
261
262
263.. function:: run_unittest(*classes)
264
265 Execute :class:`unittest.TestCase` subclasses passed to the function. The
266 function scans the classes for methods starting with the prefix ``test_`` and
267 executes the tests individually.
268
269 It is also legal to pass strings as parameters; these should be keys in
270 ``sys.modules``. Each associated module will be scanned by
271 ``unittest.TestLoader.loadTestsFromModule()``. This is usually seen in the
272 following :func:`test_main` function::
273
274 def test_main():
Nick Coghlan47384702009-04-22 16:13:36 +0000275 support.run_unittest(__name__)
Georg Brandl116aa622007-08-15 14:28:22 +0000276
277 This will run all tests defined in the named module.
278
Georg Brandl116aa622007-08-15 14:28:22 +0000279
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000280.. function:: check_warnings()
Thomas Woutersed03b412007-08-28 21:37:11 +0000281
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000282 A convenience wrapper for ``warnings.catch_warnings()`` that makes
283 it easier to test that a warning was correctly raised with a single
284 assertion. It is approximately equivalent to calling
285 ``warnings.catch_warnings(record=True)``.
286
287 The main difference is that on entry to the context manager, a
288 :class:`WarningRecorder` instance is returned instead of a simple list.
289 The underlying warnings list is available via the recorder object's
290 :attr:`warnings` attribute, while the attributes of the last raised
291 warning are also accessible directly on the object. If no warning has
292 been raised, then the latter attributes will all be :const:`None`.
293
294 A :meth:`reset` method is also provided on the recorder object. This
295 method simply clears the warning list.
Thomas Woutersed03b412007-08-28 21:37:11 +0000296
Nick Coghlanb1304932008-07-13 12:25:08 +0000297 The context manager is used like this::
Thomas Woutersed03b412007-08-28 21:37:11 +0000298
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000299 with check_warnings() as w:
Nick Coghlanb1304932008-07-13 12:25:08 +0000300 warnings.simplefilter("always")
Thomas Woutersed03b412007-08-28 21:37:11 +0000301 warnings.warn("foo")
302 assert str(w.message) == "foo"
Nick Coghlanb1304932008-07-13 12:25:08 +0000303 warnings.warn("bar")
304 assert str(w.message) == "bar"
305 assert str(w.warnings[0].message) == "foo"
306 assert str(w.warnings[1].message) == "bar"
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000307 w.reset()
308 assert len(w.warnings) == 0
Thomas Woutersed03b412007-08-28 21:37:11 +0000309
Thomas Woutersed03b412007-08-28 21:37:11 +0000310
311.. function:: captured_stdout()
312
313 This is a context manager than runs the :keyword:`with` statement body using
314 a :class:`StringIO.StringIO` object as sys.stdout. That object can be
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000315 retrieved using the ``as`` clause of the :keyword:`with` statement.
Thomas Woutersed03b412007-08-28 21:37:11 +0000316
317 Example use::
318
319 with captured_stdout() as s:
Collin Winterc79461b2007-09-01 23:34:30 +0000320 print("hello")
Thomas Woutersed03b412007-08-28 21:37:11 +0000321 assert s.getvalue() == "hello"
322
Thomas Woutersed03b412007-08-28 21:37:11 +0000323
Nick Coghlanfce769e2009-04-11 14:30:59 +0000324.. function:: import_module(name, deprecated=False)
325
326 This function imports and returns the named module. Unlike a normal
327 import, this function raises :exc:`unittest.SkipTest` if the module
328 cannot be imported.
329
330 Module and package deprecation messages are suppressed during this import
331 if *deprecated* is :const:`True`.
332
333 .. versionadded:: 3.1
334
335
Nick Coghlan47384702009-04-22 16:13:36 +0000336.. function:: import_fresh_module(name, fresh=(), blocked=(), deprecated=False)
Nick Coghlanfce769e2009-04-11 14:30:59 +0000337
Nick Coghlan47384702009-04-22 16:13:36 +0000338 This function imports and returns a fresh copy of the named Python module
339 by removing the named module from ``sys.modules`` before doing the import.
340 Note that unlike :func:`reload`, the original module is not affected by
341 this operation.
342
343 *fresh* is an iterable of additional module names that are also removed
344 from the ``sys.modules`` cache before doing the import.
345
346 *blocked* is an iterable of module names that are replaced with :const:`0`
347 in the module cache during the import to ensure that attempts to import
348 them raise :exc:`ImportError`.
349
350 The named module and any modules named in the *fresh* and *blocked*
351 parameters are saved before starting the import and then reinserted into
352 ``sys.modules`` when the fresh import is complete.
Nick Coghlanfce769e2009-04-11 14:30:59 +0000353
354 Module and package deprecation messages are suppressed during this import
355 if *deprecated* is :const:`True`.
356
Nick Coghlan47384702009-04-22 16:13:36 +0000357 This function will raise :exc:`unittest.SkipTest` is the named module
358 cannot be imported.
359
360 Example use::
361
362 # Get copies of the warnings module for testing without
363 # affecting the version being used by the rest of the test suite
364 # One copy uses the C implementation, the other is forced to use
365 # the pure Python fallback implementation
366 py_warnings = import_fresh_module('warnings', blocked=['_warnings'])
367 c_warnings = import_fresh_module('warnings', fresh=['_warnings'])
368
Nick Coghlanfce769e2009-04-11 14:30:59 +0000369 .. versionadded:: 3.1
370
371
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000372The :mod:`test.support` module defines the following classes:
Georg Brandl116aa622007-08-15 14:28:22 +0000373
Georg Brandl7f01a132009-09-16 15:58:14 +0000374.. class:: TransientResource(exc, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000375
376 Instances are a context manager that raises :exc:`ResourceDenied` if the
377 specified exception type is raised. Any keyword arguments are treated as
378 attribute/value pairs to be compared against any exception raised within the
379 :keyword:`with` statement. Only if all pairs match properly against
380 attributes on the exception is :exc:`ResourceDenied` raised.
381
Georg Brandl116aa622007-08-15 14:28:22 +0000382
383.. class:: EnvironmentVarGuard()
384
385 Class used to temporarily set or unset environment variables. Instances can be
Walter Dörwald155374d2009-05-01 19:58:58 +0000386 used as a context manager and have a complete dictionary interface for
387 querying/modifying the underlying ``os.environ``. After exit from the context
388 manager all changes to environment variables done through this instance will
389 be rolled back.
Georg Brandl116aa622007-08-15 14:28:22 +0000390
Georg Brandl705d9d52009-05-05 09:29:50 +0000391 .. versionchanged:: 3.1
Walter Dörwald155374d2009-05-01 19:58:58 +0000392 Added dictionary interface.
Georg Brandl116aa622007-08-15 14:28:22 +0000393
394.. method:: EnvironmentVarGuard.set(envvar, value)
395
396 Temporarily set the environment variable ``envvar`` to the value of ``value``.
397
398
399.. method:: EnvironmentVarGuard.unset(envvar)
400
401 Temporarily unset the environment variable ``envvar``.
Nick Coghlanb1304932008-07-13 12:25:08 +0000402
Walter Dörwald155374d2009-05-01 19:58:58 +0000403
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000404.. class:: WarningsRecorder()
405
406 Class used to record warnings for unit tests. See documentation of
407 :func:`check_warnings` above for more details.
408