blob: 0b1610986040cc8765da7fa8c842ad4f65dfb78c [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
Brett Cannonc14968f2010-07-23 12:03:37 +00008.. note::
9 The :mod:`test` package is meant for internal use by Python only. It is
10 documented for the benefit of the core developers of Python. Any use of
11 this package outside of Python's standard library is discouraged as code
12 mentioned here can change or be removed without notice between releases of
13 Python.
14
Georg Brandl116aa622007-08-15 14:28:22 +000015
16The :mod:`test` package contains all regression tests for Python as well as the
Nick Coghlan47384702009-04-22 16:13:36 +000017modules :mod:`test.support` and :mod:`test.regrtest`.
18:mod:`test.support` is used to enhance your tests while
Georg Brandl116aa622007-08-15 14:28:22 +000019:mod:`test.regrtest` drives the testing suite.
20
21Each module in the :mod:`test` package whose name starts with ``test_`` is a
22testing suite for a specific module or feature. All new tests should be written
23using the :mod:`unittest` or :mod:`doctest` module. Some older tests are
24written using a "traditional" testing style that compares output printed to
25``sys.stdout``; this style of test is considered deprecated.
26
27
28.. seealso::
29
30 Module :mod:`unittest`
31 Writing PyUnit regression tests.
32
33 Module :mod:`doctest`
34 Tests embedded in documentation strings.
35
36
37.. _writing-tests:
38
39Writing Unit Tests for the :mod:`test` package
40----------------------------------------------
41
Georg Brandl116aa622007-08-15 14:28:22 +000042It is preferred that tests that use the :mod:`unittest` module follow a few
43guidelines. One is to name the test module by starting it with ``test_`` and end
44it with the name of the module being tested. The test methods in the test module
45should start with ``test_`` and end with a description of what the method is
46testing. This is needed so that the methods are recognized by the test driver as
47test methods. Also, no documentation string for the method should be included. A
48comment (such as ``# Tests function returns only True or False``) should be used
49to provide documentation for test methods. This is done because documentation
50strings get printed out if they exist and thus what test is being run is not
51stated.
52
53A basic boilerplate is often used::
54
55 import unittest
Nick Coghlan47384702009-04-22 16:13:36 +000056 from test import support
Georg Brandl116aa622007-08-15 14:28:22 +000057
58 class MyTestCase1(unittest.TestCase):
59
60 # Only use setUp() and tearDown() if necessary
61
62 def setUp(self):
63 ... code to execute in preparation for tests ...
64
65 def tearDown(self):
66 ... code to execute to clean up after tests ...
67
68 def test_feature_one(self):
69 # Test feature one.
70 ... testing code ...
71
72 def test_feature_two(self):
73 # Test feature two.
74 ... testing code ...
75
76 ... more test methods ...
77
78 class MyTestCase2(unittest.TestCase):
79 ... same structure as MyTestCase1 ...
80
81 ... more test classes ...
82
83 def test_main():
Nick Coghlan47384702009-04-22 16:13:36 +000084 support.run_unittest(MyTestCase1,
Georg Brandl116aa622007-08-15 14:28:22 +000085 MyTestCase2,
86 ... list other tests ...
87 )
88
89 if __name__ == '__main__':
90 test_main()
91
92This boilerplate code allows the testing suite to be run by :mod:`test.regrtest`
93as well as on its own as a script.
94
95The goal for regression testing is to try to break code. This leads to a few
96guidelines to be followed:
97
98* The testing suite should exercise all classes, functions, and constants. This
99 includes not just the external API that is to be presented to the outside world
100 but also "private" code.
101
102* Whitebox testing (examining the code being tested when the tests are being
103 written) is preferred. Blackbox testing (testing only the published user
104 interface) is not complete enough to make sure all boundary and edge cases are
105 tested.
106
107* Make sure all possible values are tested including invalid ones. This makes
108 sure that not only all valid values are acceptable but also that improper values
109 are handled correctly.
110
111* Exhaust as many code paths as possible. Test where branching occurs and thus
112 tailor input to make sure as many different paths through the code are taken.
113
114* Add an explicit test for any bugs discovered for the tested code. This will
115 make sure that the error does not crop up again if the code is changed in the
116 future.
117
118* Make sure to clean up after your tests (such as close and remove all temporary
119 files).
120
121* If a test is dependent on a specific condition of the operating system then
122 verify the condition already exists before attempting the test.
123
124* Import as few modules as possible and do it as soon as possible. This
125 minimizes external dependencies of tests and also minimizes possible anomalous
126 behavior from side-effects of importing a module.
127
128* Try to maximize code reuse. On occasion, tests will vary by something as small
129 as what type of input is used. Minimize code duplication by subclassing a basic
130 test class with a class that specifies the input::
131
132 class TestFuncAcceptsSequences(unittest.TestCase):
133
134 func = mySuperWhammyFunction
135
136 def test_func(self):
137 self.func(self.arg)
138
139 class AcceptLists(TestFuncAcceptsSequences):
140 arg = [1,2,3]
141
142 class AcceptStrings(TestFuncAcceptsSequences):
143 arg = 'abc'
144
145 class AcceptTuples(TestFuncAcceptsSequences):
146 arg = (1,2,3)
147
148
149.. seealso::
150
151 Test Driven Development
152 A book by Kent Beck on writing tests before code.
153
154
155.. _regrtest:
156
157Running tests using :mod:`test.regrtest`
158----------------------------------------
159
160:mod:`test.regrtest` can be used as a script to drive Python's regression test
161suite. Running the script by itself automatically starts running all regression
162tests in the :mod:`test` package. It does this by finding all modules in the
163package whose name starts with ``test_``, importing them, and executing the
164function :func:`test_main` if present. The names of tests to execute may also be
165passed to the script. Specifying a single regression test (:program:`python
166regrtest.py` :option:`test_spam.py`) will minimize output and only print whether
167the test passed or failed and thus minimize output.
168
169Running :mod:`test.regrtest` directly allows what resources are available for
170tests to use to be set. You do this by using the :option:`-u` command-line
171option. Run :program:`python regrtest.py` :option:`-uall` to turn on all
172resources; specifying :option:`all` as an option for :option:`-u` enables all
173possible resources. If all but one resource is desired (a more common case), a
174comma-separated list of resources that are not desired may be listed after
175:option:`all`. The command :program:`python regrtest.py`
176:option:`-uall,-audio,-largefile` will run :mod:`test.regrtest` with all
177resources except the :option:`audio` and :option:`largefile` resources. For a
178list of all resources and more command-line options, run :program:`python
179regrtest.py` :option:`-h`.
180
181Some other ways to execute the regression tests depend on what platform the
182tests are being executed on. On Unix, you can run :program:`make` :option:`test`
183at the top-level directory where Python was built. On Windows, executing
184:program:`rt.bat` from your :file:`PCBuild` directory will run all regression
185tests.
186
187
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000188:mod:`test.support` --- Utility functions for tests
Georg Brandlb044b2a2009-09-16 16:05:59 +0000189===================================================
Georg Brandl116aa622007-08-15 14:28:22 +0000190
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000191.. module:: test.support
Georg Brandl116aa622007-08-15 14:28:22 +0000192 :synopsis: Support for Python regression tests.
193
194
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000195The :mod:`test.support` module provides support for Python's regression
Georg Brandl116aa622007-08-15 14:28:22 +0000196tests.
197
198This module defines the following exceptions:
199
200
201.. exception:: TestFailed
202
203 Exception to be raised when a test fails. This is deprecated in favor of
204 :mod:`unittest`\ -based tests and :class:`unittest.TestCase`'s assertion
205 methods.
206
207
208.. exception:: TestSkipped
209
210 Subclass of :exc:`TestFailed`. Raised when a test is skipped. This occurs when a
211 needed resource (such as a network connection) is not available at the time of
212 testing.
213
214
215.. exception:: ResourceDenied
216
217 Subclass of :exc:`TestSkipped`. Raised when a resource (such as a network
218 connection) is not available. Raised by the :func:`requires` function.
219
Nick Coghlanb1304932008-07-13 12:25:08 +0000220The :mod:`test.support` module defines the following constants:
Georg Brandl116aa622007-08-15 14:28:22 +0000221
222
223.. data:: verbose
224
225 :const:`True` when verbose output is enabled. Should be checked when more
226 detailed information is desired about a running test. *verbose* is set by
227 :mod:`test.regrtest`.
228
229
Georg Brandl116aa622007-08-15 14:28:22 +0000230.. data:: is_jython
231
232 :const:`True` if the running interpreter is Jython.
233
234
235.. data:: TESTFN
236
237 Set to the path that a temporary file may be created at. Any temporary that is
238 created should be closed and unlinked (removed).
239
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000240The :mod:`test.support` module defines the following functions:
Georg Brandl116aa622007-08-15 14:28:22 +0000241
242
243.. function:: forget(module_name)
244
245 Removes the module named *module_name* from ``sys.modules`` and deletes any
246 byte-compiled files of the module.
247
248
249.. function:: is_resource_enabled(resource)
250
251 Returns :const:`True` if *resource* is enabled and available. The list of
252 available resources is only set when :mod:`test.regrtest` is executing the
253 tests.
254
255
Georg Brandlb044b2a2009-09-16 16:05:59 +0000256.. function:: requires(resource, msg=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000257
258 Raises :exc:`ResourceDenied` if *resource* is not available. *msg* is the
259 argument to :exc:`ResourceDenied` if it is raised. Always returns true if called
260 by a function whose ``__name__`` is ``'__main__'``. Used when tests are executed
261 by :mod:`test.regrtest`.
262
263
264.. function:: findfile(filename)
265
266 Return the path to the file named *filename*. If no match is found *filename* is
267 returned. This does not equal a failure since it could be the path to the file.
268
269
270.. function:: run_unittest(*classes)
271
272 Execute :class:`unittest.TestCase` subclasses passed to the function. The
273 function scans the classes for methods starting with the prefix ``test_`` and
274 executes the tests individually.
275
276 It is also legal to pass strings as parameters; these should be keys in
277 ``sys.modules``. Each associated module will be scanned by
278 ``unittest.TestLoader.loadTestsFromModule()``. This is usually seen in the
279 following :func:`test_main` function::
280
281 def test_main():
Nick Coghlan47384702009-04-22 16:13:36 +0000282 support.run_unittest(__name__)
Georg Brandl116aa622007-08-15 14:28:22 +0000283
284 This will run all tests defined in the named module.
285
Georg Brandl116aa622007-08-15 14:28:22 +0000286
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000287.. function:: check_warnings()
Thomas Woutersed03b412007-08-28 21:37:11 +0000288
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000289 A convenience wrapper for ``warnings.catch_warnings()`` that makes
290 it easier to test that a warning was correctly raised with a single
291 assertion. It is approximately equivalent to calling
292 ``warnings.catch_warnings(record=True)``.
293
294 The main difference is that on entry to the context manager, a
295 :class:`WarningRecorder` instance is returned instead of a simple list.
296 The underlying warnings list is available via the recorder object's
297 :attr:`warnings` attribute, while the attributes of the last raised
298 warning are also accessible directly on the object. If no warning has
299 been raised, then the latter attributes will all be :const:`None`.
300
301 A :meth:`reset` method is also provided on the recorder object. This
302 method simply clears the warning list.
Thomas Woutersed03b412007-08-28 21:37:11 +0000303
Nick Coghlanb1304932008-07-13 12:25:08 +0000304 The context manager is used like this::
Thomas Woutersed03b412007-08-28 21:37:11 +0000305
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000306 with check_warnings() as w:
Nick Coghlanb1304932008-07-13 12:25:08 +0000307 warnings.simplefilter("always")
Thomas Woutersed03b412007-08-28 21:37:11 +0000308 warnings.warn("foo")
309 assert str(w.message) == "foo"
Nick Coghlanb1304932008-07-13 12:25:08 +0000310 warnings.warn("bar")
311 assert str(w.message) == "bar"
312 assert str(w.warnings[0].message) == "foo"
313 assert str(w.warnings[1].message) == "bar"
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000314 w.reset()
315 assert len(w.warnings) == 0
Thomas Woutersed03b412007-08-28 21:37:11 +0000316
Thomas Woutersed03b412007-08-28 21:37:11 +0000317
318.. function:: captured_stdout()
319
Senthil Kumaran5c3ef062010-05-18 03:28:44 +0000320 This is a context manager that runs the :keyword:`with` statement body using
Thomas Woutersed03b412007-08-28 21:37:11 +0000321 a :class:`StringIO.StringIO` object as sys.stdout. That object can be
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000322 retrieved using the ``as`` clause of the :keyword:`with` statement.
Thomas Woutersed03b412007-08-28 21:37:11 +0000323
324 Example use::
325
326 with captured_stdout() as s:
Collin Winterc79461b2007-09-01 23:34:30 +0000327 print("hello")
Thomas Woutersed03b412007-08-28 21:37:11 +0000328 assert s.getvalue() == "hello"
329
Thomas Woutersed03b412007-08-28 21:37:11 +0000330
Nick Coghlanfce769e2009-04-11 14:30:59 +0000331.. function:: import_module(name, deprecated=False)
332
333 This function imports and returns the named module. Unlike a normal
334 import, this function raises :exc:`unittest.SkipTest` if the module
335 cannot be imported.
336
337 Module and package deprecation messages are suppressed during this import
338 if *deprecated* is :const:`True`.
339
340 .. versionadded:: 3.1
341
342
Nick Coghlan47384702009-04-22 16:13:36 +0000343.. function:: import_fresh_module(name, fresh=(), blocked=(), deprecated=False)
Nick Coghlanfce769e2009-04-11 14:30:59 +0000344
Nick Coghlan47384702009-04-22 16:13:36 +0000345 This function imports and returns a fresh copy of the named Python module
346 by removing the named module from ``sys.modules`` before doing the import.
347 Note that unlike :func:`reload`, the original module is not affected by
348 this operation.
349
350 *fresh* is an iterable of additional module names that are also removed
351 from the ``sys.modules`` cache before doing the import.
352
353 *blocked* is an iterable of module names that are replaced with :const:`0`
354 in the module cache during the import to ensure that attempts to import
355 them raise :exc:`ImportError`.
356
357 The named module and any modules named in the *fresh* and *blocked*
358 parameters are saved before starting the import and then reinserted into
359 ``sys.modules`` when the fresh import is complete.
Nick Coghlanfce769e2009-04-11 14:30:59 +0000360
361 Module and package deprecation messages are suppressed during this import
362 if *deprecated* is :const:`True`.
363
Nick Coghlan47384702009-04-22 16:13:36 +0000364 This function will raise :exc:`unittest.SkipTest` is the named module
365 cannot be imported.
366
367 Example use::
368
369 # Get copies of the warnings module for testing without
370 # affecting the version being used by the rest of the test suite
371 # One copy uses the C implementation, the other is forced to use
372 # the pure Python fallback implementation
373 py_warnings = import_fresh_module('warnings', blocked=['_warnings'])
374 c_warnings = import_fresh_module('warnings', fresh=['_warnings'])
375
Nick Coghlanfce769e2009-04-11 14:30:59 +0000376 .. versionadded:: 3.1
377
378
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000379The :mod:`test.support` module defines the following classes:
Georg Brandl116aa622007-08-15 14:28:22 +0000380
Georg Brandlb044b2a2009-09-16 16:05:59 +0000381.. class:: TransientResource(exc, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000382
383 Instances are a context manager that raises :exc:`ResourceDenied` if the
384 specified exception type is raised. Any keyword arguments are treated as
385 attribute/value pairs to be compared against any exception raised within the
386 :keyword:`with` statement. Only if all pairs match properly against
387 attributes on the exception is :exc:`ResourceDenied` raised.
388
Georg Brandl116aa622007-08-15 14:28:22 +0000389
390.. class:: EnvironmentVarGuard()
391
392 Class used to temporarily set or unset environment variables. Instances can be
Walter Dörwald155374d2009-05-01 19:58:58 +0000393 used as a context manager and have a complete dictionary interface for
394 querying/modifying the underlying ``os.environ``. After exit from the context
395 manager all changes to environment variables done through this instance will
396 be rolled back.
Georg Brandl116aa622007-08-15 14:28:22 +0000397
Georg Brandl705d9d52009-05-05 09:29:50 +0000398 .. versionchanged:: 3.1
Walter Dörwald155374d2009-05-01 19:58:58 +0000399 Added dictionary interface.
Georg Brandl116aa622007-08-15 14:28:22 +0000400
401.. method:: EnvironmentVarGuard.set(envvar, value)
402
403 Temporarily set the environment variable ``envvar`` to the value of ``value``.
404
405
406.. method:: EnvironmentVarGuard.unset(envvar)
407
408 Temporarily unset the environment variable ``envvar``.
Nick Coghlanb1304932008-07-13 12:25:08 +0000409
Walter Dörwald155374d2009-05-01 19:58:58 +0000410
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000411.. class:: WarningsRecorder()
412
413 Class used to record warnings for unit tests. See documentation of
414 :func:`check_warnings` above for more details.
415