blob: 95d7f54ba4425350105f4d882c38af079f257da9 [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.
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04006
Georg Brandl116aa622007-08-15 14:28:22 +00007.. sectionauthor:: Brett Cannon <brett@python.org>
8
Antoine Pitrou197c9c92010-12-18 12:33:06 +00009.. note::
Antoine Pitrou36730e82010-12-12 18:25:25 +000010 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.
Brett Cannon3a4e50c2010-07-23 11:31:31 +000015
Terry Jan Reedyfa089b92016-06-11 15:02:54 -040016--------------
Georg Brandl116aa622007-08-15 14:28:22 +000017
18The :mod:`test` package contains all regression tests for Python as well as the
Nick Coghlan47384702009-04-22 16:13:36 +000019modules :mod:`test.support` and :mod:`test.regrtest`.
20:mod:`test.support` is used to enhance your tests while
Georg Brandl116aa622007-08-15 14:28:22 +000021:mod:`test.regrtest` drives the testing suite.
22
23Each module in the :mod:`test` package whose name starts with ``test_`` is a
24testing suite for a specific module or feature. All new tests should be written
25using the :mod:`unittest` or :mod:`doctest` module. Some older tests are
26written using a "traditional" testing style that compares output printed to
27``sys.stdout``; this style of test is considered deprecated.
28
29
30.. seealso::
31
32 Module :mod:`unittest`
33 Writing PyUnit regression tests.
34
35 Module :mod:`doctest`
36 Tests embedded in documentation strings.
37
38
39.. _writing-tests:
40
41Writing Unit Tests for the :mod:`test` package
42----------------------------------------------
43
Georg Brandl116aa622007-08-15 14:28:22 +000044It is preferred that tests that use the :mod:`unittest` module follow a few
45guidelines. One is to name the test module by starting it with ``test_`` and end
46it with the name of the module being tested. The test methods in the test module
47should start with ``test_`` and end with a description of what the method is
48testing. This is needed so that the methods are recognized by the test driver as
49test methods. Also, no documentation string for the method should be included. A
50comment (such as ``# Tests function returns only True or False``) should be used
51to provide documentation for test methods. This is done because documentation
52strings get printed out if they exist and thus what test is being run is not
53stated.
54
55A basic boilerplate is often used::
56
57 import unittest
Nick Coghlan47384702009-04-22 16:13:36 +000058 from test import support
Georg Brandl116aa622007-08-15 14:28:22 +000059
60 class MyTestCase1(unittest.TestCase):
61
62 # Only use setUp() and tearDown() if necessary
63
64 def setUp(self):
65 ... code to execute in preparation for tests ...
66
67 def tearDown(self):
68 ... code to execute to clean up after tests ...
69
70 def test_feature_one(self):
71 # Test feature one.
72 ... testing code ...
73
74 def test_feature_two(self):
75 # Test feature two.
76 ... testing code ...
77
78 ... more test methods ...
79
80 class MyTestCase2(unittest.TestCase):
81 ... same structure as MyTestCase1 ...
82
83 ... more test classes ...
84
Georg Brandl116aa622007-08-15 14:28:22 +000085 if __name__ == '__main__':
R David Murray78fc25c2012-04-09 08:55:42 -040086 unittest.main()
Georg Brandl116aa622007-08-15 14:28:22 +000087
R David Murray78fc25c2012-04-09 08:55:42 -040088This code pattern allows the testing suite to be run by :mod:`test.regrtest`,
89on its own as a script that supports the :mod:`unittest` CLI, or via the
Georg Brandl93a56cd2014-10-30 22:25:41 +010090``python -m unittest`` CLI.
Georg Brandl116aa622007-08-15 14:28:22 +000091
92The goal for regression testing is to try to break code. This leads to a few
93guidelines to be followed:
94
95* The testing suite should exercise all classes, functions, and constants. This
Florent Xicluna53b506be2010-03-18 20:00:57 +000096 includes not just the external API that is to be presented to the outside
97 world but also "private" code.
Georg Brandl116aa622007-08-15 14:28:22 +000098
99* Whitebox testing (examining the code being tested when the tests are being
100 written) is preferred. Blackbox testing (testing only the published user
Florent Xicluna53b506be2010-03-18 20:00:57 +0000101 interface) is not complete enough to make sure all boundary and edge cases
102 are tested.
Georg Brandl116aa622007-08-15 14:28:22 +0000103
104* Make sure all possible values are tested including invalid ones. This makes
Florent Xicluna53b506be2010-03-18 20:00:57 +0000105 sure that not only all valid values are acceptable but also that improper
106 values are handled correctly.
Georg Brandl116aa622007-08-15 14:28:22 +0000107
108* Exhaust as many code paths as possible. Test where branching occurs and thus
109 tailor input to make sure as many different paths through the code are taken.
110
111* Add an explicit test for any bugs discovered for the tested code. This will
112 make sure that the error does not crop up again if the code is changed in the
113 future.
114
115* Make sure to clean up after your tests (such as close and remove all temporary
116 files).
117
118* If a test is dependent on a specific condition of the operating system then
119 verify the condition already exists before attempting the test.
120
121* Import as few modules as possible and do it as soon as possible. This
122 minimizes external dependencies of tests and also minimizes possible anomalous
123 behavior from side-effects of importing a module.
124
125* Try to maximize code reuse. On occasion, tests will vary by something as small
Florent Xicluna53b506be2010-03-18 20:00:57 +0000126 as what type of input is used. Minimize code duplication by subclassing a
127 basic test class with a class that specifies the input::
Georg Brandl116aa622007-08-15 14:28:22 +0000128
R David Murray78fc25c2012-04-09 08:55:42 -0400129 class TestFuncAcceptsSequencesMixin:
Georg Brandl116aa622007-08-15 14:28:22 +0000130
131 func = mySuperWhammyFunction
132
133 def test_func(self):
134 self.func(self.arg)
135
R David Murray78fc25c2012-04-09 08:55:42 -0400136 class AcceptLists(TestFuncAcceptsSequencesMixin, unittest.TestCase):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000137 arg = [1, 2, 3]
Georg Brandl116aa622007-08-15 14:28:22 +0000138
R David Murray78fc25c2012-04-09 08:55:42 -0400139 class AcceptStrings(TestFuncAcceptsSequencesMixin, unittest.TestCase):
Georg Brandl116aa622007-08-15 14:28:22 +0000140 arg = 'abc'
141
R David Murray78fc25c2012-04-09 08:55:42 -0400142 class AcceptTuples(TestFuncAcceptsSequencesMixin, unittest.TestCase):
Florent Xiclunab14930c2010-03-13 15:26:44 +0000143 arg = (1, 2, 3)
Georg Brandl116aa622007-08-15 14:28:22 +0000144
R David Murray78fc25c2012-04-09 08:55:42 -0400145 When using this pattern, remember that all classes that inherit from
Georg Brandl93a56cd2014-10-30 22:25:41 +0100146 :class:`unittest.TestCase` are run as tests. The :class:`Mixin` class in the example above
R David Murray78fc25c2012-04-09 08:55:42 -0400147 does not have any data and so can't be run by itself, thus it does not
Georg Brandl93a56cd2014-10-30 22:25:41 +0100148 inherit from :class:`unittest.TestCase`.
R David Murray78fc25c2012-04-09 08:55:42 -0400149
Georg Brandl116aa622007-08-15 14:28:22 +0000150
151.. seealso::
152
153 Test Driven Development
154 A book by Kent Beck on writing tests before code.
155
156
157.. _regrtest:
158
Éric Araujo1d55c7e2010-12-16 01:40:26 +0000159Running tests using the command-line interface
160----------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000161
Éric Araujo1d55c7e2010-12-16 01:40:26 +0000162The :mod:`test` package can be run as a script to drive Python's regression
163test suite, thanks to the :option:`-m` option: :program:`python -m test`. Under
164the hood, it uses :mod:`test.regrtest`; the call :program:`python -m
Martin Panter9955a372015-10-07 10:26:23 +0000165test.regrtest` used in previous Python versions still works. Running the
R David Murrayf1cdb602012-04-09 09:12:57 -0400166script by itself automatically starts running all regression tests in the
167:mod:`test` package. It does this by finding all modules in the package whose
168name starts with ``test_``, importing them, and executing the function
169:func:`test_main` if present or loading the tests via
170unittest.TestLoader.loadTestsFromModule if ``test_main`` does not exist. The
171names of tests to execute may also be passed to the script. Specifying a single
172regression test (:program:`python -m test test_spam`) will minimize output and
173only print whether the test passed or failed.
Georg Brandl116aa622007-08-15 14:28:22 +0000174
Éric Araujo1d55c7e2010-12-16 01:40:26 +0000175Running :mod:`test` directly allows what resources are available for
Éric Araujo713d3032010-11-18 16:38:46 +0000176tests to use to be set. You do this by using the ``-u`` command-line
R David Murray644cabe2012-04-11 20:11:53 -0400177option. Specifying ``all`` as the value for the ``-u`` option enables all
178possible resources: :program:`python -m test -uall`.
179If all but one resource is desired (a more common case), a
Georg Brandl116aa622007-08-15 14:28:22 +0000180comma-separated list of resources that are not desired may be listed after
Éric Araujo1d55c7e2010-12-16 01:40:26 +0000181``all``. The command :program:`python -m test -uall,-audio,-largefile`
182will run :mod:`test` with all resources except the ``audio`` and
Éric Araujo713d3032010-11-18 16:38:46 +0000183``largefile`` resources. For a list of all resources and more command-line
Éric Araujo1d55c7e2010-12-16 01:40:26 +0000184options, run :program:`python -m test -h`.
Georg Brandl116aa622007-08-15 14:28:22 +0000185
186Some other ways to execute the regression tests depend on what platform the
Éric Araujo713d3032010-11-18 16:38:46 +0000187tests are being executed on. On Unix, you can run :program:`make test` at the
188top-level directory where Python was built. On Windows,
Stefan Grönkef1502d02017-09-25 18:58:10 +0200189executing :program:`rt.bat` from your :file:`PCbuild` directory will run all
Florent Xicluna53b506be2010-03-18 20:00:57 +0000190regression tests.
Georg Brandl116aa622007-08-15 14:28:22 +0000191
192
Georg Brandleea6cda2011-07-30 09:00:48 +0200193:mod:`test.support` --- Utilities for the Python test suite
194===========================================================
Georg Brandl116aa622007-08-15 14:28:22 +0000195
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000196.. module:: test.support
Georg Brandleea6cda2011-07-30 09:00:48 +0200197 :synopsis: Support for Python's regression test suite.
Georg Brandl116aa622007-08-15 14:28:22 +0000198
199
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000200The :mod:`test.support` module provides support for Python's regression
Georg Brandleea6cda2011-07-30 09:00:48 +0200201test suite.
202
203.. note::
Larry Hastings3732ed22014-03-15 21:13:56 -0700204
Georg Brandleea6cda2011-07-30 09:00:48 +0200205 :mod:`test.support` is not a public module. It is documented here to help
206 Python developers write tests. The API of this module is subject to change
207 without backwards compatibility concerns between releases.
208
Georg Brandl116aa622007-08-15 14:28:22 +0000209
210This module defines the following exceptions:
211
Georg Brandl116aa622007-08-15 14:28:22 +0000212.. exception:: TestFailed
213
214 Exception to be raised when a test fails. This is deprecated in favor of
215 :mod:`unittest`\ -based tests and :class:`unittest.TestCase`'s assertion
216 methods.
217
218
Georg Brandl116aa622007-08-15 14:28:22 +0000219.. exception:: ResourceDenied
220
Florent Xicluna53b506be2010-03-18 20:00:57 +0000221 Subclass of :exc:`unittest.SkipTest`. Raised when a resource (such as a
222 network connection) is not available. Raised by the :func:`requires`
223 function.
Georg Brandl116aa622007-08-15 14:28:22 +0000224
Georg Brandl116aa622007-08-15 14:28:22 +0000225
Georg Brandleea6cda2011-07-30 09:00:48 +0200226The :mod:`test.support` module defines the following constants:
Georg Brandl116aa622007-08-15 14:28:22 +0000227
228.. data:: verbose
229
Eli Benderskye1689652011-05-06 09:29:27 +0300230 ``True`` when verbose output is enabled. Should be checked when more
Georg Brandl116aa622007-08-15 14:28:22 +0000231 detailed information is desired about a running test. *verbose* is set by
232 :mod:`test.regrtest`.
233
234
Georg Brandl116aa622007-08-15 14:28:22 +0000235.. data:: is_jython
236
Eli Benderskye1689652011-05-06 09:29:27 +0300237 ``True`` if the running interpreter is Jython.
Georg Brandl116aa622007-08-15 14:28:22 +0000238
239
Cheryl Sabella988fb282018-02-11 08:10:42 -0500240.. data:: is_android
241
242 ``True`` if the system is Android.
243
244
245.. data:: unix_shell
246
247 Path for shell if not on Windows; otherwise ``None``.
248
249
250.. data:: FS_NONASCII
251
252 A non-ASCII character encodable by :func:`os.fsencode`.
253
254
Georg Brandl116aa622007-08-15 14:28:22 +0000255.. data:: TESTFN
256
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000257 Set to a name that is safe to use as the name of a temporary file. Any
258 temporary file that is created should be closed and unlinked (removed).
Georg Brandl116aa622007-08-15 14:28:22 +0000259
Eli Benderskye1689652011-05-06 09:29:27 +0300260
Cheryl Sabella988fb282018-02-11 08:10:42 -0500261.. data:: TESTFN_UNICODE
262
263 Set to a non-ASCII name for a temporary file.
264
265
266.. data:: TESTFN_ENCODING
267
268 Set to :func:`sys.getfilesystemencoding`.
269
270
271.. data:: TESTFN_UNENCODABLE
272
273 Set to a filename (str type) that should not be able to be encoded by file
274 system encoding in strict mode. It may be ``None`` if it's not possible to
275 generate such a filename.
276
277
278.. data:: TESTFN_UNDECODABLE
279
280 Set to a filename (bytes type) that should not be able to be decoded by
281 file system encoding in strict mode. It may be ``None`` if it's not
282 possible to generate such a filename.
283
284
285.. data:: TESTFN_NONASCII
286
287 Set to a filename containing the :data:`FS_NONASCII` character.
288
289
290.. data:: IPV6_ENABLED
291
292 Set to ``True`` if IPV6 is enabled on this host, ``False`` otherwise.
293
294
295.. data:: SAVEDCWD
296
297 Set to :func:`os.getcwd`.
298
299
300.. data:: PGO
301
302 Set when tests can be skipped when they are not useful for PGO.
303
304
305.. data:: PIPE_MAX_SIZE
306
307 A constant that is likely larger than the underlying OS pipe buffer size,
308 to make writes blocking.
309
310
311.. data:: SOCK_MAX_SIZE
312
313 A constant that is likely larger than the underlying OS socket buffer size,
314 to make writes blocking.
315
316
317.. data:: TEST_SUPPORT_DIR
318
319 Set to the top level directory that contains :mod:`test.support`.
320
321
322.. data:: TEST_HOME_DIR
323
324 Set to the top level directory for the test package.
325
326
327.. data:: TEST_DATA_DIR
328
329 Set to the ``data`` directory within the test package.
330
331
332.. data:: MAX_Py_ssize_t
333
334 Set to :data:`sys.maxsize` for big memory tests.
335
336
337.. data:: max_memuse
338
339 Set by :func:`set_memlimit` as the memory limit for big memory tests.
340 Limited by :data:`MAX_Py_ssize_t`.
341
342
343.. data:: real_max_memuse
344
345 Set by :func:`set_memlimit` as the memory limit for big memory tests. Not
346 limited by :data:`MAX_Py_ssize_t`.
347
348
349.. data:: MISSING_C_DOCSTRINGS
350
351 Return ``True`` if running on CPython, not on Windows, and configuration
352 not set with ``WITH_DOC_STRINGS``.
353
354
355.. data:: HAVE_DOCSTRINGS
356
357 Check for presence of docstrings.
358
359
360
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000361The :mod:`test.support` module defines the following functions:
Georg Brandl116aa622007-08-15 14:28:22 +0000362
Georg Brandl116aa622007-08-15 14:28:22 +0000363.. function:: forget(module_name)
364
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000365 Remove the module named *module_name* from ``sys.modules`` and delete any
Georg Brandl116aa622007-08-15 14:28:22 +0000366 byte-compiled files of the module.
367
368
Cheryl Sabella988fb282018-02-11 08:10:42 -0500369.. function:: unload(name)
370
371 Delete *name* from ``sys.modules``.
372
373
374.. function:: unlink(filename)
375
376 Call :func:`os.unlink` on *filename*. On Windows platforms, this is
377 wrapped with a wait loop that checks for the existence fo the file.
378
379
380.. function:: rmdir(filename)
381
382 Call :func:`os.rmdir` on *filename*. On Windows platforms, this is
383 wrapped with a wait loop that checks for the existence of the file.
384
385
386.. function:: rmtree(path)
387
388 Call :func:`shutil.rmtree` on *path* or call :func:`os.lstat` and
389 :func:`os.rmdir` to remove a path and its contents. On Windows platforms,
390 this is wrapped with a wait loop that checks for the existence of the files.
391
392
393.. function:: make_legacy_pyc(source)
394
395 Move a PEP 3147/488 pyc file to its legacy pyc location and return the file
396 system path to the legacy pyc file. The *source* value is the file system
397 path to the source file. It does not need to exist, however the PEP
398 3147/488 pyc file must exist.
399
400
Georg Brandl116aa622007-08-15 14:28:22 +0000401.. function:: is_resource_enabled(resource)
402
Eli Benderskye1689652011-05-06 09:29:27 +0300403 Return ``True`` if *resource* is enabled and available. The list of
Georg Brandl116aa622007-08-15 14:28:22 +0000404 available resources is only set when :mod:`test.regrtest` is executing the
405 tests.
406
407
Cheryl Sabella988fb282018-02-11 08:10:42 -0500408.. function:: python_is_optimized()
409
410 Return ``True`` if Python was not built with ``-O0`` or ``-Og``.
411
412
413.. function:: with_pymalloc()
414
415 Return :data:`_testcapi.WITH_PYMALLOC`.
416
417
Georg Brandl7f01a132009-09-16 15:58:14 +0000418.. function:: requires(resource, msg=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000419
Florent Xiclunab14930c2010-03-13 15:26:44 +0000420 Raise :exc:`ResourceDenied` if *resource* is not available. *msg* is the
Florent Xicluna53b506be2010-03-18 20:00:57 +0000421 argument to :exc:`ResourceDenied` if it is raised. Always returns
Eli Benderskye1689652011-05-06 09:29:27 +0300422 ``True`` if called by a function whose ``__name__`` is ``'__main__'``.
Florent Xicluna53b506be2010-03-18 20:00:57 +0000423 Used when tests are executed by :mod:`test.regrtest`.
Georg Brandl116aa622007-08-15 14:28:22 +0000424
425
Cheryl Sabella988fb282018-02-11 08:10:42 -0500426.. function:: system_must_validate_cert(f)
427
428 Raise :exc:`unittest.SkipTest` on TLS certification validation failures.
429
430
431.. function:: sortdict(dict)
432
433 Return a repr of *dict* with keys sorted.
434
435
Nick Coghlan0494c2a2013-09-08 11:40:34 +1000436.. function:: findfile(filename, subdir=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000437
Florent Xicluna53b506be2010-03-18 20:00:57 +0000438 Return the path to the file named *filename*. If no match is found
439 *filename* is returned. This does not equal a failure since it could be the
440 path to the file.
Georg Brandl116aa622007-08-15 14:28:22 +0000441
Cheryl Sabella988fb282018-02-11 08:10:42 -0500442 Setting *subdir* indicates a relative path to use to find the file
443 rather than looking directly in the path directories.
444
445
446.. function:: create_empty_file(filename)
447
448 Create an empty file with *filename*. If it already exists, truncate it.
449
450
451.. function:: fd_count()
452
453 Count the number of open file descriptors.
454
455
456.. function:: match_test(test)
457
458 Match *test* to patterns set in :func:`set_match_tests`.
459
460
461.. function:: set_match_tests(patterns)
462
463 Define match test with regular expression *patterns*.
Nick Coghlan0494c2a2013-09-08 11:40:34 +1000464
Georg Brandl116aa622007-08-15 14:28:22 +0000465
Senthil Kumaran279b56d2010-10-15 15:21:19 +0000466.. function:: run_unittest(\*classes)
Georg Brandl116aa622007-08-15 14:28:22 +0000467
468 Execute :class:`unittest.TestCase` subclasses passed to the function. The
Florent Xicluna53b506be2010-03-18 20:00:57 +0000469 function scans the classes for methods starting with the prefix ``test_``
470 and executes the tests individually.
Georg Brandl116aa622007-08-15 14:28:22 +0000471
472 It is also legal to pass strings as parameters; these should be keys in
473 ``sys.modules``. Each associated module will be scanned by
474 ``unittest.TestLoader.loadTestsFromModule()``. This is usually seen in the
475 following :func:`test_main` function::
476
477 def test_main():
Nick Coghlan47384702009-04-22 16:13:36 +0000478 support.run_unittest(__name__)
Georg Brandl116aa622007-08-15 14:28:22 +0000479
480 This will run all tests defined in the named module.
481
Georg Brandl116aa622007-08-15 14:28:22 +0000482
Cheryl Sabella988fb282018-02-11 08:10:42 -0500483.. function:: run_doctest(module, verbosity=None, optionflags=0)
Eli Benderskye1689652011-05-06 09:29:27 +0300484
485 Run :func:`doctest.testmod` on the given *module*. Return
486 ``(failure_count, test_count)``.
487
488 If *verbosity* is ``None``, :func:`doctest.testmod` is run with verbosity
489 set to :data:`verbose`. Otherwise, it is run with verbosity set to
Cheryl Sabella988fb282018-02-11 08:10:42 -0500490 ``None``. *optionflags* is passed as ``optionflags`` to
491 :func:`doctest.testmod`.
492
493
494.. function:: setswitchinterval(interval)
495
496 Set the :func:`sys.setswitchinterval` to the given *interval*. Defines
497 a minimum interval for Android systems to prevent the system from hanging.
498
499
500.. function:: check_impl_detail(**guards)
501
502 Use this check to guard CPython's implementation-specific tests or to
503 run them only on the implementations guarded by the arguments::
504
505 check_impl_detail() # Only on CPython (default).
506 check_impl_detail(jython=True) # Only on Jython.
507 check_impl_detail(cpython=False) # Everywhere except CPython.
508
Eli Benderskye1689652011-05-06 09:29:27 +0300509
Senthil Kumaran279b56d2010-10-15 15:21:19 +0000510.. function:: check_warnings(\*filters, quiet=True)
Thomas Woutersed03b412007-08-28 21:37:11 +0000511
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000512 A convenience wrapper for :func:`warnings.catch_warnings()` that makes it
513 easier to test that a warning was correctly raised. It is approximately
514 equivalent to calling ``warnings.catch_warnings(record=True)`` with
515 :meth:`warnings.simplefilter` set to ``always`` and with the option to
516 automatically validate the results that are recorded.
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000517
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000518 ``check_warnings`` accepts 2-tuples of the form ``("message regexp",
519 WarningCategory)`` as positional arguments. If one or more *filters* are
Eli Benderskye1689652011-05-06 09:29:27 +0300520 provided, or if the optional keyword argument *quiet* is ``False``,
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000521 it checks to make sure the warnings are as expected: each specified filter
522 must match at least one of the warnings raised by the enclosed code or the
523 test fails, and if any warnings are raised that do not match any of the
524 specified filters the test fails. To disable the first of these checks,
Eli Benderskye1689652011-05-06 09:29:27 +0300525 set *quiet* to ``True``.
Florent Xiclunab14930c2010-03-13 15:26:44 +0000526
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000527 If no arguments are specified, it defaults to::
Florent Xiclunab14930c2010-03-13 15:26:44 +0000528
Florent Xicluna53b506be2010-03-18 20:00:57 +0000529 check_warnings(("", Warning), quiet=True)
Florent Xiclunab14930c2010-03-13 15:26:44 +0000530
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000531 In this case all warnings are caught and no errors are raised.
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000532
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000533 On entry to the context manager, a :class:`WarningRecorder` instance is
534 returned. The underlying warnings list from
535 :func:`~warnings.catch_warnings` is available via the recorder object's
536 :attr:`warnings` attribute. As a convenience, the attributes of the object
537 representing the most recent warning can also be accessed directly through
538 the recorder object (see example below). If no warning has been raised,
539 then any of the attributes that would otherwise be expected on an object
Eli Benderskye1689652011-05-06 09:29:27 +0300540 representing a warning will return ``None``.
Thomas Woutersed03b412007-08-28 21:37:11 +0000541
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000542 The recorder object also has a :meth:`reset` method, which clears the
543 warnings list.
Thomas Woutersed03b412007-08-28 21:37:11 +0000544
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000545 The context manager is designed to be used like this::
Florent Xiclunab14930c2010-03-13 15:26:44 +0000546
547 with check_warnings(("assertion is always true", SyntaxWarning),
548 ("", UserWarning)):
549 exec('assert(False, "Hey!")')
550 warnings.warn(UserWarning("Hide me!"))
551
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000552 In this case if either warning was not raised, or some other warning was
553 raised, :func:`check_warnings` would raise an error.
554
555 When a test needs to look more deeply into the warnings, rather than
556 just checking whether or not they occurred, code like this can be used::
557
Florent Xiclunab14930c2010-03-13 15:26:44 +0000558 with check_warnings(quiet=True) as w:
Thomas Woutersed03b412007-08-28 21:37:11 +0000559 warnings.warn("foo")
Florent Xiclunab14930c2010-03-13 15:26:44 +0000560 assert str(w.args[0]) == "foo"
Nick Coghlanb1304932008-07-13 12:25:08 +0000561 warnings.warn("bar")
Florent Xiclunab14930c2010-03-13 15:26:44 +0000562 assert str(w.args[0]) == "bar"
563 assert str(w.warnings[0].args[0]) == "foo"
564 assert str(w.warnings[1].args[0]) == "bar"
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000565 w.reset()
566 assert len(w.warnings) == 0
Thomas Woutersed03b412007-08-28 21:37:11 +0000567
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000568
569 Here all warnings will be caught, and the test code tests the captured
570 warnings directly.
571
Ezio Melottif8754a62010-03-21 07:16:43 +0000572 .. versionchanged:: 3.2
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000573 New optional arguments *filters* and *quiet*.
Florent Xiclunab14930c2010-03-13 15:26:44 +0000574
Thomas Woutersed03b412007-08-28 21:37:11 +0000575
Cheryl Sabella988fb282018-02-11 08:10:42 -0500576.. function:: check_no_resource_warning(testcase)
577
578 Context manager to check that no :exc:`ResourceWarning` was raised. You
579 must remove the object which may emit :exc:`ResourceWarning` before the
580 end of the context manager.
581
582
583.. function:: set_memlimit(limit)
584
585 Set the values for :data:`max_memuse` and :data:`real_max_memuse` for big
586 memory tests.
587
588
589.. function:: record_original_stdout(stdout)
590
591 Store the value from *stdout*. It is meant to hold the stdout at the
592 time the regrtest began.
593
594
595.. function:: get_original_stdout
596
597 Return the original stdout set by :func:`record_original_stdout` or
598 ``sys.stdout`` if it's not set.
599
600
601.. function:: strip_python_strerr(stderr)
602
603 Strip the *stderr* of a Python process from potential debug output
604 emitted by the interpreter. This will typically be run on the result of
605 :meth:`subprocess.Popen.communicate`.
606
607
608.. function:: args_from_interpreter_flags()
609
610 Return a list of command line arguments reproducing the current settings
611 in ``sys.flags`` and ``sys.warnoptions``.
612
613
614.. function:: optim_args_from_interpreter_flags()
615
616 Return a list of command line arguments reproducing the current
617 optimization settings in ``sys.flags``.
618
619
R David Murray5a33f812013-07-11 12:28:40 -0400620.. function:: captured_stdin()
621 captured_stdout()
622 captured_stderr()
Thomas Woutersed03b412007-08-28 21:37:11 +0000623
R David Murray5a33f812013-07-11 12:28:40 -0400624 A context managers that temporarily replaces the named stream with
625 :class:`io.StringIO` object.
Thomas Woutersed03b412007-08-28 21:37:11 +0000626
R David Murray5a33f812013-07-11 12:28:40 -0400627 Example use with output streams::
Thomas Woutersed03b412007-08-28 21:37:11 +0000628
R David Murray5a33f812013-07-11 12:28:40 -0400629 with captured_stdout() as stdout, captured_stderr() as stderr:
Collin Winterc79461b2007-09-01 23:34:30 +0000630 print("hello")
R David Murray5a33f812013-07-11 12:28:40 -0400631 print("error", file=sys.stderr)
632 assert stdout.getvalue() == "hello\n"
633 assert stderr.getvalue() == "error\n"
634
635 Example use with input stream::
636
637 with captured_stdin() as stdin:
638 stdin.write('hello\n')
639 stdin.seek(0)
640 # call test code that consumes from sys.stdin
641 captured = input()
642 self.assertEqual(captured, "hello")
Thomas Woutersed03b412007-08-28 21:37:11 +0000643
Thomas Woutersed03b412007-08-28 21:37:11 +0000644
Nick Coghlan55175962013-07-28 22:11:50 +1000645.. function:: temp_dir(path=None, quiet=False)
646
647 A context manager that creates a temporary directory at *path* and
648 yields the directory.
649
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300650 If *path* is ``None``, the temporary directory is created using
Nick Coghlan55175962013-07-28 22:11:50 +1000651 :func:`tempfile.mkdtemp`. If *quiet* is ``False``, the context manager
652 raises an exception on error. Otherwise, if *path* is specified and
653 cannot be created, only a warning is issued.
654
655
656.. function:: change_cwd(path, quiet=False)
Eli Benderskye1689652011-05-06 09:29:27 +0300657
658 A context manager that temporarily changes the current working
Nick Coghlan55175962013-07-28 22:11:50 +1000659 directory to *path* and yields the directory.
Eli Benderskye1689652011-05-06 09:29:27 +0300660
Nick Coghlan55175962013-07-28 22:11:50 +1000661 If *quiet* is ``False``, the context manager raises an exception
662 on error. Otherwise, it issues only a warning and keeps the current
663 working directory the same.
Eli Benderskye1689652011-05-06 09:29:27 +0300664
Nick Coghlan55175962013-07-28 22:11:50 +1000665
666.. function:: temp_cwd(name='tempcwd', quiet=False)
667
668 A context manager that temporarily creates a new directory and
669 changes the current working directory (CWD).
670
671 The context manager creates a temporary directory in the current
672 directory with name *name* before temporarily changing the current
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300673 working directory. If *name* is ``None``, the temporary directory is
Nick Coghlan55175962013-07-28 22:11:50 +1000674 created using :func:`tempfile.mkdtemp`.
675
676 If *quiet* is ``False`` and it is not possible to create or change
677 the CWD, an error is raised. Otherwise, only a warning is raised
678 and the original CWD is used.
Eli Benderskye1689652011-05-06 09:29:27 +0300679
680
681.. function:: temp_umask(umask)
682
683 A context manager that temporarily sets the process umask.
684
685
Cheryl Sabella988fb282018-02-11 08:10:42 -0500686.. function:: transient_internet(resource_name, *, timeout=30.0, errnos=())
687
688 A context manager that raises :exc:`ResourceDenied` when various issues
689 with the internet connection manifest themselves as exceptions.
690
691
692.. function:: disable_faulthandler()
693
694 A context manager that replaces ``sys.stderr`` with ``sys.__stderr__``.
695
696
697.. function:: gc_collect()
698
699 Force as many objects as possible to be collected. This is needed because
700 timely deallocation is not guaranteed by the garbage collector. This means
701 that ``__del__`` methods may be called later than expected and weakrefs
702 may remain alive for longer than expected.
703
704
705.. function:: disable_gc()
706
707 A context manager that disables the garbage collector upon entry and
708 reenables it upon exit.
709
710
711.. function:: swap_attr(obj, attr, new_val)
712
713 Context manager to swap out an attribute with a new object.
714
715 Usage::
716
717 with swap_attr(obj, "attr", 5):
718 ...
719
720 This will set ``obj.attr`` to 5 for the duration of the ``with`` block,
721 restoring the old value at the end of the block. If ``attr`` doesn't
722 exist on ``obj``, it will be created and then deleted at the end of the
723 block.
724
725 The old value (or ``None`` if it doesn't exist) will be assigned to the
726 target of the "as" clause, if there is one.
727
728
729.. function:: swap_item(obj, attr, new_val)
730
731 Context manager to swap out an item with a new object.
732
733 Usage::
734
735 with swap_item(obj, "item", 5):
736 ...
737
738 This will set ``obj["item"]`` to 5 for the duration of the ``with`` block,
739 restoring the old value at the end of the block. If ``item`` doesn't
740 exist on ``obj``, it will be created and then deleted at the end of the
741 block.
742
743 The old value (or ``None`` if it doesn't exist) will be assigned to the
744 target of the "as" clause, if there is one.
745
746
747.. function:: wait_threads_exit(timeout=60.0)
748
Ville Skyttä61f82e02018-04-20 23:08:45 +0300749 Context manager to wait until all threads created in the ``with`` statement
Cheryl Sabella988fb282018-02-11 08:10:42 -0500750 exit.
751
752
753.. function:: start_threads(threads, unlock=None)
754
755 Context manager to start *threads*. It attempts to join the threads upon
756 exit.
757
758
759.. function:: calcobjsize(fmt)
760
761 Return :func:`struct.calcsize` for ``nP{fmt}0n`` or, if ``gettotalrefcount``
762 exists, ``2PnP{fmt}0P``.
763
764
765.. function:: calcvobjsize(fmt)
766
767 Return :func:`struct.calcsize` for ``nPn{fmt}0n`` or, if ``gettotalrefcount``
768 exists, ``2PnPn{fmt}0P``.
769
770
771.. function:: checksizeof(test, o, size)
772
773 For testcase *test*, assert that the ``sys.getsizeof`` for *o* plus the GC
774 header size equals *size*.
775
776
Eli Benderskye1689652011-05-06 09:29:27 +0300777.. function:: can_symlink()
778
779 Return ``True`` if the OS supports symbolic links, ``False``
780 otherwise.
781
782
Cheryl Sabella988fb282018-02-11 08:10:42 -0500783.. function:: can_xattr()
784
785 Return ``True`` if the OS supports xattr, ``False``
786 otherwise.
787
788
Daisuke Miyakawa0e61e672017-10-12 23:39:43 +0900789.. decorator:: skip_unless_symlink
Eli Benderskye1689652011-05-06 09:29:27 +0300790
791 A decorator for running tests that require support for symbolic links.
792
793
Cheryl Sabella988fb282018-02-11 08:10:42 -0500794.. decorator:: skip_unless_xattr
795
796 A decorator for running tests that require support for xattr.
797
798
799.. decorator:: skip_unless_bind_unix_socket
800
801 A decorator for running tests that require a functional bind() for Unix
802 sockets.
803
804
Nick Coghlan2496f332011-09-19 20:26:31 +1000805.. decorator:: anticipate_failure(condition)
806
807 A decorator to conditionally mark tests with
808 :func:`unittest.expectedFailure`. Any use of this decorator should
809 have an associated comment identifying the relevant tracker issue.
810
811
812.. decorator:: run_with_locale(catstr, *locales)
Eli Benderskye1689652011-05-06 09:29:27 +0300813
814 A decorator for running a function in a different locale, correctly
815 resetting it after it has finished. *catstr* is the locale category as
816 a string (for example ``"LC_ALL"``). The *locales* passed will be tried
817 sequentially, and the first valid locale will be used.
818
819
Cheryl Sabella988fb282018-02-11 08:10:42 -0500820.. decorator:: run_with_tz(tz)
821
822 A decorator for running a function in a specific timezone, correctly
823 resetting it after it has finished.
824
825
826.. decorator:: requires_freebsd_version(*min_version)
827
828 Decorator for the minimum version when running test on FreeBSD. If the
829 FreeBSD version is less than the minimum, raise :exc:`unittest.SkipTest`.
830
831
832.. decorator:: requires_linux_version(*min_version)
833
834 Decorator for the minimum version when running test on Linux. If the
835 Linux version is less than the minimum, raise :exc:`unittest.SkipTest`.
836
837
838.. decorator:: requires_mac_version(*min_version)
839
840 Decorator for the minimum version when running test on Mac OS X. If the
841 MAC OS X version is less than the minimum, raise :exc:`unittest.SkipTest`.
842
843
844.. decorator:: requires_IEEE_754
845
846 Decorator for skipping tests on non-IEEE 754 platforms.
847
848
849.. decorator:: requires_zlib
850
851 Decorator for skipping tests if :mod:`zlib` doesn't exist.
852
853
854.. decorator:: requires_gzip
855
856 Decorator for skipping tests if :mod:`gzip` doesn't exist.
857
858
859.. decorator:: requires_bz2
860
861 Decorator for skipping tests if :mod:`bz2` doesn't exist.
862
863
864.. decorator:: requires_lzma
865
866 Decorator for skipping tests if :mod:`lzma` doesn't exist.
867
868
869.. decorator:: requires_resource(resource)
870
871 Decorator for skipping tests if *resource* is not available.
872
873
874.. decorator:: requires_docstrings
875
876 Decorator for only running the test if :data:`HAVE_DOCSTRINGS`.
877
878
879.. decorator:: cpython_only(test)
880
881 Decorator for tests only applicable to CPython.
882
883
884.. decorator:: impl_detail(msg=None, **guards)
885
886 Decorator for invoking :func:`check_impl_detail` on *guards*. If that
887 returns ``False``, then uses *msg* as the reason for skipping the test.
888
889
890.. decorator:: no_tracing(func)
891
892 Decorator to temporarily turn off tracing for the duration of the test.
893
894
895.. decorator:: refcount_test(test)
896
897 Decorator for tests which involve reference counting. The decorator does
898 not run the test if it is not run by CPython. Any trace function is unset
899 for the duration of the test to prevent unexpected refcounts caused by
900 the trace function.
901
902
903.. decorator:: reap_threads(func)
904
905 Decorator to ensure the threads are cleaned up even if the test fails.
906
907
908.. decorator:: bigmemtest(size, memuse, dry_run=True)
909
910 Decorator for bigmem tests.
911
912 *size* is a requested size for the test (in arbitrary, test-interpreted
913 units.) *memuse* is the number of bytes per unit for the test, or a good
914 estimate of it. For example, a test that needs two byte buffers, of 4 GiB
915 each, could be decorated with ``@bigmemtest(size=_4G, memuse=2)``.
916
917 The *size* argument is normally passed to the decorated test method as an
918 extra argument. If *dry_run* is ``True``, the value passed to the test
919 method may be less than the requested value. If *dry_run* is ``False``, it
920 means the test doesn't support dummy runs when ``-M`` is not specified.
921
922
923.. decorator:: bigaddrspacetest(f)
924
925 Decorator for tests that fill the address space. *f* is the function to
926 wrap.
927
928
Eli Benderskye1689652011-05-06 09:29:27 +0300929.. function:: make_bad_fd()
930
931 Create an invalid file descriptor by opening and closing a temporary file,
Zachary Waref012ba42014-07-23 12:00:29 -0500932 and returning its descriptor.
Eli Benderskye1689652011-05-06 09:29:27 +0300933
934
Cheryl Sabella988fb282018-02-11 08:10:42 -0500935.. function:: check_syntax_error(testcase, statement, errtext='', *, lineno=None, offset=None)
936
937 Test for syntax errors in *statement* by attempting to compile *statement*.
938 *testcase* is the :mod:`unittest` instance for the test. *errtext* is the
939 text of the error raised by :exc:`SyntaxError`. If *lineno* is not None,
940 compares to the line of the :exc:`SyntaxError`. If *offset* is not None,
941 compares to the offset of the :exc:`SyntaxError`.
942
943
944.. function:: open_urlresource(url, *args, **kw)
945
946 Open *url*. If open fails, raises :exc:`TestFailed`.
947
948
949.. function:: import_module(name, deprecated=False, *, required_on())
Nick Coghlanfce769e2009-04-11 14:30:59 +0000950
951 This function imports and returns the named module. Unlike a normal
952 import, this function raises :exc:`unittest.SkipTest` if the module
953 cannot be imported.
954
955 Module and package deprecation messages are suppressed during this import
Cheryl Sabella988fb282018-02-11 08:10:42 -0500956 if *deprecated* is ``True``. If a module is required on a platform but
957 optional for others, set *required_on* to an iterable of platform prefixes
958 which will be compared against :data:`sys.platform`.
Nick Coghlanfce769e2009-04-11 14:30:59 +0000959
960 .. versionadded:: 3.1
961
962
Nick Coghlan47384702009-04-22 16:13:36 +0000963.. function:: import_fresh_module(name, fresh=(), blocked=(), deprecated=False)
Nick Coghlanfce769e2009-04-11 14:30:59 +0000964
Nick Coghlan47384702009-04-22 16:13:36 +0000965 This function imports and returns a fresh copy of the named Python module
966 by removing the named module from ``sys.modules`` before doing the import.
967 Note that unlike :func:`reload`, the original module is not affected by
968 this operation.
969
970 *fresh* is an iterable of additional module names that are also removed
971 from the ``sys.modules`` cache before doing the import.
972
Eli Benderskyba5517d2013-08-11 15:38:08 -0700973 *blocked* is an iterable of module names that are replaced with ``None``
Nick Coghlan47384702009-04-22 16:13:36 +0000974 in the module cache during the import to ensure that attempts to import
975 them raise :exc:`ImportError`.
976
977 The named module and any modules named in the *fresh* and *blocked*
978 parameters are saved before starting the import and then reinserted into
979 ``sys.modules`` when the fresh import is complete.
Nick Coghlanfce769e2009-04-11 14:30:59 +0000980
981 Module and package deprecation messages are suppressed during this import
Eli Benderskye1689652011-05-06 09:29:27 +0300982 if *deprecated* is ``True``.
Nick Coghlanfce769e2009-04-11 14:30:59 +0000983
Eli Benderskyba5517d2013-08-11 15:38:08 -0700984 This function will raise :exc:`ImportError` if the named module cannot be
985 imported.
Nick Coghlan47384702009-04-22 16:13:36 +0000986
987 Example use::
988
Eli Benderskyba5517d2013-08-11 15:38:08 -0700989 # Get copies of the warnings module for testing without affecting the
990 # version being used by the rest of the test suite. One copy uses the
991 # C implementation, the other is forced to use the pure Python fallback
992 # implementation
Nick Coghlan47384702009-04-22 16:13:36 +0000993 py_warnings = import_fresh_module('warnings', blocked=['_warnings'])
994 c_warnings = import_fresh_module('warnings', fresh=['_warnings'])
995
Nick Coghlanfce769e2009-04-11 14:30:59 +0000996 .. versionadded:: 3.1
997
998
Cheryl Sabella988fb282018-02-11 08:10:42 -0500999.. function:: modules_setup()
1000
1001 Return a copy of :data:`sys.modules`.
1002
1003
1004.. function:: modules_cleanup(oldmodules)
1005
1006 Remove modules except for *oldmodules* and ``encodings`` in order to
1007 preserve internal cache.
1008
1009
1010.. function:: threading_setup()
1011
1012 Return current thread count and copy of dangling threads.
1013
1014
1015.. function:: threading_cleanup(*original_values)
1016
1017 Cleanup up threads not specified in *original_values*. Designed to emit
1018 a warning if a test leaves running threads in the background.
1019
1020
1021.. function:: join_thread(thread, timeout=30.0)
1022
1023 Join a *thread* within *timeout*. Raise an :exc:`AssertionError` if thread
1024 is still alive after *timeout* seconds.
1025
1026
1027.. function:: reap_children()
1028
1029 Use this at the end of ``test_main`` whenever sub-processes are started.
1030 This will help ensure that no extra children (zombies) stick around to
1031 hog resources and create problems when looking for refleaks.
1032
1033
1034.. function:: get_attribute(obj, name)
1035
1036 Get an attribute, raising :exc:`unittest.SkipTest` if :exc:`AttributeError`
1037 is raised.
1038
1039
Eli Benderskye1689652011-05-06 09:29:27 +03001040.. function:: bind_port(sock, host=HOST)
1041
1042 Bind the socket to a free port and return the port number. Relies on
1043 ephemeral ports in order to ensure we are using an unbound port. This is
1044 important as many tests may be running simultaneously, especially in a
1045 buildbot environment. This method raises an exception if the
1046 ``sock.family`` is :const:`~socket.AF_INET` and ``sock.type`` is
1047 :const:`~socket.SOCK_STREAM`, and the socket has
1048 :const:`~socket.SO_REUSEADDR` or :const:`~socket.SO_REUSEPORT` set on it.
1049 Tests should never set these socket options for TCP/IP sockets.
1050 The only case for setting these options is testing multicasting via
1051 multiple UDP sockets.
1052
1053 Additionally, if the :const:`~socket.SO_EXCLUSIVEADDRUSE` socket option is
1054 available (i.e. on Windows), it will be set on the socket. This will
1055 prevent anyone else from binding to our host/port for the duration of the
1056 test.
1057
1058
Cheryl Sabella988fb282018-02-11 08:10:42 -05001059.. function:: bind_unix_socket(sock, addr)
1060
1061 Bind a unix socket, raising :exc:`unittest.SkipTest` if
1062 :exc:`PermissionError` is raised.
1063
1064
Eli Benderskye1689652011-05-06 09:29:27 +03001065.. function:: find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM)
1066
1067 Returns an unused port that should be suitable for binding. This is
1068 achieved by creating a temporary socket with the same family and type as
1069 the ``sock`` parameter (default is :const:`~socket.AF_INET`,
1070 :const:`~socket.SOCK_STREAM`),
1071 and binding it to the specified host address (defaults to ``0.0.0.0``)
1072 with the port set to 0, eliciting an unused ephemeral port from the OS.
1073 The temporary socket is then closed and deleted, and the ephemeral port is
1074 returned.
1075
1076 Either this method or :func:`bind_port` should be used for any tests
1077 where a server socket needs to be bound to a particular port for the
1078 duration of the test.
Andrés Delfino271818f2018-09-14 14:13:09 -03001079 Which one to use depends on whether the calling code is creating a Python
Eli Benderskye1689652011-05-06 09:29:27 +03001080 socket, or if an unused port needs to be provided in a constructor
1081 or passed to an external program (i.e. the ``-accept`` argument to
1082 openssl's s_server mode). Always prefer :func:`bind_port` over
1083 :func:`find_unused_port` where possible. Using a hard coded port is
Martin Panter8f265652016-04-19 04:03:41 +00001084 discouraged since it can make multiple instances of the test impossible to
Eli Benderskye1689652011-05-06 09:29:27 +03001085 run simultaneously, which is a problem for buildbots.
1086
1087
Zachary Waref012ba42014-07-23 12:00:29 -05001088.. function:: load_package_tests(pkg_dir, loader, standard_tests, pattern)
1089
1090 Generic implementation of the :mod:`unittest` ``load_tests`` protocol for
1091 use in test packages. *pkg_dir* is the root directory of the package;
1092 *loader*, *standard_tests*, and *pattern* are the arguments expected by
1093 ``load_tests``. In simple cases, the test package's ``__init__.py``
1094 can be the following::
1095
1096 import os
1097 from test.support import load_package_tests
1098
1099 def load_tests(*args):
1100 return load_package_tests(os.path.dirname(__file__), *args)
1101
Louie Lu7fae81e2017-04-22 14:46:18 +08001102
Cheryl Sabella988fb282018-02-11 08:10:42 -05001103.. function:: fs_is_case_insensitive(directory)
1104
1105 Return ``True`` if the file system for *directory* is case-insensitive.
1106
1107
Louie Lu7fae81e2017-04-22 14:46:18 +08001108.. function:: detect_api_mismatch(ref_api, other_api, *, ignore=())
Gregory P. Smith4e72cce2015-04-14 13:26:06 -07001109
Zachary Ware3d3aedc2015-07-07 00:07:25 -05001110 Returns the set of attributes, functions or methods of *ref_api* not
1111 found on *other_api*, except for a defined list of items to be
1112 ignored in this check specified in *ignore*.
Gregory P. Smith4e72cce2015-04-14 13:26:06 -07001113
1114 By default this skips private attributes beginning with '_' but
1115 includes all magic methods, i.e. those starting and ending in '__'.
1116
Gregory P. Smith7c63fd32015-04-14 15:25:01 -07001117 .. versionadded:: 3.5
1118
Zachary Waref012ba42014-07-23 12:00:29 -05001119
Cheryl Sabella988fb282018-02-11 08:10:42 -05001120.. function:: patch(test_instance, object_to_patch, attr_name, new_value)
1121
1122 Override *object_to_patch.attr_name* with *new_value*. Also add
1123 cleanup procedure to *test_instance* to restore *object_to_patch* for
1124 *attr_name*. The *attr_name* should be a valid attribute for
1125 *object_to_patch*.
1126
1127
1128.. function:: run_in_subinterp(code)
1129
1130 Run *code* in subinterpreter. Raise :exc:`unittest.SkipTest` if
1131 :mod:`tracemalloc` is enabled.
1132
1133
1134.. function:: check_free_after_iterating(test, iter, cls, args=())
1135
1136 Assert that *iter* is deallocated after iterating.
1137
1138
1139.. function:: missing_compiler_executable(cmd_names=[])
1140
1141 Check for the existence of the compiler executables whose names are listed
1142 in *cmd_names* or all the compiler executables when *cmd_names* is empty
1143 and return the first missing executable or ``None`` when none is found
1144 missing.
1145
1146
Martin Panterd226d302015-11-14 11:47:00 +00001147.. function:: check__all__(test_case, module, name_of_module=None, extra=(), blacklist=())
1148
1149 Assert that the ``__all__`` variable of *module* contains all public names.
1150
1151 The module's public names (its API) are detected automatically
1152 based on whether they match the public name convention and were defined in
1153 *module*.
1154
1155 The *name_of_module* argument can specify (as a string or tuple thereof) what
Serhiy Storchakabac2d5b2018-03-28 22:14:26 +03001156 module(s) an API could be defined in order to be detected as a public
Martin Panterd226d302015-11-14 11:47:00 +00001157 API. One case for this is when *module* imports part of its public API from
1158 other modules, possibly a C backend (like ``csv`` and its ``_csv``).
1159
1160 The *extra* argument can be a set of names that wouldn't otherwise be automatically
1161 detected as "public", like objects without a proper ``__module__``
1162 attribute. If provided, it will be added to the automatically detected ones.
1163
1164 The *blacklist* argument can be a set of names that must not be treated as part of
1165 the public API even though their names indicate otherwise.
1166
1167 Example use::
1168
1169 import bar
1170 import foo
1171 import unittest
1172 from test import support
1173
1174 class MiscTestCase(unittest.TestCase):
1175 def test__all__(self):
1176 support.check__all__(self, foo)
1177
1178 class OtherTestCase(unittest.TestCase):
1179 def test__all__(self):
1180 extra = {'BAR_CONST', 'FOO_CONST'}
1181 blacklist = {'baz'} # Undocumented name.
1182 # bar imports part of its API from _bar.
1183 support.check__all__(self, bar, ('bar', '_bar'),
1184 extra=extra, blacklist=blacklist)
1185
1186 .. versionadded:: 3.6
1187
1188
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001189The :mod:`test.support` module defines the following classes:
Georg Brandl116aa622007-08-15 14:28:22 +00001190
Georg Brandl7f01a132009-09-16 15:58:14 +00001191.. class:: TransientResource(exc, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001192
1193 Instances are a context manager that raises :exc:`ResourceDenied` if the
1194 specified exception type is raised. Any keyword arguments are treated as
1195 attribute/value pairs to be compared against any exception raised within the
1196 :keyword:`with` statement. Only if all pairs match properly against
1197 attributes on the exception is :exc:`ResourceDenied` raised.
1198
Georg Brandl116aa622007-08-15 14:28:22 +00001199
1200.. class:: EnvironmentVarGuard()
1201
Florent Xicluna53b506be2010-03-18 20:00:57 +00001202 Class used to temporarily set or unset environment variables. Instances can
1203 be used as a context manager and have a complete dictionary interface for
1204 querying/modifying the underlying ``os.environ``. After exit from the
1205 context manager all changes to environment variables done through this
1206 instance will be rolled back.
Georg Brandl116aa622007-08-15 14:28:22 +00001207
Georg Brandl705d9d52009-05-05 09:29:50 +00001208 .. versionchanged:: 3.1
Walter Dörwald155374d2009-05-01 19:58:58 +00001209 Added dictionary interface.
Georg Brandl116aa622007-08-15 14:28:22 +00001210
1211.. method:: EnvironmentVarGuard.set(envvar, value)
1212
Florent Xicluna53b506be2010-03-18 20:00:57 +00001213 Temporarily set the environment variable ``envvar`` to the value of
1214 ``value``.
Georg Brandl116aa622007-08-15 14:28:22 +00001215
1216
1217.. method:: EnvironmentVarGuard.unset(envvar)
1218
1219 Temporarily unset the environment variable ``envvar``.
Nick Coghlanb1304932008-07-13 12:25:08 +00001220
Walter Dörwald155374d2009-05-01 19:58:58 +00001221
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001222.. class:: SuppressCrashReport()
1223
1224 A context manager used to try to prevent crash dialog popups on tests that
1225 are expected to crash a subprocess.
1226
1227 On Windows, it disables Windows Error Reporting dialogs using
Georg Brandl5d941342016-02-26 19:37:12 +01001228 `SetErrorMode <https://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx>`_.
Antoine Pitrou77e904e2013-10-08 23:04:32 +02001229
1230 On UNIX, :func:`resource.setrlimit` is used to set
1231 :attr:`resource.RLIMIT_CORE`'s soft limit to 0 to prevent coredump file
1232 creation.
1233
1234 On both platforms, the old value is restored by :meth:`__exit__`.
1235
1236
Cheryl Sabella988fb282018-02-11 08:10:42 -05001237.. class:: CleanImport(*module_names)
1238
1239 A context manager to force import to return a new module reference. This
1240 is useful for testing module-level behaviors, such as the emission of a
1241 DeprecationWarning on import. Example usage::
1242
1243 with CleanImport('foo'):
1244 importlib.import_module('foo') # New reference.
1245
1246
1247.. class:: DirsOnSysPath(*paths)
1248
1249 A context manager to temporarily add directories to sys.path.
1250
1251 This makes a copy of :data:`sys.path`, appends any directories given
1252 as positional arguments, then reverts :data:`sys.path` to the copied
1253 settings when the context ends.
1254
1255 Note that *all* :data:`sys.path` modifications in the body of the
1256 context manager, including replacement of the object,
1257 will be reverted at the end of the block.
1258
1259
1260.. class:: SaveSignals()
1261
1262 Class to save and restore signal handlers registered by the Python signal
1263 handler.
1264
1265
1266.. class:: Matcher()
1267
1268 .. method:: matches(self, d, **kwargs)
1269
1270 Try to match a single dict with the supplied arguments.
1271
1272
1273 .. method:: match_value(self, k, dv, v)
1274
1275 Try to match a single stored value (*dv*) with a supplied value (*v*).
1276
1277
Benjamin Petersonfcf5d632008-10-16 23:24:44 +00001278.. class:: WarningsRecorder()
1279
1280 Class used to record warnings for unit tests. See documentation of
1281 :func:`check_warnings` above for more details.
Cheryl Sabella988fb282018-02-11 08:10:42 -05001282
1283
1284.. class:: BasicTestRunner()
1285
1286 .. method:: run(test)
1287
1288 Run *test* and return the result.
1289
1290
1291.. class:: TestHandler(logging.handlers.BufferingHandler)
1292
1293 Class for logging support.
1294
1295
Serhiy Storchakab21d1552018-03-02 11:53:51 +02001296.. class:: FakePath(path)
1297
1298 Simple :term:`path-like object`. It implements the :meth:`__fspath__`
1299 method which just returns the *path* argument. If *path* is an exception,
1300 it will be raised in :meth:`!__fspath__`.
1301
1302
Cheryl Sabella988fb282018-02-11 08:10:42 -05001303:mod:`test.support.script_helper` --- Utilities for the Python execution tests
1304==============================================================================
1305
1306.. module:: test.support.script_helper
1307 :synopsis: Support for Python's script execution tests.
1308
1309
1310The :mod:`test.support.script_helper` module provides support for Python's
1311script execution tests.
1312
1313.. function:: interpreter_requires_environment()
1314
1315 Return ``True`` if ``sys.executable interpreter`` requires environment
1316 variables in order to be able to run at all.
1317
1318 This is designed to be used with ``@unittest.skipIf()`` to annotate tests
1319 that need to use an ``assert_python*()`` function to launch an isolated
1320 mode (``-I``) or no environment mode (``-E``) sub-interpreter process.
1321
1322 A normal build & test does not run into this situation but it can happen
1323 when trying to run the standard library test suite from an interpreter that
1324 doesn't have an obvious home with Python's current home finding logic.
1325
1326 Setting :envvar:`PYTHONHOME` is one way to get most of the testsuite to run
1327 in that situation. :envvar:`PYTHONPATH` or :envvar:`PYTHONUSERSITE` are
1328 other common environment variables that might impact whether or not the
1329 interpreter can start.
1330
1331
1332.. function:: run_python_until_end(*args, **env_vars)
1333
1334 Set up the environment based on *env_vars* for running the interpreter
Nick Coghland5d9e022018-03-25 23:03:10 +10001335 in a subprocess. The values can include ``__isolated``, ``__cleanenv``,
1336 ``__cwd``, and ``TERM``.
Cheryl Sabella988fb282018-02-11 08:10:42 -05001337
1338
1339.. function:: assert_python_ok(*args, **env_vars)
1340
1341 Assert that running the interpreter with *args* and optional environment
1342 variables *env_vars* succeeds (``rc == 0``) and return a ``(return code,
1343 stdout, stderr)`` tuple.
1344
1345 If the ``__cleanenv`` keyword is set, *env_vars* is used as a fresh
1346 environment.
1347
1348 Python is started in isolated mode (command line option ``-I``),
1349 except if the ``__isolated`` keyword is set to ``False``.
1350
1351
1352.. function:: assert_python_failure(*args, **env_vars)
1353
1354 Assert that running the interpreter with *args* and optional environment
1355 variables *env_vars* fails (``rc != 0``) and return a ``(return code,
1356 stdout, stderr)`` tuple.
1357
1358 See :func:`assert_python_ok` for more options.
1359
1360
1361.. function:: spawn_python(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kw)
1362
1363 Run a Python subprocess with the given arguments.
1364
1365 *kw* is extra keyword args to pass to :func:`subprocess.Popen`. Returns a
1366 :class:`subprocess.Popen` object.
1367
1368
1369.. function:: kill_python(p)
1370
1371 Run the given :class:`subprocess.Popen` process until completion and return
1372 stdout.
1373
1374
1375.. function:: make_script(script_dir, script_basename, source, omit_suffix=False)
1376
1377 Create script containing *source* in path *script_dir* and *script_basename*.
1378 If *omit_suffix* is ``False``, append ``.py`` to the name. Return the full
1379 script path.
1380
1381
1382.. function:: make_zip_script(zip_dir, zip_basename, script_name, name_in_zip=None)
1383
1384 Create zip file at *zip_dir* and *zip_basename* with extension ``zip`` which
1385 contains the files in *script_name*. *name_in_zip* is the archive name.
1386 Return a tuple containing ``(full path, full path of archive name)``.
1387
1388
1389.. function:: make_pkg(pkg_dir, init_source='')
1390
1391 Create a directory named *pkg_dir* containing an ``__init__`` file with
1392 *init_source* as its contents.
1393
1394
1395.. function:: make_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename, \
1396 source, depth=1, compiled=False)
1397
1398 Create a zip package directory with a path of *zip_dir* and *zip_basename*
1399 containing an empty ``__init__`` file and a file *script_basename*
1400 containing the *source*. If *compiled* is ``True``, both source files will
1401 be compiled and added to the zip package. Return a tuple of the full zip
1402 path and the archive name for the zip file.