Debian Codegraph @

cpython27/Doc/library/test.rst

raw
1
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 <[email protected]>
8
9 .. 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
16
17 The :mod:`test` package contains all regression tests for Python as well as the
18 modules :mod:`test.support` and :mod:`test.regrtest`.
19 :mod:`test.support` is used to enhance your tests while
20 :mod:`test.regrtest` drives the testing suite.
21
22 Each module in the :mod:`test` package whose name starts with ``test_`` is a
23 testing suite for a specific module or feature. All new tests should be written
24 using the :mod:`unittest` or :mod:`doctest` module. Some older tests are
25 written 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
40 Writing Unit Tests for the :mod:`test` package
41 ----------------------------------------------
42
43 It is preferred that tests that use the :mod:`unittest` module follow a few
44 guidelines. One is to name the test module by starting it with ``test_`` and end
45 it with the name of the module being tested. The test methods in the test module
46 should start with ``test_`` and end with a description of what the method is
47 testing. This is needed so that the methods are recognized by the test driver as
48 test methods. Also, no documentation string for the method should be included. A
49 comment (such as ``# Tests function returns only True or False``) should be used
50 to provide documentation for test methods. This is done because documentation
51 strings get printed out if they exist and thus what test is being run is not
52 stated.
53
54 A basic boilerplate is often used::
55
56 import unittest
57 from test import 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 support.run_unittest(MyTestCase1,
86 MyTestCase2,
87 ... list other tests ...
88 )
89
90 if __name__ == '__main__':
91 test_main()
92
93 This boilerplate code allows the testing suite to be run by :mod:`test.regrtest`
94 as well as on its own as a script.
95
96 The goal for regression testing is to try to break code. This leads to a few
97 guidelines 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
101 world 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
106 are 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
110 values 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
131 basic 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
158 Running tests using the command-line interface
159 ----------------------------------------------
160
161 The :mod:`test.regrtest` module can be run as a script to drive Python's regression
162 test suite, thanks to the :option:`-m` option: :program:`python -m test.regrtest`.
163 Running the script by itself automatically starts running all regression
164 tests in the :mod:`test` package. It does this by finding all modules in the
165 package whose name starts with ``test_``, importing them, and executing the
166 function :func:`test_main` if present. The names of tests to execute may also
167 be passed to the script. Specifying a single regression test (:program:`python
168 -m test.regrtest test_spam`) will minimize output and only print whether
169 the test passed or failed and thus minimize output.
170
171 Running :mod:`test.regrtest` directly allows what resources are available for
172 tests to use to be set. You do this by using the ``-u`` command-line
173 option. Specifying ``all`` as the value for the ``-u`` option enables all
174 possible resources: :program:`python -m test.regrtest -uall`.
175 If all but one resource is desired (a more common case), a
176 comma-separated list of resources that are not desired may be listed after
177 ``all``. The command :program:`python -m test.regrtest -uall,-audio,-largefile`
178 will run :mod:`test.regrtest` with all resources except the ``audio`` and
179 ``largefile`` resources. For a list of all resources and more command-line
180 options, run :program:`python -m test.regrtest -h`.
181
182 Some other ways to execute the regression tests depend on what platform the
183 tests are being executed on. On Unix, you can run :program:`make test` at the
184 top-level directory where Python was built. On Windows, executing
185 :program:`rt.bat` from your :file:`PCBuild` directory will run all regression
186 tests.
187
188 .. versionchanged:: 2.7.14
189 The :mod:`test` package can be run as a script: :program:`python -m test`.
190 This works the same as running the :mod:`test.regrtest` module.
191
192
193 :mod:`test.support` --- Utility functions for tests
194 ===================================================
195
196 .. module:: test.support
197 :synopsis: Support for Python regression tests.
198
199 .. note::
200
201 The :mod:`test.test_support` module has been renamed to :mod:`test.support`
202 in Python 3.x and 2.7.14. The name ``test.test_support`` has been retained
203 as an alias in 2.7.
204
205 The :mod:`test.support` module provides support for Python's regression
206 tests.
207
208 This module defines the following exceptions:
209
210
211 .. exception:: TestFailed
212
213 Exception to be raised when a test fails. This is deprecated in favor of
214 :mod:`unittest`\ -based tests and :class:`unittest.TestCase`'s assertion
215 methods.
216
217
218 .. exception:: ResourceDenied
219
220 Subclass of :exc:`unittest.SkipTest`. Raised when a resource (such as a
221 network connection) is not available. Raised by the :func:`requires`
222 function.
223
224 The :mod:`test.support` module defines the following constants:
225
226
227 .. data:: verbose
228
229 :const:`True` when verbose output is enabled. Should be checked when more
230 detailed information is desired about a running test. *verbose* is set by
231 :mod:`test.regrtest`.
232
233
234 .. data:: have_unicode
235
236 :const:`True` when Unicode support is available.
237
238
239 .. data:: is_jython
240
241 :const:`True` if the running interpreter is Jython.
242
243
244 .. data:: TESTFN
245
246 Set to a name that is safe to use as the name of a temporary file. Any
247 temporary file that is created should be closed and unlinked (removed).
248
249
250 .. data:: TEST_HTTP_URL
251
252 Define the URL of a dedicated HTTP server for the network tests.
253
254 The :mod:`test.support` module defines the following functions:
255
256
257 .. function:: forget(module_name)
258
259 Remove the module named *module_name* from ``sys.modules`` and delete any
260 byte-compiled files of the module.
261
262
263 .. function:: is_resource_enabled(resource)
264
265 Return :const:`True` if *resource* is enabled and available. The list of
266 available resources is only set when :mod:`test.regrtest` is executing the
267 tests.
268
269
270 .. function:: requires(resource[, msg])
271
272 Raise :exc:`ResourceDenied` if *resource* is not available. *msg* is the
273 argument to :exc:`ResourceDenied` if it is raised. Always returns
274 :const:`True` if called by a function whose ``__name__`` is ``'__main__'``.
275 Used when tests are executed by :mod:`test.regrtest`.
276
277
278 .. function:: findfile(filename)
279
280 Return the path to the file named *filename*. If no match is found
281 *filename* is returned. This does not equal a failure since it could be the
282 path to the file.
283
284
285 .. function:: run_unittest(*classes)
286
287 Execute :class:`unittest.TestCase` subclasses passed to the function. The
288 function scans the classes for methods starting with the prefix ``test_``
289 and executes the tests individually.
290
291 It is also legal to pass strings as parameters; these should be keys in
292 ``sys.modules``. Each associated module will be scanned by
293 ``unittest.TestLoader.loadTestsFromModule()``. This is usually seen in the
294 following :func:`test_main` function::
295
296 def test_main():
297 support.run_unittest(__name__)
298
299 This will run all tests defined in the named module.
300
301
302 .. function:: check_warnings(*filters, quiet=True)
303
304 A convenience wrapper for :func:`warnings.catch_warnings()` that makes it
305 easier to test that a warning was correctly raised. It is approximately
306 equivalent to calling ``warnings.catch_warnings(record=True)`` with
307 :meth:`warnings.simplefilter` set to ``always`` and with the option to
308 automatically validate the results that are recorded.
309
310 ``check_warnings`` accepts 2-tuples of the form ``("message regexp",
311 WarningCategory)`` as positional arguments. If one or more *filters* are
312 provided, or if the optional keyword argument *quiet* is :const:`False`,
313 it checks to make sure the warnings are as expected: each specified filter
314 must match at least one of the warnings raised by the enclosed code or the
315 test fails, and if any warnings are raised that do not match any of the
316 specified filters the test fails. To disable the first of these checks,
317 set *quiet* to :const:`True`.
318
319 If no arguments are specified, it defaults to::
320
321 check_warnings(("", Warning), quiet=True)
322
323 In this case all warnings are caught and no errors are raised.
324
325 On entry to the context manager, a :class:`WarningRecorder` instance is
326 returned. The underlying warnings list from
327 :func:`~warnings.catch_warnings` is available via the recorder object's
328 :attr:`warnings` attribute. As a convenience, the attributes of the object
329 representing the most recent warning can also be accessed directly through
330 the recorder object (see example below). If no warning has been raised,
331 then any of the attributes that would otherwise be expected on an object
332 representing a warning will return :const:`None`.
333
334 The recorder object also has a :meth:`reset` method, which clears the
335 warnings list.
336
337 The context manager is designed to be used like this::
338
339 with check_warnings(("assertion is always true", SyntaxWarning),
340 ("", UserWarning)):
341 exec('assert(False, "Hey!")')
342 warnings.warn(UserWarning("Hide me!"))
343
344 In this case if either warning was not raised, or some other warning was
345 raised, :func:`check_warnings` would raise an error.
346
347 When a test needs to look more deeply into the warnings, rather than
348 just checking whether or not they occurred, code like this can be used::
349
350 with check_warnings(quiet=True) as w:
351 warnings.warn("foo")
352 assert str(w.args[0]) == "foo"
353 warnings.warn("bar")
354 assert str(w.args[0]) == "bar"
355 assert str(w.warnings[0].args[0]) == "foo"
356 assert str(w.warnings[1].args[0]) == "bar"
357 w.reset()
358 assert len(w.warnings) == 0
359
360 Here all warnings will be caught, and the test code tests the captured
361 warnings directly.
362
363 .. versionadded:: 2.6
364 .. versionchanged:: 2.7
365 New optional arguments *filters* and *quiet*.
366
367
368 .. function:: check_py3k_warnings(*filters, quiet=False)
369
370 Similar to :func:`check_warnings`, but for Python 3 compatibility warnings.
371 If ``sys.py3kwarning == 1``, it checks if the warning is effectively raised.
372 If ``sys.py3kwarning == 0``, it checks that no warning is raised. It
373 accepts 2-tuples of the form ``("message regexp", WarningCategory)`` as
374 positional arguments. When the optional keyword argument *quiet* is
375 :const:`True`, it does not fail if a filter catches nothing. Without
376 arguments, it defaults to::
377
378 check_py3k_warnings(("", DeprecationWarning), quiet=False)
379
380 .. versionadded:: 2.7
381
382
383 .. function:: captured_stdout()
384
385 This is a context manager that runs the :keyword:`with` statement body using
386 a :class:`StringIO.StringIO` object as sys.stdout. That object can be
387 retrieved using the ``as`` clause of the :keyword:`with` statement.
388
389 Example use::
390
391 with captured_stdout() as s:
392 print "hello"
393 assert s.getvalue() == "hello\n"
394
395 .. versionadded:: 2.6
396
397
398 .. function:: import_module(name, deprecated=False)
399
400 This function imports and returns the named module. Unlike a normal
401 import, this function raises :exc:`unittest.SkipTest` if the module
402 cannot be imported.
403
404 Module and package deprecation messages are suppressed during this import
405 if *deprecated* is :const:`True`.
406
407 .. versionadded:: 2.7
408
409
410 .. function:: import_fresh_module(name, fresh=(), blocked=(), deprecated=False)
411
412 This function imports and returns a fresh copy of the named Python module
413 by removing the named module from ``sys.modules`` before doing the import.
414 Note that unlike :func:`reload`, the original module is not affected by
415 this operation.
416
417 *fresh* is an iterable of additional module names that are also removed
418 from the ``sys.modules`` cache before doing the import.
419
420 *blocked* is an iterable of module names that are replaced with :const:`0`
421 in the module cache during the import to ensure that attempts to import
422 them raise :exc:`ImportError`.
423
424 The named module and any modules named in the *fresh* and *blocked*
425 parameters are saved before starting the import and then reinserted into
426 ``sys.modules`` when the fresh import is complete.
427
428 Module and package deprecation messages are suppressed during this import
429 if *deprecated* is :const:`True`.
430
431 This function will raise :exc:`unittest.SkipTest` if the named module
432 cannot be imported.
433
434 Example use::
435
436 # Get copies of the warnings module for testing without
437 # affecting the version being used by the rest of the test suite
438 # One copy uses the C implementation, the other is forced to use
439 # the pure Python fallback implementation
440 py_warnings = import_fresh_module('warnings', blocked=['_warnings'])
441 c_warnings = import_fresh_module('warnings', fresh=['_warnings'])
442
443 .. versionadded:: 2.7
444
445
446 The :mod:`test.support` module defines the following classes:
447
448 .. class:: TransientResource(exc[, **kwargs])
449
450 Instances are a context manager that raises :exc:`ResourceDenied` if the
451 specified exception type is raised. Any keyword arguments are treated as
452 attribute/value pairs to be compared against any exception raised within the
453 :keyword:`with` statement. Only if all pairs match properly against
454 attributes on the exception is :exc:`ResourceDenied` raised.
455
456 .. versionadded:: 2.6
457 .. class:: EnvironmentVarGuard()
458
459 Class used to temporarily set or unset environment variables. Instances can
460 be used as a context manager and have a complete dictionary interface for
461 querying/modifying the underlying ``os.environ``. After exit from the
462 context manager all changes to environment variables done through this
463 instance will be rolled back.
464
465 .. versionadded:: 2.6
466 .. versionchanged:: 2.7
467 Added dictionary interface.
468
469
470 .. method:: EnvironmentVarGuard.set(envvar, value)
471
472 Temporarily set the environment variable ``envvar`` to the value of
473 ``value``.
474
475
476 .. method:: EnvironmentVarGuard.unset(envvar)
477
478 Temporarily unset the environment variable ``envvar``.
479
480
481 .. class:: WarningsRecorder()
482
483 Class used to record warnings for unit tests. See documentation of
484 :func:`check_warnings` above for more details.
485
486 .. versionadded:: 2.6