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:: TESTFN 241 242 Set to a name that is safe to use as the name of a temporary file. Any 243 temporary file that is created should be closed and unlinked (removed). 244 245 246The :mod:`test.support` module defines the following functions: 247 248.. function:: forget(module_name) 249 250 Remove the module named *module_name* from ``sys.modules`` and delete any 251 byte-compiled files of the module. 252 253 254.. function:: is_resource_enabled(resource) 255 256 Return ``True`` if *resource* is enabled and available. The list of 257 available resources is only set when :mod:`test.regrtest` is executing the 258 tests. 259 260 261.. function:: requires(resource, msg=None) 262 263 Raise :exc:`ResourceDenied` if *resource* is not available. *msg* is the 264 argument to :exc:`ResourceDenied` if it is raised. Always returns 265 ``True`` if called by a function whose ``__name__`` is ``'__main__'``. 266 Used when tests are executed by :mod:`test.regrtest`. 267 268 269.. function:: findfile(filename, subdir=None) 270 271 Return the path to the file named *filename*. If no match is found 272 *filename* is returned. This does not equal a failure since it could be the 273 path to the file. 274 275 Setting *subdir* indicates a relative path to use to find the file 276 rather than looking directly in the path directories. 277 278 279.. function:: run_unittest(\*classes) 280 281 Execute :class:`unittest.TestCase` subclasses passed to the function. The 282 function scans the classes for methods starting with the prefix ``test_`` 283 and executes the tests individually. 284 285 It is also legal to pass strings as parameters; these should be keys in 286 ``sys.modules``. Each associated module will be scanned by 287 ``unittest.TestLoader.loadTestsFromModule()``. This is usually seen in the 288 following :func:`test_main` function:: 289 290 def test_main(): 291 support.run_unittest(__name__) 292 293 This will run all tests defined in the named module. 294 295 296.. function:: run_doctest(module, verbosity=None) 297 298 Run :func:`doctest.testmod` on the given *module*. Return 299 ``(failure_count, test_count)``. 300 301 If *verbosity* is ``None``, :func:`doctest.testmod` is run with verbosity 302 set to :data:`verbose`. Otherwise, it is run with verbosity set to 303 ``None``. 304 305.. function:: check_warnings(\*filters, quiet=True) 306 307 A convenience wrapper for :func:`warnings.catch_warnings()` that makes it 308 easier to test that a warning was correctly raised. It is approximately 309 equivalent to calling ``warnings.catch_warnings(record=True)`` with 310 :meth:`warnings.simplefilter` set to ``always`` and with the option to 311 automatically validate the results that are recorded. 312 313 ``check_warnings`` accepts 2-tuples of the form ``("message regexp", 314 WarningCategory)`` as positional arguments. If one or more *filters* are 315 provided, or if the optional keyword argument *quiet* is ``False``, 316 it checks to make sure the warnings are as expected: each specified filter 317 must match at least one of the warnings raised by the enclosed code or the 318 test fails, and if any warnings are raised that do not match any of the 319 specified filters the test fails. To disable the first of these checks, 320 set *quiet* to ``True``. 321 322 If no arguments are specified, it defaults to:: 323 324 check_warnings(("", Warning), quiet=True) 325 326 In this case all warnings are caught and no errors are raised. 327 328 On entry to the context manager, a :class:`WarningRecorder` instance is 329 returned. The underlying warnings list from 330 :func:`~warnings.catch_warnings` is available via the recorder object's 331 :attr:`warnings` attribute. As a convenience, the attributes of the object 332 representing the most recent warning can also be accessed directly through 333 the recorder object (see example below). If no warning has been raised, 334 then any of the attributes that would otherwise be expected on an object 335 representing a warning will return ``None``. 336 337 The recorder object also has a :meth:`reset` method, which clears the 338 warnings list. 339 340 The context manager is designed to be used like this:: 341 342 with check_warnings(("assertion is always true", SyntaxWarning), 343 ("", UserWarning)): 344 exec('assert(False, "Hey!")') 345 warnings.warn(UserWarning("Hide me!")) 346 347 In this case if either warning was not raised, or some other warning was 348 raised, :func:`check_warnings` would raise an error. 349 350 When a test needs to look more deeply into the warnings, rather than 351 just checking whether or not they occurred, code like this can be used:: 352 353 with check_warnings(quiet=True) as w: 354 warnings.warn("foo") 355 assert str(w.args[0]) == "foo" 356 warnings.warn("bar") 357 assert str(w.args[0]) == "bar" 358 assert str(w.warnings[0].args[0]) == "foo" 359 assert str(w.warnings[1].args[0]) == "bar" 360 w.reset() 361 assert len(w.warnings) == 0 362 363 364 Here all warnings will be caught, and the test code tests the captured 365 warnings directly. 366 367 .. versionchanged:: 3.2 368 New optional arguments *filters* and *quiet*. 369 370 371.. function:: captured_stdin() 372 captured_stdout() 373 captured_stderr() 374 375 A context managers that temporarily replaces the named stream with 376 :class:`io.StringIO` object. 377 378 Example use with output streams:: 379 380 with captured_stdout() as stdout, captured_stderr() as stderr: 381 print("hello") 382 print("error", file=sys.stderr) 383 assert stdout.getvalue() == "hello\n" 384 assert stderr.getvalue() == "error\n" 385 386 Example use with input stream:: 387 388 with captured_stdin() as stdin: 389 stdin.write('hello\n') 390 stdin.seek(0) 391 # call test code that consumes from sys.stdin 392 captured = input() 393 self.assertEqual(captured, "hello") 394 395 396.. function:: temp_dir(path=None, quiet=False) 397 398 A context manager that creates a temporary directory at *path* and 399 yields the directory. 400 401 If *path* is ``None``, the temporary directory is created using 402 :func:`tempfile.mkdtemp`. If *quiet* is ``False``, the context manager 403 raises an exception on error. Otherwise, if *path* is specified and 404 cannot be created, only a warning is issued. 405 406 407.. function:: change_cwd(path, quiet=False) 408 409 A context manager that temporarily changes the current working 410 directory to *path* and yields the directory. 411 412 If *quiet* is ``False``, the context manager raises an exception 413 on error. Otherwise, it issues only a warning and keeps the current 414 working directory the same. 415 416 417.. function:: temp_cwd(name='tempcwd', quiet=False) 418 419 A context manager that temporarily creates a new directory and 420 changes the current working directory (CWD). 421 422 The context manager creates a temporary directory in the current 423 directory with name *name* before temporarily changing the current 424 working directory. If *name* is ``None``, the temporary directory is 425 created using :func:`tempfile.mkdtemp`. 426 427 If *quiet* is ``False`` and it is not possible to create or change 428 the CWD, an error is raised. Otherwise, only a warning is raised 429 and the original CWD is used. 430 431 432.. function:: temp_umask(umask) 433 434 A context manager that temporarily sets the process umask. 435 436 437.. function:: can_symlink() 438 439 Return ``True`` if the OS supports symbolic links, ``False`` 440 otherwise. 441 442 443.. decorator:: skip_unless_symlink() 444 445 A decorator for running tests that require support for symbolic links. 446 447 448.. decorator:: anticipate_failure(condition) 449 450 A decorator to conditionally mark tests with 451 :func:`unittest.expectedFailure`. Any use of this decorator should 452 have an associated comment identifying the relevant tracker issue. 453 454 455.. decorator:: run_with_locale(catstr, *locales) 456 457 A decorator for running a function in a different locale, correctly 458 resetting it after it has finished. *catstr* is the locale category as 459 a string (for example ``"LC_ALL"``). The *locales* passed will be tried 460 sequentially, and the first valid locale will be used. 461 462 463.. function:: make_bad_fd() 464 465 Create an invalid file descriptor by opening and closing a temporary file, 466 and returning its descriptor. 467 468 469.. function:: import_module(name, deprecated=False) 470 471 This function imports and returns the named module. Unlike a normal 472 import, this function raises :exc:`unittest.SkipTest` if the module 473 cannot be imported. 474 475 Module and package deprecation messages are suppressed during this import 476 if *deprecated* is ``True``. 477 478 .. versionadded:: 3.1 479 480 481.. function:: import_fresh_module(name, fresh=(), blocked=(), deprecated=False) 482 483 This function imports and returns a fresh copy of the named Python module 484 by removing the named module from ``sys.modules`` before doing the import. 485 Note that unlike :func:`reload`, the original module is not affected by 486 this operation. 487 488 *fresh* is an iterable of additional module names that are also removed 489 from the ``sys.modules`` cache before doing the import. 490 491 *blocked* is an iterable of module names that are replaced with ``None`` 492 in the module cache during the import to ensure that attempts to import 493 them raise :exc:`ImportError`. 494 495 The named module and any modules named in the *fresh* and *blocked* 496 parameters are saved before starting the import and then reinserted into 497 ``sys.modules`` when the fresh import is complete. 498 499 Module and package deprecation messages are suppressed during this import 500 if *deprecated* is ``True``. 501 502 This function will raise :exc:`ImportError` if the named module cannot be 503 imported. 504 505 Example use:: 506 507 # Get copies of the warnings module for testing without affecting the 508 # version being used by the rest of the test suite. One copy uses the 509 # C implementation, the other is forced to use the pure Python fallback 510 # implementation 511 py_warnings = import_fresh_module('warnings', blocked=['_warnings']) 512 c_warnings = import_fresh_module('warnings', fresh=['_warnings']) 513 514 .. versionadded:: 3.1 515 516 517.. function:: bind_port(sock, host=HOST) 518 519 Bind the socket to a free port and return the port number. Relies on 520 ephemeral ports in order to ensure we are using an unbound port. This is 521 important as many tests may be running simultaneously, especially in a 522 buildbot environment. This method raises an exception if the 523 ``sock.family`` is :const:`~socket.AF_INET` and ``sock.type`` is 524 :const:`~socket.SOCK_STREAM`, and the socket has 525 :const:`~socket.SO_REUSEADDR` or :const:`~socket.SO_REUSEPORT` set on it. 526 Tests should never set these socket options for TCP/IP sockets. 527 The only case for setting these options is testing multicasting via 528 multiple UDP sockets. 529 530 Additionally, if the :const:`~socket.SO_EXCLUSIVEADDRUSE` socket option is 531 available (i.e. on Windows), it will be set on the socket. This will 532 prevent anyone else from binding to our host/port for the duration of the 533 test. 534 535 536.. function:: find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM) 537 538 Returns an unused port that should be suitable for binding. This is 539 achieved by creating a temporary socket with the same family and type as 540 the ``sock`` parameter (default is :const:`~socket.AF_INET`, 541 :const:`~socket.SOCK_STREAM`), 542 and binding it to the specified host address (defaults to ``0.0.0.0``) 543 with the port set to 0, eliciting an unused ephemeral port from the OS. 544 The temporary socket is then closed and deleted, and the ephemeral port is 545 returned. 546 547 Either this method or :func:`bind_port` should be used for any tests 548 where a server socket needs to be bound to a particular port for the 549 duration of the test. 550 Which one to use depends on whether the calling code is creating a python 551 socket, or if an unused port needs to be provided in a constructor 552 or passed to an external program (i.e. the ``-accept`` argument to 553 openssl's s_server mode). Always prefer :func:`bind_port` over 554 :func:`find_unused_port` where possible. Using a hard coded port is 555 discouraged since it can make multiple instances of the test impossible to 556 run simultaneously, which is a problem for buildbots. 557 558 559.. function:: load_package_tests(pkg_dir, loader, standard_tests, pattern) 560 561 Generic implementation of the :mod:`unittest` ``load_tests`` protocol for 562 use in test packages. *pkg_dir* is the root directory of the package; 563 *loader*, *standard_tests*, and *pattern* are the arguments expected by 564 ``load_tests``. In simple cases, the test package's ``__init__.py`` 565 can be the following:: 566 567 import os 568 from test.support import load_package_tests 569 570 def load_tests(*args): 571 return load_package_tests(os.path.dirname(__file__), *args) 572 573.. function:: detect_api_mismatch(ref_api, other_api, *, ignore=()): 574 575 Returns the set of attributes, functions or methods of *ref_api* not 576 found on *other_api*, except for a defined list of items to be 577 ignored in this check specified in *ignore*. 578 579 By default this skips private attributes beginning with '_' but 580 includes all magic methods, i.e. those starting and ending in '__'. 581 582 .. versionadded:: 3.5 583 584 585.. function:: check__all__(test_case, module, name_of_module=None, extra=(), blacklist=()) 586 587 Assert that the ``__all__`` variable of *module* contains all public names. 588 589 The module's public names (its API) are detected automatically 590 based on whether they match the public name convention and were defined in 591 *module*. 592 593 The *name_of_module* argument can specify (as a string or tuple thereof) what 594 module(s) an API could be defined in in order to be detected as a public 595 API. One case for this is when *module* imports part of its public API from 596 other modules, possibly a C backend (like ``csv`` and its ``_csv``). 597 598 The *extra* argument can be a set of names that wouldn't otherwise be automatically 599 detected as "public", like objects without a proper ``__module__`` 600 attribute. If provided, it will be added to the automatically detected ones. 601 602 The *blacklist* argument can be a set of names that must not be treated as part of 603 the public API even though their names indicate otherwise. 604 605 Example use:: 606 607 import bar 608 import foo 609 import unittest 610 from test import support 611 612 class MiscTestCase(unittest.TestCase): 613 def test__all__(self): 614 support.check__all__(self, foo) 615 616 class OtherTestCase(unittest.TestCase): 617 def test__all__(self): 618 extra = {'BAR_CONST', 'FOO_CONST'} 619 blacklist = {'baz'} # Undocumented name. 620 # bar imports part of its API from _bar. 621 support.check__all__(self, bar, ('bar', '_bar'), 622 extra=extra, blacklist=blacklist) 623 624 .. versionadded:: 3.6 625 626 627The :mod:`test.support` module defines the following classes: 628 629.. class:: TransientResource(exc, **kwargs) 630 631 Instances are a context manager that raises :exc:`ResourceDenied` if the 632 specified exception type is raised. Any keyword arguments are treated as 633 attribute/value pairs to be compared against any exception raised within the 634 :keyword:`with` statement. Only if all pairs match properly against 635 attributes on the exception is :exc:`ResourceDenied` raised. 636 637 638.. class:: EnvironmentVarGuard() 639 640 Class used to temporarily set or unset environment variables. Instances can 641 be used as a context manager and have a complete dictionary interface for 642 querying/modifying the underlying ``os.environ``. After exit from the 643 context manager all changes to environment variables done through this 644 instance will be rolled back. 645 646 .. versionchanged:: 3.1 647 Added dictionary interface. 648 649.. method:: EnvironmentVarGuard.set(envvar, value) 650 651 Temporarily set the environment variable ``envvar`` to the value of 652 ``value``. 653 654 655.. method:: EnvironmentVarGuard.unset(envvar) 656 657 Temporarily unset the environment variable ``envvar``. 658 659 660.. class:: SuppressCrashReport() 661 662 A context manager used to try to prevent crash dialog popups on tests that 663 are expected to crash a subprocess. 664 665 On Windows, it disables Windows Error Reporting dialogs using 666 `SetErrorMode <https://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx>`_. 667 668 On UNIX, :func:`resource.setrlimit` is used to set 669 :attr:`resource.RLIMIT_CORE`'s soft limit to 0 to prevent coredump file 670 creation. 671 672 On both platforms, the old value is restored by :meth:`__exit__`. 673 674 675.. class:: WarningsRecorder() 676 677 Class used to record warnings for unit tests. See documentation of 678 :func:`check_warnings` above for more details. 679