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