Debian Codegraph @

Doc/library/test.rst

raw
1 :mod:`!test` --- Regression tests package for Python
2 ====================================================
3
4 .. module:: test
5 :synopsis: Regression tests package containing the testing suite for Python.
6
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
18 The :mod:`test` package contains all regression tests for Python as well as the
19 modules :mod:`test.support` and :mod:`test.regrtest`.
20 :mod:`test.support` is used to enhance your tests while
21 :mod:`test.regrtest` drives the testing suite.
22
23 Each module in the :mod:`test` package whose name starts with ``test_`` is a
24 testing suite for a specific module or feature. All new tests should be written
25 using the :mod:`unittest` or :mod:`doctest` module. Some older tests are
26 written 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
41 Writing Unit Tests for the :mod:`test` package
42 ----------------------------------------------
43
44 It is preferred that tests that use the :mod:`unittest` module follow a few
45 guidelines. One is to name the test module by starting it with ``test_`` and end
46 it with the name of the module being tested. The test methods in the test module
47 should start with ``test_`` and end with a description of what the method is
48 testing. This is needed so that the methods are recognized by the test driver as
49 test methods. Also, no documentation string for the method should be included. A
50 comment (such as ``# Tests function returns only True or False``) should be used
51 to provide documentation for test methods. This is done because documentation
52 strings get printed out if they exist and thus what test is being run is not
53 stated.
54
55 A basic boilerplate is often used::
56
57 import unittest
58 from test import support
59
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
85 if __name__ == '__main__':
86 unittest.main()
87
88 This code pattern allows the testing suite to be run by :mod:`test.regrtest`,
89 on its own as a script that supports the :mod:`unittest` CLI, or via the
90 ``python -m unittest`` CLI.
91
92 The goal for regression testing is to try to break code. This leads to a few
93 guidelines to be followed:
94
95 * The testing suite should exercise all classes, functions, and constants. This
96 includes not just the external API that is to be presented to the outside
97 world but also "private" code.
98
99 * Whitebox testing (examining the code being tested when the tests are being
100 written) is preferred. Blackbox testing (testing only the published user
101 interface) is not complete enough to make sure all boundary and edge cases
102 are tested.
103
104 * Make sure all possible values are tested including invalid ones. This makes
105 sure that not only all valid values are acceptable but also that improper
106 values are handled correctly.
107
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
126 as what type of input is used. Minimize code duplication by subclassing a
127 basic test class with a class that specifies the input::
128
129 class TestFuncAcceptsSequencesMixin:
130
131 func = mySuperWhammyFunction
132
133 def test_func(self):
134 self.func(self.arg)
135
136 class AcceptLists(TestFuncAcceptsSequencesMixin, unittest.TestCase):
137 arg = [1, 2, 3]
138
139 class AcceptStrings(TestFuncAcceptsSequencesMixin, unittest.TestCase):
140 arg = 'abc'
141
142 class AcceptTuples(TestFuncAcceptsSequencesMixin, unittest.TestCase):
143 arg = (1, 2, 3)
144
145 When using this pattern, remember that all classes that inherit from
146 :class:`unittest.TestCase` are run as tests. The :class:`!TestFuncAcceptsSequencesMixin` class in the example above
147 does not have any data and so can't be run by itself, thus it does not
148 inherit from :class:`unittest.TestCase`.
149
150
151 .. seealso::
152
153 Test Driven Development
154 A book by Kent Beck on writing tests before code.
155
156
157 .. _regrtest:
158
159 Running tests using the command-line interface
160 ----------------------------------------------
161
162 .. module:: test.regrtest
163 :synopsis: Drives the regression test suite.
164
165 The :mod:`test` package can be run as a script to drive Python's regression
166 test suite, thanks to the :option:`-m` option: :program:`python -m test`. Under
167 the hood, it uses :mod:`test.regrtest`; the call :program:`python -m
168 test.regrtest` used in previous Python versions still works. Running the
169 script by itself automatically starts running all regression tests in the
170 :mod:`test` package. It does this by finding all modules in the package whose
171 name starts with ``test_``, importing them, and executing the function
172 :func:`test_main` if present or loading the tests via
173 unittest.TestLoader.loadTestsFromModule if ``test_main`` does not exist. The
174 names of tests to execute may also be passed to the script. Specifying a single
175 regression test (:program:`python -m test test_spam`) will minimize output and
176 only print whether the test passed or failed.
177
178 Running :mod:`test` directly allows what resources are available for
179 tests to use to be set. You do this by using the ``-u`` command-line
180 option. Specifying ``all`` as the value for the ``-u`` option enables all
181 possible resources: :program:`python -m test -uall`.
182 If all but one resource is desired (a more common case), a
183 comma-separated list of resources that are not desired may be listed after
184 ``all``. The command :program:`python -m test -uall,-audio,-largefile`
185 will run :mod:`test` with all resources except the ``audio`` and
186 ``largefile`` resources. For a list of all resources and more command-line
187 options, run :program:`python -m test -h`.
188
189 Some other ways to execute the regression tests depend on what platform the
190 tests are being executed on. On Unix, you can run :program:`make test` at the
191 top-level directory where Python was built. On Windows,
192 executing :program:`rt.bat` from your :file:`PCbuild` directory will run all
193 regression tests.
194
195
196 :mod:`test.support` --- Utilities for the Python test suite
197 ===========================================================
198
199 .. module:: test.support
200 :synopsis: Support for Python's regression test suite.
201
202
203 The :mod:`test.support` module provides support for Python's regression
204 test suite.
205
206 .. note::
207
208 :mod:`test.support` is not a public module. It is documented here to help
209 Python developers write tests. The API of this module is subject to change
210 without backwards compatibility concerns between releases.
211
212
213 This module defines the following exceptions:
214
215 .. exception:: TestFailed
216
217 Exception to be raised when a test fails. This is deprecated in favor of
218 :mod:`unittest`\ -based tests and :class:`unittest.TestCase`'s assertion
219 methods.
220
221
222 .. exception:: ResourceDenied
223
224 Subclass of :exc:`unittest.SkipTest`. Raised when a resource (such as a
225 network connection) is not available. Raised by the :func:`requires`
226 function.
227
228
229 The :mod:`test.support` module defines the following constants:
230
231 .. data:: verbose
232
233 ``True`` when verbose output is enabled. Should be checked when more
234 detailed information is desired about a running test. *verbose* is set by
235 :mod:`test.regrtest`.
236
237
238 .. data:: is_jython
239
240 ``True`` if the running interpreter is Jython.
241
242
243 .. data:: is_android
244
245 ``True`` if the system is Android.
246
247
248 .. data:: unix_shell
249
250 Path for shell if not on Windows; otherwise ``None``.
251
252
253 .. data:: LOOPBACK_TIMEOUT
254
255 Timeout in seconds for tests using a network server listening on the network
256 local loopback interface like ``127.0.0.1``.
257
258 The timeout is long enough to prevent test failure: it takes into account
259 that the client and the server can run in different threads or even
260 different processes.
261
262 The timeout should be long enough for :meth:`~socket.socket.connect`,
263 :meth:`~socket.socket.recv` and :meth:`~socket.socket.send` methods of
264 :class:`socket.socket`.
265
266 Its default value is 5 seconds.
267
268 See also :data:`INTERNET_TIMEOUT`.
269
270
271 .. data:: INTERNET_TIMEOUT
272
273 Timeout in seconds for network requests going to the internet.
274
275 The timeout is short enough to prevent a test to wait for too long if the
276 internet request is blocked for whatever reason.
277
278 Usually, a timeout using :data:`INTERNET_TIMEOUT` should not mark a test as
279 failed, but skip the test instead: see
280 :func:`~test.support.socket_helper.transient_internet`.
281
282 Its default value is 1 minute.
283
284 See also :data:`LOOPBACK_TIMEOUT`.
285
286
287 .. data:: SHORT_TIMEOUT
288
289 Timeout in seconds to mark a test as failed if the test takes "too long".
290
291 The timeout value depends on the regrtest ``--timeout`` command line option.
292
293 If a test using :data:`SHORT_TIMEOUT` starts to fail randomly on slow
294 buildbots, use :data:`LONG_TIMEOUT` instead.
295
296 Its default value is 30 seconds.
297
298
299 .. data:: LONG_TIMEOUT
300
301 Timeout in seconds to detect when a test hangs.
302
303 It is long enough to reduce the risk of test failure on the slowest Python
304 buildbots. It should not be used to mark a test as failed if the test takes
305 "too long". The timeout value depends on the regrtest ``--timeout`` command
306 line option.
307
308 Its default value is 5 minutes.
309
310 See also :data:`LOOPBACK_TIMEOUT`, :data:`INTERNET_TIMEOUT` and
311 :data:`SHORT_TIMEOUT`.
312
313
314 .. data:: PGO
315
316 Set when tests can be skipped when they are not useful for PGO.
317
318
319 .. data:: PIPE_MAX_SIZE
320
321 A constant that is likely larger than the underlying OS pipe buffer size,
322 to make writes blocking.
323
324
325 .. data:: Py_DEBUG
326
327 ``True`` if Python was built with the :c:macro:`Py_DEBUG` macro
328 defined, that is, if
329 Python was :ref:`built in debug mode <debug-build>`.
330
331 .. versionadded:: 3.12
332
333
334 .. data:: SOCK_MAX_SIZE
335
336 A constant that is likely larger than the underlying OS socket buffer size,
337 to make writes blocking.
338
339
340 .. data:: TEST_SUPPORT_DIR
341
342 Set to the top level directory that contains :mod:`test.support`.
343
344
345 .. data:: TEST_HOME_DIR
346
347 Set to the top level directory for the test package.
348
349
350 .. data:: TEST_DATA_DIR
351
352 Set to the ``data`` directory within the test package.
353
354
355 .. data:: MAX_Py_ssize_t
356
357 Set to :data:`sys.maxsize` for big memory tests.
358
359
360 .. data:: max_memuse
361
362 Set by :func:`set_memlimit` as the memory limit for big memory tests.
363 Limited by :data:`MAX_Py_ssize_t`.
364
365
366 .. data:: real_max_memuse
367
368 Set by :func:`set_memlimit` as the memory limit for big memory tests. Not
369 limited by :data:`MAX_Py_ssize_t`.
370
371
372 .. data:: MISSING_C_DOCSTRINGS
373
374 Set to ``True`` if Python is built without docstrings (the
375 :c:macro:`WITH_DOC_STRINGS` macro is not defined).
376 See the :option:`configure --without-doc-strings <--without-doc-strings>` option.
377
378 See also the :data:`HAVE_DOCSTRINGS` variable.
379
380
381 .. data:: HAVE_DOCSTRINGS
382
383 Set to ``True`` if function docstrings are available.
384 See the :option:`python -OO <-O>` option, which strips docstrings of functions implemented in Python.
385
386 See also the :data:`MISSING_C_DOCSTRINGS` variable.
387
388
389 .. data:: TEST_HTTP_URL
390
391 Define the URL of a dedicated HTTP server for the network tests.
392
393
394 .. data:: ALWAYS_EQ
395
396 Object that is equal to anything. Used to test mixed type comparison.
397
398
399 .. data:: NEVER_EQ
400
401 Object that is not equal to anything (even to :data:`ALWAYS_EQ`).
402 Used to test mixed type comparison.
403
404
405 .. data:: LARGEST
406
407 Object that is greater than anything (except itself).
408 Used to test mixed type comparison.
409
410
411 .. data:: SMALLEST
412
413 Object that is less than anything (except itself).
414 Used to test mixed type comparison.
415
416
417 The :mod:`test.support` module defines the following functions:
418
419 .. function:: busy_retry(timeout, err_msg=None, /, *, error=True)
420
421 Run the loop body until ``break`` stops the loop.
422
423 After *timeout* seconds, raise an :exc:`AssertionError` if *error* is true,
424 or just stop the loop if *error* is false.
425
426 Example::
427
428 for _ in support.busy_retry(support.SHORT_TIMEOUT):
429 if check():
430 break
431
432 Example of error=False usage::
433
434 for _ in support.busy_retry(support.SHORT_TIMEOUT, error=False):
435 if check():
436 break
437 else:
438 raise RuntimeError('my custom error')
439
440 .. function:: sleeping_retry(timeout, err_msg=None, /, *, init_delay=0.010, max_delay=1.0, error=True)
441
442 Wait strategy that applies exponential backoff.
443
444 Run the loop body until ``break`` stops the loop. Sleep at each loop
445 iteration, but not at the first iteration. The sleep delay is doubled at
446 each iteration (up to *max_delay* seconds).
447
448 See :func:`busy_retry` documentation for the parameters usage.
449
450 Example raising an exception after SHORT_TIMEOUT seconds::
451
452 for _ in support.sleeping_retry(support.SHORT_TIMEOUT):
453 if check():
454 break
455
456 Example of error=False usage::
457
458 for _ in support.sleeping_retry(support.SHORT_TIMEOUT, error=False):
459 if check():
460 break
461 else:
462 raise RuntimeError('my custom error')
463
464 .. function:: is_resource_enabled(resource)
465
466 Return ``True`` if *resource* is enabled and available. The list of
467 available resources is only set when :mod:`test.regrtest` is executing the
468 tests.
469
470
471 .. function:: get_resource_value(resource)
472
473 Return the value specified for *resource* (as :samp:`-u {resource}={value}`).
474 Return ``None`` if *resource* is disabled or no value is specified.
475
476
477 .. function:: python_is_optimized()
478
479 Return ``True`` if Python was not built with ``-O0`` or ``-Og``.
480
481
482 .. function:: with_pymalloc()
483
484 Return :const:`_testcapi.WITH_PYMALLOC`.
485
486
487 .. function:: requires(resource, msg=None)
488
489 Raise :exc:`ResourceDenied` if *resource* is not available. *msg* is the
490 argument to :exc:`ResourceDenied` if it is raised. Always returns
491 ``True`` if called by a function whose ``__name__`` is ``'__main__'``.
492 Used when tests are executed by :mod:`test.regrtest`.
493
494
495 .. function:: sortdict(dict)
496
497 Return a repr of *dict* with keys sorted.
498
499
500 .. function:: findfile(filename, subdir=None)
501
502 Return the path to the file named *filename*. If no match is found
503 *filename* is returned. This does not equal a failure since it could be the
504 path to the file.
505
506 Setting *subdir* indicates a relative path to use to find the file
507 rather than looking directly in the path directories.
508
509
510 .. function:: get_pagesize()
511
512 Get size of a page in bytes.
513
514 .. versionadded:: 3.12
515
516
517 .. function:: setswitchinterval(interval)
518
519 Set the :func:`sys.setswitchinterval` to the given *interval*. Defines
520 a minimum interval for Android systems to prevent the system from hanging.
521
522
523 .. function:: check_impl_detail(**guards)
524
525 Use this check to guard CPython's implementation-specific tests or to
526 run them only on the implementations guarded by the arguments. This
527 function returns ``True`` or ``False`` depending on the host platform.
528 Example usage::
529
530 check_impl_detail() # Only on CPython (default).
531 check_impl_detail(jython=True) # Only on Jython.
532 check_impl_detail(cpython=False) # Everywhere except CPython.
533
534
535 .. function:: set_memlimit(limit)
536
537 Set the values for :data:`max_memuse` and :data:`real_max_memuse` for big
538 memory tests.
539
540
541 .. function:: record_original_stdout(stdout)
542
543 Store the value from *stdout*. It is meant to hold the stdout at the
544 time the regrtest began.
545
546
547 .. function:: get_original_stdout()
548
549 Return the original stdout set by :func:`record_original_stdout` or
550 ``sys.stdout`` if it's not set.
551
552
553 .. function:: args_from_interpreter_flags()
554
555 Return a list of command line arguments reproducing the current settings
556 in ``sys.flags`` and ``sys.warnoptions``.
557
558
559 .. function:: optim_args_from_interpreter_flags()
560
561 Return a list of command line arguments reproducing the current
562 optimization settings in ``sys.flags``.
563
564
565 .. function:: captured_stdin()
566 captured_stdout()
567 captured_stderr()
568
569 A context managers that temporarily replaces the named stream with
570 :class:`io.StringIO` object.
571
572 Example use with output streams::
573
574 with captured_stdout() as stdout, captured_stderr() as stderr:
575 print("hello")
576 print("error", file=sys.stderr)
577 assert stdout.getvalue() == "hello\n"
578 assert stderr.getvalue() == "error\n"
579
580 Example use with input stream::
581
582 with captured_stdin() as stdin:
583 stdin.write('hello\n')
584 stdin.seek(0)
585 # call test code that consumes from sys.stdin
586 captured = input()
587 self.assertEqual(captured, "hello")
588
589
590 .. function:: disable_faulthandler()
591
592 A context manager that temporary disables :mod:`faulthandler`.
593
594
595 .. function:: gc_collect()
596
597 Force as many objects as possible to be collected. This is needed because
598 timely deallocation is not guaranteed by the garbage collector. This means
599 that ``__del__`` methods may be called later than expected and weakrefs
600 may remain alive for longer than expected.
601
602
603 .. function:: disable_gc()
604
605 A context manager that disables the garbage collector on entry. On
606 exit, the garbage collector is restored to its prior state.
607
608
609 .. function:: swap_attr(obj, attr, new_val)
610
611 Context manager to swap out an attribute with a new object.
612
613 Usage::
614
615 with swap_attr(obj, "attr", 5):
616 ...
617
618 This will set ``obj.attr`` to 5 for the duration of the ``with`` block,
619 restoring the old value at the end of the block. If ``attr`` doesn't
620 exist on ``obj``, it will be created and then deleted at the end of the
621 block.
622
623 The old value (or ``None`` if it doesn't exist) will be assigned to the
624 target of the "as" clause, if there is one.
625
626
627 .. function:: swap_item(obj, attr, new_val)
628
629 Context manager to swap out an item with a new object.
630
631 Usage::
632
633 with swap_item(obj, "item", 5):
634 ...
635
636 This will set ``obj["item"]`` to 5 for the duration of the ``with`` block,
637 restoring the old value at the end of the block. If ``item`` doesn't
638 exist on ``obj``, it will be created and then deleted at the end of the
639 block.
640
641 The old value (or ``None`` if it doesn't exist) will be assigned to the
642 target of the "as" clause, if there is one.
643
644
645 .. function:: flush_std_streams()
646
647 Call the ``flush()`` method on :data:`sys.stdout` and then on
648 :data:`sys.stderr`. It can be used to make sure that the logs order is
649 consistent before writing into stderr.
650
651 .. versionadded:: 3.11
652
653
654 .. function:: print_warning(msg)
655
656 Print a warning into :data:`sys.__stderr__`. Format the message as:
657 ``f"Warning -- {msg}"``. If *msg* is made of multiple lines, add
658 ``"Warning -- "`` prefix to each line.
659
660 .. versionadded:: 3.9
661
662
663 .. function:: wait_process(pid, *, exitcode, timeout=None)
664
665 Wait until process *pid* completes and check that the process exit code is
666 *exitcode*.
667
668 Raise an :exc:`AssertionError` if the process exit code is not equal to
669 *exitcode*.
670
671 If the process runs longer than *timeout* seconds (:data:`SHORT_TIMEOUT` by
672 default), kill the process and raise an :exc:`AssertionError`. The timeout
673 feature is not available on Windows.
674
675 .. versionadded:: 3.9
676
677
678 .. function:: calcobjsize(fmt)
679
680 Return the size of the :c:type:`PyObject` whose structure members are
681 defined by *fmt*. The returned value includes the size of the Python object header and alignment.
682
683
684 .. function:: calcvobjsize(fmt)
685
686 Return the size of the :c:type:`PyVarObject` whose structure members are
687 defined by *fmt*. The returned value includes the size of the Python object header and alignment.
688
689
690 .. function:: checksizeof(test, o, size)
691
692 For testcase *test*, assert that the ``sys.getsizeof`` for *o* plus the GC
693 header size equals *size*.
694
695
696 .. decorator:: anticipate_failure(condition)
697
698 A decorator to conditionally mark tests with
699 :func:`unittest.expectedFailure`. Any use of this decorator should
700 have an associated comment identifying the relevant tracker issue.
701
702
703 .. function:: system_must_validate_cert(f)
704
705 A decorator that skips the decorated test on TLS certification validation failures.
706
707
708 .. decorator:: run_with_locale(catstr, *locales)
709
710 A decorator for running a function in a different locale, correctly
711 resetting it after it has finished. *catstr* is the locale category as
712 a string (for example ``"LC_ALL"``). The *locales* passed will be tried
713 sequentially, and the first valid locale will be used.
714
715
716 .. decorator:: run_with_tz(tz)
717
718 A decorator for running a function in a specific timezone, correctly
719 resetting it after it has finished.
720
721
722 .. decorator:: requires_freebsd_version(*min_version)
723
724 Decorator for the minimum version when running test on FreeBSD. If the
725 FreeBSD version is less than the minimum, the test is skipped.
726
727
728 .. decorator:: requires_linux_version(*min_version)
729
730 Decorator for the minimum version when running test on Linux. If the
731 Linux version is less than the minimum, the test is skipped.
732
733
734 .. decorator:: requires_mac_version(*min_version)
735
736 Decorator for the minimum version when running test on macOS. If the
737 macOS version is less than the minimum, the test is skipped.
738
739
740 .. decorator:: requires_gil_enabled
741
742 Decorator for skipping tests on the free-threaded build. If the
743 :term:`GIL` is disabled, the test is skipped.
744
745
746 .. decorator:: requires_IEEE_754
747
748 Decorator for skipping tests on non-IEEE 754 platforms.
749
750
751 .. decorator:: requires_zlib
752
753 Decorator for skipping tests if :mod:`zlib` doesn't exist.
754
755
756 .. decorator:: requires_gzip
757
758 Decorator for skipping tests if :mod:`gzip` doesn't exist.
759
760
761 .. decorator:: requires_bz2
762
763 Decorator for skipping tests if :mod:`bz2` doesn't exist.
764
765
766 .. decorator:: requires_lzma
767
768 Decorator for skipping tests if :mod:`lzma` doesn't exist.
769
770
771 .. decorator:: requires_resource(resource)
772
773 Decorator for skipping tests if *resource* is not available.
774
775
776 .. decorator:: requires_docstrings
777
778 Decorator for only running the test if :data:`HAVE_DOCSTRINGS`.
779
780
781 .. decorator:: requires_limited_api
782
783 Decorator for only running the test if :ref:`Limited C API <limited-c-api>`
784 is available.
785
786
787 .. decorator:: cpython_only
788
789 Decorator for tests only applicable to CPython.
790
791
792 .. decorator:: impl_detail(msg=None, **guards)
793
794 Decorator for invoking :func:`check_impl_detail` on *guards*. If that
795 returns ``False``, then uses *msg* as the reason for skipping the test.
796
797
798 .. decorator:: no_tracing
799
800 Decorator to temporarily turn off tracing for the duration of the test.
801
802
803 .. decorator:: refcount_test
804
805 Decorator for tests which involve reference counting. The decorator does
806 not run the test if it is not run by CPython. Any trace function is unset
807 for the duration of the test to prevent unexpected refcounts caused by
808 the trace function.
809
810
811 .. decorator:: bigmemtest(size, memuse, dry_run=True)
812
813 Decorator for bigmem tests.
814
815 *size* is a requested size for the test (in arbitrary, test-interpreted
816 units.) *memuse* is the number of bytes per unit for the test, or a good
817 estimate of it. For example, a test that needs two byte buffers, of 4 GiB
818 each, could be decorated with ``@bigmemtest(size=_4G, memuse=2)``.
819
820 The *size* argument is normally passed to the decorated test method as an
821 extra argument. If *dry_run* is ``True``, the value passed to the test
822 method may be less than the requested value. If *dry_run* is ``False``, it
823 means the test doesn't support dummy runs when ``-M`` is not specified.
824
825
826 .. decorator:: bigaddrspacetest
827
828 Decorator for tests that fill the address space.
829
830
831 .. function:: check_syntax_error(testcase, statement, errtext='', *, lineno=None, offset=None)
832
833 Test for syntax errors in *statement* by attempting to compile *statement*.
834 *testcase* is the :mod:`unittest` instance for the test. *errtext* is the
835 regular expression which should match the string representation of the
836 raised :exc:`SyntaxError`. If *lineno* is not ``None``, compares to
837 the line of the exception. If *offset* is not ``None``, compares to
838 the offset of the exception.
839
840
841 .. function:: open_urlresource(url, *args, **kw)
842
843 Open *url*. If open fails, raises :exc:`TestFailed`.
844
845
846 .. function:: reap_children()
847
848 Use this at the end of ``test_main`` whenever sub-processes are started.
849 This will help ensure that no extra children (zombies) stick around to
850 hog resources and create problems when looking for refleaks.
851
852
853 .. function:: get_attribute(obj, name)
854
855 Get an attribute, raising :exc:`unittest.SkipTest` if :exc:`AttributeError`
856 is raised.
857
858
859 .. function:: catch_unraisable_exception()
860
861 Context manager catching unraisable exception using
862 :func:`sys.unraisablehook`.
863
864 Storing the exception value (``cm.unraisable.exc_value``) creates a
865 reference cycle. The reference cycle is broken explicitly when the context
866 manager exits.
867
868 Storing the object (``cm.unraisable.object``) can resurrect it if it is set
869 to an object which is being finalized. Exiting the context manager clears
870 the stored object.
871
872 Usage::
873
874 with support.catch_unraisable_exception() as cm:
875 # code creating an "unraisable exception"
876 ...
877
878 # check the unraisable exception: use cm.unraisable
879 ...
880
881 # cm.unraisable attribute no longer exists at this point
882 # (to break a reference cycle)
883
884 .. versionadded:: 3.8
885
886
887 .. function:: load_package_tests(pkg_dir, loader, standard_tests, pattern)
888
889 Generic implementation of the :mod:`unittest` ``load_tests`` protocol for
890 use in test packages. *pkg_dir* is the root directory of the package;
891 *loader*, *standard_tests*, and *pattern* are the arguments expected by
892 ``load_tests``. In simple cases, the test package's ``__init__.py``
893 can be the following::
894
895 import os
896 from test.support import load_package_tests
897
898 def load_tests(*args):
899 return load_package_tests(os.path.dirname(__file__), *args)
900
901
902 .. function:: detect_api_mismatch(ref_api, other_api, *, ignore=())
903
904 Returns the set of attributes, functions or methods of *ref_api* not
905 found on *other_api*, except for a defined list of items to be
906 ignored in this check specified in *ignore*.
907
908 By default this skips private attributes beginning with '_' but
909 includes all magic methods, i.e. those starting and ending in '__'.
910
911 .. versionadded:: 3.5
912
913
914 .. function:: patch(test_instance, object_to_patch, attr_name, new_value)
915
916 Override *object_to_patch.attr_name* with *new_value*. Also add
917 cleanup procedure to *test_instance* to restore *object_to_patch* for
918 *attr_name*. The *attr_name* should be a valid attribute for
919 *object_to_patch*.
920
921
922 .. function:: run_in_subinterp(code)
923
924 Run *code* in subinterpreter. Raise :exc:`unittest.SkipTest` if
925 :mod:`tracemalloc` is enabled.
926
927
928 .. function:: check_free_after_iterating(test, iter, cls, args=())
929
930 Assert instances of *cls* are deallocated after iterating.
931
932
933 .. function:: missing_compiler_executable(cmd_names=[])
934
935 Check for the existence of the compiler executables whose names are listed
936 in *cmd_names* or all the compiler executables when *cmd_names* is empty
937 and return the first missing executable or ``None`` when none is found
938 missing.
939
940
941 .. function:: check__all__(test_case, module, name_of_module=None, extra=(), not_exported=())
942
943 Assert that the ``__all__`` variable of *module* contains all public names.
944
945 The module's public names (its API) are detected automatically
946 based on whether they match the public name convention and were defined in
947 *module*.
948
949 The *name_of_module* argument can specify (as a string or tuple thereof) what
950 module(s) an API could be defined in order to be detected as a public
951 API. One case for this is when *module* imports part of its public API from
952 other modules, possibly a C backend (like ``csv`` and its ``_csv``).
953
954 The *extra* argument can be a set of names that wouldn't otherwise be automatically
955 detected as "public", like objects without a proper :attr:`~definition.__module__`
956 attribute. If provided, it will be added to the automatically detected ones.
957
958 The *not_exported* argument can be a set of names that must not be treated
959 as part of the public API even though their names indicate otherwise.
960
961 Example use::
962
963 import bar
964 import foo
965 import unittest
966 from test import support
967
968 class MiscTestCase(unittest.TestCase):
969 def test__all__(self):
970 support.check__all__(self, foo)
971
972 class OtherTestCase(unittest.TestCase):
973 def test__all__(self):
974 extra = {'BAR_CONST', 'FOO_CONST'}
975 not_exported = {'baz'} # Undocumented name.
976 # bar imports part of its API from _bar.
977 support.check__all__(self, bar, ('bar', '_bar'),
978 extra=extra, not_exported=not_exported)
979
980 .. versionadded:: 3.6
981
982 .. function:: skip_if_broken_multiprocessing_synchronize()
983
984 Skip tests if the :mod:`multiprocessing.synchronize` module is missing, if
985 there is no available semaphore implementation, or if creating a lock raises
986 an :exc:`OSError`.
987
988 .. versionadded:: 3.10
989
990
991 .. function:: check_disallow_instantiation(test_case, tp, *args, **kwds)
992
993 Assert that type *tp* cannot be instantiated using *args* and *kwds*.
994
995 .. versionadded:: 3.10
996
997
998 .. function:: adjust_int_max_str_digits(max_digits)
999
1000 This function returns a context manager that will change the global
1001 :func:`sys.set_int_max_str_digits` setting for the duration of the
1002 context to allow execution of test code that needs a different limit
1003 on the number of digits when converting between an integer and string.
1004
1005 .. versionadded:: 3.11
1006
1007
1008 The :mod:`test.support` module defines the following classes:
1009
1010
1011 .. class:: SuppressCrashReport()
1012
1013 A context manager used to try to prevent crash dialog popups on tests that
1014 are expected to crash a subprocess.
1015
1016 On Windows, it disables Windows Error Reporting dialogs using
1017 `SetErrorMode <https://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx>`_.
1018
1019 On UNIX, :func:`resource.setrlimit` is used to set
1020 :const:`resource.RLIMIT_CORE`'s soft limit to 0 to prevent coredump file
1021 creation.
1022
1023 On both platforms, the old value is restored by :meth:`~object.__exit__`.
1024
1025
1026 .. class:: SaveSignals()
1027
1028 Class to save and restore signal handlers registered by the Python signal
1029 handler.
1030
1031 .. method:: save(self)
1032
1033 Save the signal handlers to a dictionary mapping signal numbers to the
1034 current signal handler.
1035
1036 .. method:: restore(self)
1037
1038 Set the signal numbers from the :meth:`save` dictionary to the saved
1039 handler.
1040
1041
1042 .. class:: Matcher()
1043
1044 .. method:: matches(self, d, **kwargs)
1045
1046 Try to match a single dict with the supplied arguments.
1047
1048
1049 .. method:: match_value(self, k, dv, v)
1050
1051 Try to match a single stored value (*dv*) with a supplied value (*v*).
1052
1053
1054 :mod:`test.support.socket_helper` --- Utilities for socket tests
1055 ================================================================
1056
1057 .. module:: test.support.socket_helper
1058 :synopsis: Support for socket tests.
1059
1060
1061 The :mod:`test.support.socket_helper` module provides support for socket tests.
1062
1063 .. versionadded:: 3.9
1064
1065
1066 .. data:: IPV6_ENABLED
1067
1068 Set to ``True`` if IPv6 is enabled on this host, ``False`` otherwise.
1069
1070
1071 .. function:: find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM)
1072
1073 Returns an unused port that should be suitable for binding. This is
1074 achieved by creating a temporary socket with the same family and type as
1075 the ``sock`` parameter (default is :const:`~socket.AF_INET`,
1076 :const:`~socket.SOCK_STREAM`),
1077 and binding it to the specified host address (defaults to ``0.0.0.0``)
1078 with the port set to 0, eliciting an unused ephemeral port from the OS.
1079 The temporary socket is then closed and deleted, and the ephemeral port is
1080 returned.
1081
1082 Either this method or :func:`bind_port` should be used for any tests
1083 where a server socket needs to be bound to a particular port for the
1084 duration of the test.
1085 Which one to use depends on whether the calling code is creating a Python
1086 socket, or if an unused port needs to be provided in a constructor
1087 or passed to an external program (i.e. the ``-accept`` argument to
1088 openssl's s_server mode). Always prefer :func:`bind_port` over
1089 :func:`find_unused_port` where possible. Using a hard coded port is
1090 discouraged since it can make multiple instances of the test impossible to
1091 run simultaneously, which is a problem for buildbots.
1092
1093
1094 .. function:: bind_port(sock, host=HOST)
1095
1096 Bind the socket to a free port and return the port number. Relies on
1097 ephemeral ports in order to ensure we are using an unbound port. This is
1098 important as many tests may be running simultaneously, especially in a
1099 buildbot environment. This method raises an exception if the
1100 ``sock.family`` is :const:`~socket.AF_INET` and ``sock.type`` is
1101 :const:`~socket.SOCK_STREAM`, and the socket has
1102 :const:`~socket.SO_REUSEADDR` or :const:`~socket.SO_REUSEPORT` set on it.
1103 Tests should never set these socket options for TCP/IP sockets.
1104 The only case for setting these options is testing multicasting via
1105 multiple UDP sockets.
1106
1107 Additionally, if the :const:`~socket.SO_EXCLUSIVEADDRUSE` socket option is
1108 available (i.e. on Windows), it will be set on the socket. This will
1109 prevent anyone else from binding to our host/port for the duration of the
1110 test.
1111
1112
1113 .. function:: bind_unix_socket(sock, addr)
1114
1115 Bind a Unix socket, raising :exc:`unittest.SkipTest` if
1116 :exc:`PermissionError` is raised.
1117
1118
1119 .. decorator:: skip_unless_bind_unix_socket
1120
1121 A decorator for running tests that require a functional ``bind()`` for Unix
1122 sockets.
1123
1124
1125 .. function:: transient_internet(resource_name, *, timeout=30.0, errnos=())
1126
1127 A context manager that raises :exc:`~test.support.ResourceDenied` when
1128 various issues with the internet connection manifest themselves as
1129 exceptions.
1130
1131
1132 :mod:`test.support.script_helper` --- Utilities for the Python execution tests
1133 ==============================================================================
1134
1135 .. module:: test.support.script_helper
1136 :synopsis: Support for Python's script execution tests.
1137
1138
1139 The :mod:`test.support.script_helper` module provides support for Python's
1140 script execution tests.
1141
1142 .. function:: interpreter_requires_environment()
1143
1144 Return ``True`` if ``sys.executable interpreter`` requires environment
1145 variables in order to be able to run at all.
1146
1147 This is designed to be used with ``@unittest.skipIf()`` to annotate tests
1148 that need to use an ``assert_python*()`` function to launch an isolated
1149 mode (``-I``) or no environment mode (``-E``) sub-interpreter process.
1150
1151 A normal build & test does not run into this situation but it can happen
1152 when trying to run the standard library test suite from an interpreter that
1153 doesn't have an obvious home with Python's current home finding logic.
1154
1155 Setting :envvar:`PYTHONHOME` is one way to get most of the testsuite to run
1156 in that situation. :envvar:`PYTHONPATH` or :envvar:`PYTHONUSERSITE` are
1157 other common environment variables that might impact whether or not the
1158 interpreter can start.
1159
1160
1161 .. function:: run_python_until_end(*args, **env_vars)
1162
1163 Set up the environment based on *env_vars* for running the interpreter
1164 in a subprocess. The values can include ``__isolated``, ``__cleanenv``,
1165 ``__cwd``, and ``TERM``.
1166
1167 .. versionchanged:: 3.9
1168 The function no longer strips whitespaces from *stderr*.
1169
1170
1171 .. function:: assert_python_ok(*args, **env_vars)
1172
1173 Assert that running the interpreter with *args* and optional environment
1174 variables *env_vars* succeeds (``rc == 0``) and return a ``(return code,
1175 stdout, stderr)`` tuple.
1176
1177 If the *__cleanenv* keyword-only parameter is set, *env_vars* is used as a fresh
1178 environment.
1179
1180 Python is started in isolated mode (command line option ``-I``),
1181 except if the *__isolated* keyword-only parameter is set to ``False``.
1182
1183 .. versionchanged:: 3.9
1184 The function no longer strips whitespaces from *stderr*.
1185
1186
1187 .. function:: assert_python_failure(*args, **env_vars)
1188
1189 Assert that running the interpreter with *args* and optional environment
1190 variables *env_vars* fails (``rc != 0``) and return a ``(return code,
1191 stdout, stderr)`` tuple.
1192
1193 See :func:`assert_python_ok` for more options.
1194
1195 .. versionchanged:: 3.9
1196 The function no longer strips whitespaces from *stderr*.
1197
1198
1199 .. function:: spawn_python(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kw)
1200
1201 Run a Python subprocess with the given arguments.
1202
1203 *kw* is extra keyword args to pass to :func:`subprocess.Popen`. Returns a
1204 :class:`subprocess.Popen` object.
1205
1206
1207 .. function:: kill_python(p)
1208
1209 Run the given :class:`subprocess.Popen` process until completion and return
1210 stdout.
1211
1212
1213 .. function:: make_script(script_dir, script_basename, source, omit_suffix=False)
1214
1215 Create script containing *source* in path *script_dir* and *script_basename*.
1216 If *omit_suffix* is ``False``, append ``.py`` to the name. Return the full
1217 script path.
1218
1219
1220 .. function:: make_zip_script(zip_dir, zip_basename, script_name, name_in_zip=None)
1221
1222 Create zip file at *zip_dir* and *zip_basename* with extension ``zip`` which
1223 contains the files in *script_name*. *name_in_zip* is the archive name.
1224 Return a tuple containing ``(full path, full path of archive name)``.
1225
1226
1227 .. function:: make_pkg(pkg_dir, init_source='')
1228
1229 Create a directory named *pkg_dir* containing an ``__init__`` file with
1230 *init_source* as its contents.
1231
1232
1233 .. function:: make_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename, \
1234 source, depth=1, compiled=False)
1235
1236 Create a zip package directory with a path of *zip_dir* and *zip_basename*
1237 containing an empty ``__init__`` file and a file *script_basename*
1238 containing the *source*. If *compiled* is ``True``, both source files will
1239 be compiled and added to the zip package. Return a tuple of the full zip
1240 path and the archive name for the zip file.
1241
1242
1243 :mod:`test.support.bytecode_helper` --- Support tools for testing correct bytecode generation
1244 =============================================================================================
1245
1246 .. module:: test.support.bytecode_helper
1247 :synopsis: Support tools for testing correct bytecode generation.
1248
1249 The :mod:`test.support.bytecode_helper` module provides support for testing
1250 and inspecting bytecode generation.
1251
1252 .. versionadded:: 3.9
1253
1254 The module defines the following class:
1255
1256 .. class:: BytecodeTestCase(unittest.TestCase)
1257
1258 This class has custom assertion methods for inspecting bytecode.
1259
1260 .. method:: BytecodeTestCase.get_disassembly_as_string(co)
1261
1262 Return the disassembly of *co* as string.
1263
1264
1265 .. method:: BytecodeTestCase.assertInBytecode(x, opname, argval=_UNSPECIFIED)
1266
1267 Return instr if *opname* is found, otherwise throws :exc:`AssertionError`.
1268
1269
1270 .. method:: BytecodeTestCase.assertNotInBytecode(x, opname, argval=_UNSPECIFIED)
1271
1272 Throws :exc:`AssertionError` if *opname* is found.
1273
1274
1275 :mod:`test.support.threading_helper` --- Utilities for threading tests
1276 ======================================================================
1277
1278 .. module:: test.support.threading_helper
1279 :synopsis: Support for threading tests.
1280
1281 The :mod:`test.support.threading_helper` module provides support for threading tests.
1282
1283 .. versionadded:: 3.10
1284
1285
1286 .. function:: join_thread(thread, timeout=None)
1287
1288 Join a *thread* within *timeout*. Raise an :exc:`AssertionError` if thread
1289 is still alive after *timeout* seconds.
1290
1291
1292 .. decorator:: reap_threads
1293
1294 Decorator to ensure the threads are cleaned up even if the test fails.
1295
1296
1297 .. function:: start_threads(threads, unlock=None)
1298
1299 Context manager to start *threads*, which is a sequence of threads.
1300 *unlock* is a function called after the threads are started, even if an
1301 exception was raised; an example would be :meth:`threading.Event.set`.
1302 ``start_threads`` will attempt to join the started threads upon exit.
1303
1304
1305 .. function:: threading_cleanup(*original_values)
1306
1307 Cleanup up threads not specified in *original_values*. Designed to emit
1308 a warning if a test leaves running threads in the background.
1309
1310
1311 .. function:: threading_setup()
1312
1313 Return current thread count and copy of dangling threads.
1314
1315
1316 .. function:: wait_threads_exit(timeout=None)
1317
1318 Context manager to wait until all threads created in the ``with`` statement
1319 exit.
1320
1321
1322 .. function:: catch_threading_exception()
1323
1324 Context manager catching :class:`threading.Thread` exception using
1325 :func:`threading.excepthook`.
1326
1327 Attributes set when an exception is caught:
1328
1329 * ``exc_type``
1330 * ``exc_value``
1331 * ``exc_traceback``
1332 * ``thread``
1333
1334 See :func:`threading.excepthook` documentation.
1335
1336 These attributes are deleted at the context manager exit.
1337
1338 Usage::
1339
1340 with threading_helper.catch_threading_exception() as cm:
1341 # code spawning a thread which raises an exception
1342 ...
1343
1344 # check the thread exception, use cm attributes:
1345 # exc_type, exc_value, exc_traceback, thread
1346 ...
1347
1348 # exc_type, exc_value, exc_traceback, thread attributes of cm no longer
1349 # exists at this point
1350 # (to avoid reference cycles)
1351
1352 .. versionadded:: 3.8
1353
1354
1355 :mod:`test.support.os_helper` --- Utilities for os tests
1356 ========================================================================
1357
1358 .. module:: test.support.os_helper
1359 :synopsis: Support for os tests.
1360
1361 The :mod:`test.support.os_helper` module provides support for os tests.
1362
1363 .. versionadded:: 3.10
1364
1365
1366 .. data:: FS_NONASCII
1367
1368 A non-ASCII character encodable by :func:`os.fsencode`.
1369
1370
1371 .. data:: SAVEDCWD
1372
1373 Set to :func:`os.getcwd`.
1374
1375
1376 .. data:: TESTFN
1377
1378 Set to a name that is safe to use as the name of a temporary file. Any
1379 temporary file that is created should be closed and unlinked (removed).
1380
1381
1382 .. data:: TESTFN_NONASCII
1383
1384 Set to a filename containing the :data:`FS_NONASCII` character, if it exists.
1385 This guarantees that if the filename exists, it can be encoded and decoded
1386 with the default filesystem encoding. This allows tests that require a
1387 non-ASCII filename to be easily skipped on platforms where they can't work.
1388
1389
1390 .. data:: TESTFN_UNENCODABLE
1391
1392 Set to a filename (str type) that should not be able to be encoded by file
1393 system encoding in strict mode. It may be ``None`` if it's not possible to
1394 generate such a filename.
1395
1396
1397 .. data:: TESTFN_UNDECODABLE
1398
1399 Set to a filename (bytes type) that should not be able to be decoded by
1400 file system encoding in strict mode. It may be ``None`` if it's not
1401 possible to generate such a filename.
1402
1403
1404 .. data:: TESTFN_UNICODE
1405
1406 Set to a non-ASCII name for a temporary file.
1407
1408
1409 .. class:: EnvironmentVarGuard()
1410
1411 Class used to temporarily set or unset environment variables. Instances can
1412 be used as a context manager and have a complete dictionary interface for
1413 querying/modifying the underlying ``os.environ``. After exit from the
1414 context manager all changes to environment variables done through this
1415 instance will be rolled back.
1416
1417 .. versionchanged:: 3.1
1418 Added dictionary interface.
1419
1420
1421 .. class:: FakePath(path)
1422
1423 Simple :term:`path-like object`. It implements the
1424 :meth:`~os.PathLike.__fspath__`
1425 method which just returns the *path* argument. If *path* is an exception,
1426 it will be raised in :meth:`!__fspath__`.
1427
1428
1429 .. method:: EnvironmentVarGuard.set(envvar, value)
1430
1431 Temporarily set the environment variable ``envvar`` to the value of
1432 ``value``.
1433
1434
1435 .. method:: EnvironmentVarGuard.unset(envvar)
1436
1437 Temporarily unset the environment variable ``envvar``.
1438
1439
1440 .. function:: can_symlink()
1441
1442 Return ``True`` if the OS supports symbolic links, ``False``
1443 otherwise.
1444
1445
1446 .. function:: can_xattr()
1447
1448 Return ``True`` if the OS supports xattr, ``False``
1449 otherwise.
1450
1451
1452 .. function:: change_cwd(path, quiet=False)
1453
1454 A context manager that temporarily changes the current working
1455 directory to *path* and yields the directory.
1456
1457 If *quiet* is ``False``, the context manager raises an exception
1458 on error. Otherwise, it issues only a warning and keeps the current
1459 working directory the same.
1460
1461
1462 .. function:: create_empty_file(filename)
1463
1464 Create an empty file with *filename*. If it already exists, truncate it.
1465
1466
1467 .. function:: fd_count()
1468
1469 Count the number of open file descriptors.
1470
1471
1472 .. function:: fs_is_case_insensitive(directory)
1473
1474 Return ``True`` if the file system for *directory* is case-insensitive.
1475
1476
1477 .. function:: make_bad_fd()
1478
1479 Create an invalid file descriptor by opening and closing a temporary file,
1480 and returning its descriptor.
1481
1482
1483 .. function:: rmdir(filename)
1484
1485 Call :func:`os.rmdir` on *filename*. On Windows platforms, this is
1486 wrapped with a wait loop that checks for the existence of the file,
1487 which is needed due to antivirus programs that can hold files open and prevent
1488 deletion.
1489
1490
1491 .. function:: rmtree(path)
1492
1493 Call :func:`shutil.rmtree` on *path* or call :func:`os.lstat` and
1494 :func:`os.rmdir` to remove a path and its contents. As with :func:`rmdir`,
1495 on Windows platforms
1496 this is wrapped with a wait loop that checks for the existence of the files.
1497
1498
1499 .. decorator:: skip_unless_symlink
1500
1501 A decorator for running tests that require support for symbolic links.
1502
1503
1504 .. decorator:: skip_unless_xattr
1505
1506 A decorator for running tests that require support for xattr.
1507
1508
1509 .. function:: temp_cwd(name='tempcwd', quiet=False)
1510
1511 A context manager that temporarily creates a new directory and
1512 changes the current working directory (CWD).
1513
1514 The context manager creates a temporary directory in the current
1515 directory with name *name* before temporarily changing the current
1516 working directory. If *name* is ``None``, the temporary directory is
1517 created using :func:`tempfile.mkdtemp`.
1518
1519 If *quiet* is ``False`` and it is not possible to create or change
1520 the CWD, an error is raised. Otherwise, only a warning is raised
1521 and the original CWD is used.
1522
1523
1524 .. function:: temp_dir(path=None, quiet=False)
1525
1526 A context manager that creates a temporary directory at *path* and
1527 yields the directory.
1528
1529 If *path* is ``None``, the temporary directory is created using
1530 :func:`tempfile.mkdtemp`. If *quiet* is ``False``, the context manager
1531 raises an exception on error. Otherwise, if *path* is specified and
1532 cannot be created, only a warning is issued.
1533
1534
1535 .. function:: temp_umask(umask)
1536
1537 A context manager that temporarily sets the process umask.
1538
1539
1540 .. function:: unlink(filename)
1541
1542 Call :func:`os.unlink` on *filename*. As with :func:`rmdir`,
1543 on Windows platforms, this is
1544 wrapped with a wait loop that checks for the existence of the file.
1545
1546
1547 :mod:`test.support.import_helper` --- Utilities for import tests
1548 ================================================================
1549
1550 .. module:: test.support.import_helper
1551 :synopsis: Support for import tests.
1552
1553 The :mod:`test.support.import_helper` module provides support for import tests.
1554
1555 .. versionadded:: 3.10
1556
1557
1558 .. function:: forget(module_name)
1559
1560 Remove the module named *module_name* from ``sys.modules`` and delete any
1561 byte-compiled files of the module.
1562
1563
1564 .. function:: import_fresh_module(name, fresh=(), blocked=(), deprecated=False)
1565
1566 This function imports and returns a fresh copy of the named Python module
1567 by removing the named module from ``sys.modules`` before doing the import.
1568 Note that unlike :func:`reload`, the original module is not affected by
1569 this operation.
1570
1571 *fresh* is an iterable of additional module names that are also removed
1572 from the ``sys.modules`` cache before doing the import.
1573
1574 *blocked* is an iterable of module names that are replaced with ``None``
1575 in the module cache during the import to ensure that attempts to import
1576 them raise :exc:`ImportError`.
1577
1578 The named module and any modules named in the *fresh* and *blocked*
1579 parameters are saved before starting the import and then reinserted into
1580 ``sys.modules`` when the fresh import is complete.
1581
1582 Module and package deprecation messages are suppressed during this import
1583 if *deprecated* is ``True``.
1584
1585 This function will raise :exc:`ImportError` if the named module cannot be
1586 imported.
1587
1588 Example use::
1589
1590 # Get copies of the warnings module for testing without affecting the
1591 # version being used by the rest of the test suite. One copy uses the
1592 # C implementation, the other is forced to use the pure Python fallback
1593 # implementation
1594 py_warnings = import_fresh_module('warnings', blocked=['_warnings'])
1595 c_warnings = import_fresh_module('warnings', fresh=['_warnings'])
1596
1597 .. versionadded:: 3.1
1598
1599
1600 .. function:: import_module(name, deprecated=False, *, required_on=())
1601
1602 This function imports and returns the named module. Unlike a normal
1603 import, this function raises :exc:`unittest.SkipTest` if the module
1604 cannot be imported.
1605
1606 Module and package deprecation messages are suppressed during this import
1607 if *deprecated* is ``True``. If a module is required on a platform but
1608 optional for others, set *required_on* to an iterable of platform prefixes
1609 which will be compared against :data:`sys.platform`.
1610
1611 .. versionadded:: 3.1
1612
1613
1614 .. function:: modules_setup()
1615
1616 Return a copy of :data:`sys.modules`.
1617
1618
1619 .. function:: modules_cleanup(oldmodules)
1620
1621 Remove modules except for *oldmodules* and ``encodings`` in order to
1622 preserve internal cache.
1623
1624
1625 .. function:: unload(name)
1626
1627 Delete *name* from ``sys.modules``.
1628
1629
1630 .. function:: make_legacy_pyc(source)
1631
1632 Move a :pep:`3147`/:pep:`488` pyc file to its legacy pyc location and return the file
1633 system path to the legacy pyc file. The *source* value is the file system
1634 path to the source file. It does not need to exist, however the PEP
1635 3147/488 pyc file must exist.
1636
1637
1638 .. class:: CleanImport(*module_names)
1639
1640 A context manager to force import to return a new module reference. This
1641 is useful for testing module-level behaviors, such as the emission of a
1642 :exc:`DeprecationWarning` on import. Example usage::
1643
1644 with CleanImport('foo'):
1645 importlib.import_module('foo') # New reference.
1646
1647
1648 .. class:: DirsOnSysPath(*paths)
1649
1650 A context manager to temporarily add directories to :data:`sys.path`.
1651
1652 This makes a copy of :data:`sys.path`, appends any directories given
1653 as positional arguments, then reverts :data:`sys.path` to the copied
1654 settings when the context ends.
1655
1656 Note that *all* :data:`sys.path` modifications in the body of the
1657 context manager, including replacement of the object,
1658 will be reverted at the end of the block.
1659
1660
1661 :mod:`test.support.warnings_helper` --- Utilities for warnings tests
1662 ====================================================================
1663
1664 .. module:: test.support.warnings_helper
1665 :synopsis: Support for warnings tests.
1666
1667 The :mod:`test.support.warnings_helper` module provides support for warnings tests.
1668
1669 .. versionadded:: 3.10
1670
1671
1672 .. function:: ignore_warnings(*, category)
1673
1674 Suppress warnings that are instances of *category*,
1675 which must be :exc:`Warning` or a subclass.
1676 Roughly equivalent to :func:`warnings.catch_warnings`
1677 with :meth:`warnings.simplefilter('ignore', category=category) <warnings.simplefilter>`.
1678 For example::
1679
1680 @warning_helper.ignore_warnings(category=DeprecationWarning)
1681 def test_suppress_warning():
1682 # do something
1683
1684 .. versionadded:: 3.8
1685
1686
1687 .. function:: check_no_resource_warning(testcase)
1688
1689 Context manager to check that no :exc:`ResourceWarning` was raised. You
1690 must remove the object which may emit :exc:`ResourceWarning` before the
1691 end of the context manager.
1692
1693
1694 .. function:: check_syntax_warning(testcase, statement, errtext='', *, lineno=1, offset=None)
1695
1696 Test for syntax warning in *statement* by attempting to compile *statement*.
1697 Test also that the :exc:`SyntaxWarning` is emitted only once, and that it
1698 will be converted to a :exc:`SyntaxError` when turned into error.
1699 *testcase* is the :mod:`unittest` instance for the test. *errtext* is the
1700 regular expression which should match the string representation of the
1701 emitted :exc:`SyntaxWarning` and raised :exc:`SyntaxError`. If *lineno*
1702 is not ``None``, compares to the line of the warning and exception.
1703 If *offset* is not ``None``, compares to the offset of the exception.
1704
1705 .. versionadded:: 3.8
1706
1707
1708 .. function:: check_warnings(*filters, quiet=True)
1709
1710 A convenience wrapper for :func:`warnings.catch_warnings` that makes it
1711 easier to test that a warning was correctly raised. It is approximately
1712 equivalent to calling ``warnings.catch_warnings(record=True)`` with
1713 :meth:`warnings.simplefilter` set to ``always`` and with the option to
1714 automatically validate the results that are recorded.
1715
1716 ``check_warnings`` accepts 2-tuples of the form ``("message regexp",
1717 WarningCategory)`` as positional arguments. If one or more *filters* are
1718 provided, or if the optional keyword argument *quiet* is ``False``,
1719 it checks to make sure the warnings are as expected: each specified filter
1720 must match at least one of the warnings raised by the enclosed code or the
1721 test fails, and if any warnings are raised that do not match any of the
1722 specified filters the test fails. To disable the first of these checks,
1723 set *quiet* to ``True``.
1724
1725 If no arguments are specified, it defaults to::
1726
1727 check_warnings(("", Warning), quiet=True)
1728
1729 In this case all warnings are caught and no errors are raised.
1730
1731 On entry to the context manager, a :class:`WarningRecorder` instance is
1732 returned. The underlying warnings list from
1733 :func:`~warnings.catch_warnings` is available via the recorder object's
1734 :attr:`warnings` attribute. As a convenience, the attributes of the object
1735 representing the most recent warning can also be accessed directly through
1736 the recorder object (see example below). If no warning has been raised,
1737 then any of the attributes that would otherwise be expected on an object
1738 representing a warning will return ``None``.
1739
1740 The recorder object also has a :meth:`reset` method, which clears the
1741 warnings list.
1742
1743 The context manager is designed to be used like this::
1744
1745 with check_warnings(("assertion is always true", SyntaxWarning),
1746 ("", UserWarning)):
1747 exec('assert(False, "Hey!")')
1748 warnings.warn(UserWarning("Hide me!"))
1749
1750 In this case if either warning was not raised, or some other warning was
1751 raised, :func:`check_warnings` would raise an error.
1752
1753 When a test needs to look more deeply into the warnings, rather than
1754 just checking whether or not they occurred, code like this can be used::
1755
1756 with check_warnings(quiet=True) as w:
1757 warnings.warn("foo")
1758 assert str(w.args[0]) == "foo"
1759 warnings.warn("bar")
1760 assert str(w.args[0]) == "bar"
1761 assert str(w.warnings[0].args[0]) == "foo"
1762 assert str(w.warnings[1].args[0]) == "bar"
1763 w.reset()
1764 assert len(w.warnings) == 0
1765
1766
1767 Here all warnings will be caught, and the test code tests the captured
1768 warnings directly.
1769
1770 .. versionchanged:: 3.2
1771 New optional arguments *filters* and *quiet*.
1772
1773
1774 .. class:: WarningsRecorder()
1775
1776 Class used to record warnings for unit tests. See documentation of
1777 :func:`check_warnings` above for more details.