Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 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 | .. sectionauthor:: Brett Cannon <brett@python.org> |
| 7 | |
Antoine Pitrou | 197c9c9 | 2010-12-18 12:33:06 +0000 | [diff] [blame] | 8 | .. note:: |
Antoine Pitrou | 36730e8 | 2010-12-12 18:25:25 +0000 | [diff] [blame] | 9 | The :mod:`test` package is meant for internal use by Python only. It is |
| 10 | documented for the benefit of the core developers of Python. Any use of |
| 11 | this package outside of Python's standard library is discouraged as code |
| 12 | mentioned here can change or be removed without notice between releases of |
| 13 | Python. |
Brett Cannon | 3a4e50c | 2010-07-23 11:31:31 +0000 | [diff] [blame] | 14 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 15 | |
| 16 | The :mod:`test` package contains all regression tests for Python as well as the |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 17 | modules :mod:`test.support` and :mod:`test.regrtest`. |
| 18 | :mod:`test.support` is used to enhance your tests while |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 19 | :mod:`test.regrtest` drives the testing suite. |
| 20 | |
| 21 | Each module in the :mod:`test` package whose name starts with ``test_`` is a |
| 22 | testing suite for a specific module or feature. All new tests should be written |
| 23 | using the :mod:`unittest` or :mod:`doctest` module. Some older tests are |
| 24 | written using a "traditional" testing style that compares output printed to |
| 25 | ``sys.stdout``; this style of test is considered deprecated. |
| 26 | |
| 27 | |
| 28 | .. seealso:: |
| 29 | |
| 30 | Module :mod:`unittest` |
| 31 | Writing PyUnit regression tests. |
| 32 | |
| 33 | Module :mod:`doctest` |
| 34 | Tests embedded in documentation strings. |
| 35 | |
| 36 | |
| 37 | .. _writing-tests: |
| 38 | |
| 39 | Writing Unit Tests for the :mod:`test` package |
| 40 | ---------------------------------------------- |
| 41 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 42 | It is preferred that tests that use the :mod:`unittest` module follow a few |
| 43 | guidelines. One is to name the test module by starting it with ``test_`` and end |
| 44 | it with the name of the module being tested. The test methods in the test module |
| 45 | should start with ``test_`` and end with a description of what the method is |
| 46 | testing. This is needed so that the methods are recognized by the test driver as |
| 47 | test methods. Also, no documentation string for the method should be included. A |
| 48 | comment (such as ``# Tests function returns only True or False``) should be used |
| 49 | to provide documentation for test methods. This is done because documentation |
| 50 | strings get printed out if they exist and thus what test is being run is not |
| 51 | stated. |
| 52 | |
| 53 | A basic boilerplate is often used:: |
| 54 | |
| 55 | import unittest |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 56 | from test import support |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 57 | |
| 58 | class MyTestCase1(unittest.TestCase): |
| 59 | |
| 60 | # Only use setUp() and tearDown() if necessary |
| 61 | |
| 62 | def setUp(self): |
| 63 | ... code to execute in preparation for tests ... |
| 64 | |
| 65 | def tearDown(self): |
| 66 | ... code to execute to clean up after tests ... |
| 67 | |
| 68 | def test_feature_one(self): |
| 69 | # Test feature one. |
| 70 | ... testing code ... |
| 71 | |
| 72 | def test_feature_two(self): |
| 73 | # Test feature two. |
| 74 | ... testing code ... |
| 75 | |
| 76 | ... more test methods ... |
| 77 | |
| 78 | class MyTestCase2(unittest.TestCase): |
| 79 | ... same structure as MyTestCase1 ... |
| 80 | |
| 81 | ... more test classes ... |
| 82 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 83 | if __name__ == '__main__': |
R David Murray | 78fc25c | 2012-04-09 08:55:42 -0400 | [diff] [blame] | 84 | unittest.main() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 85 | |
R David Murray | 78fc25c | 2012-04-09 08:55:42 -0400 | [diff] [blame] | 86 | This code pattern allows the testing suite to be run by :mod:`test.regrtest`, |
| 87 | on its own as a script that supports the :mod:`unittest` CLI, or via the |
Georg Brandl | 6b4c847 | 2014-10-30 22:26:26 +0100 | [diff] [blame] | 88 | ``python -m unittest`` CLI. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 89 | |
| 90 | The goal for regression testing is to try to break code. This leads to a few |
| 91 | guidelines to be followed: |
| 92 | |
| 93 | * The testing suite should exercise all classes, functions, and constants. This |
Florent Xicluna | 53b506be | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 94 | includes not just the external API that is to be presented to the outside |
| 95 | world but also "private" code. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 96 | |
| 97 | * Whitebox testing (examining the code being tested when the tests are being |
| 98 | written) is preferred. Blackbox testing (testing only the published user |
Florent Xicluna | 53b506be | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 99 | interface) is not complete enough to make sure all boundary and edge cases |
| 100 | are tested. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 101 | |
| 102 | * Make sure all possible values are tested including invalid ones. This makes |
Florent Xicluna | 53b506be | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 103 | sure that not only all valid values are acceptable but also that improper |
| 104 | values are handled correctly. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 105 | |
| 106 | * Exhaust as many code paths as possible. Test where branching occurs and thus |
| 107 | tailor input to make sure as many different paths through the code are taken. |
| 108 | |
| 109 | * Add an explicit test for any bugs discovered for the tested code. This will |
| 110 | make sure that the error does not crop up again if the code is changed in the |
| 111 | future. |
| 112 | |
| 113 | * Make sure to clean up after your tests (such as close and remove all temporary |
| 114 | files). |
| 115 | |
| 116 | * If a test is dependent on a specific condition of the operating system then |
| 117 | verify the condition already exists before attempting the test. |
| 118 | |
| 119 | * Import as few modules as possible and do it as soon as possible. This |
| 120 | minimizes external dependencies of tests and also minimizes possible anomalous |
| 121 | behavior from side-effects of importing a module. |
| 122 | |
| 123 | * Try to maximize code reuse. On occasion, tests will vary by something as small |
Florent Xicluna | 53b506be | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 124 | as what type of input is used. Minimize code duplication by subclassing a |
| 125 | basic test class with a class that specifies the input:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 126 | |
R David Murray | 78fc25c | 2012-04-09 08:55:42 -0400 | [diff] [blame] | 127 | class TestFuncAcceptsSequencesMixin: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 128 | |
| 129 | func = mySuperWhammyFunction |
| 130 | |
| 131 | def test_func(self): |
| 132 | self.func(self.arg) |
| 133 | |
R David Murray | 78fc25c | 2012-04-09 08:55:42 -0400 | [diff] [blame] | 134 | class AcceptLists(TestFuncAcceptsSequencesMixin, unittest.TestCase): |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 135 | arg = [1, 2, 3] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 136 | |
R David Murray | 78fc25c | 2012-04-09 08:55:42 -0400 | [diff] [blame] | 137 | class AcceptStrings(TestFuncAcceptsSequencesMixin, unittest.TestCase): |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 138 | arg = 'abc' |
| 139 | |
R David Murray | 78fc25c | 2012-04-09 08:55:42 -0400 | [diff] [blame] | 140 | class AcceptTuples(TestFuncAcceptsSequencesMixin, unittest.TestCase): |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 141 | arg = (1, 2, 3) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 142 | |
R David Murray | 78fc25c | 2012-04-09 08:55:42 -0400 | [diff] [blame] | 143 | When using this pattern, remember that all classes that inherit from |
Georg Brandl | 6b4c847 | 2014-10-30 22:26:26 +0100 | [diff] [blame] | 144 | :class:`unittest.TestCase` are run as tests. The :class:`Mixin` class in the example above |
R David Murray | 78fc25c | 2012-04-09 08:55:42 -0400 | [diff] [blame] | 145 | does not have any data and so can't be run by itself, thus it does not |
Georg Brandl | 6b4c847 | 2014-10-30 22:26:26 +0100 | [diff] [blame] | 146 | inherit from :class:`unittest.TestCase`. |
R David Murray | 78fc25c | 2012-04-09 08:55:42 -0400 | [diff] [blame] | 147 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 148 | |
| 149 | .. seealso:: |
| 150 | |
| 151 | Test Driven Development |
| 152 | A book by Kent Beck on writing tests before code. |
| 153 | |
| 154 | |
| 155 | .. _regrtest: |
| 156 | |
Éric Araujo | 1d55c7e | 2010-12-16 01:40:26 +0000 | [diff] [blame] | 157 | Running tests using the command-line interface |
| 158 | ---------------------------------------------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 159 | |
Éric Araujo | 1d55c7e | 2010-12-16 01:40:26 +0000 | [diff] [blame] | 160 | The :mod:`test` package can be run as a script to drive Python's regression |
| 161 | test suite, thanks to the :option:`-m` option: :program:`python -m test`. Under |
| 162 | the hood, it uses :mod:`test.regrtest`; the call :program:`python -m |
R David Murray | f1cdb60 | 2012-04-09 09:12:57 -0400 | [diff] [blame] | 163 | test.regrtest` used in previous Python versions still works). Running the |
| 164 | script by itself automatically starts running all regression tests in the |
| 165 | :mod:`test` package. It does this by finding all modules in the package whose |
| 166 | name starts with ``test_``, importing them, and executing the function |
| 167 | :func:`test_main` if present or loading the tests via |
| 168 | unittest.TestLoader.loadTestsFromModule if ``test_main`` does not exist. The |
| 169 | names of tests to execute may also be passed to the script. Specifying a single |
| 170 | regression test (:program:`python -m test test_spam`) will minimize output and |
| 171 | only print whether the test passed or failed. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 172 | |
Éric Araujo | 1d55c7e | 2010-12-16 01:40:26 +0000 | [diff] [blame] | 173 | Running :mod:`test` directly allows what resources are available for |
Éric Araujo | 713d303 | 2010-11-18 16:38:46 +0000 | [diff] [blame] | 174 | tests to use to be set. You do this by using the ``-u`` command-line |
R David Murray | 644cabe | 2012-04-11 20:11:53 -0400 | [diff] [blame] | 175 | option. Specifying ``all`` as the value for the ``-u`` option enables all |
| 176 | possible resources: :program:`python -m test -uall`. |
| 177 | If all but one resource is desired (a more common case), a |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 178 | comma-separated list of resources that are not desired may be listed after |
Éric Araujo | 1d55c7e | 2010-12-16 01:40:26 +0000 | [diff] [blame] | 179 | ``all``. The command :program:`python -m test -uall,-audio,-largefile` |
| 180 | will run :mod:`test` with all resources except the ``audio`` and |
Éric Araujo | 713d303 | 2010-11-18 16:38:46 +0000 | [diff] [blame] | 181 | ``largefile`` resources. For a list of all resources and more command-line |
Éric Araujo | 1d55c7e | 2010-12-16 01:40:26 +0000 | [diff] [blame] | 182 | options, run :program:`python -m test -h`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 183 | |
| 184 | Some other ways to execute the regression tests depend on what platform the |
Éric Araujo | 713d303 | 2010-11-18 16:38:46 +0000 | [diff] [blame] | 185 | tests are being executed on. On Unix, you can run :program:`make test` at the |
| 186 | top-level directory where Python was built. On Windows, |
Florent Xicluna | 53b506be | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 187 | executing :program:`rt.bat` from your :file:`PCBuild` directory will run all |
| 188 | regression tests. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 189 | |
| 190 | |
Georg Brandl | eea6cda | 2011-07-30 09:00:48 +0200 | [diff] [blame] | 191 | :mod:`test.support` --- Utilities for the Python test suite |
| 192 | =========================================================== |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 193 | |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 194 | .. module:: test.support |
Georg Brandl | eea6cda | 2011-07-30 09:00:48 +0200 | [diff] [blame] | 195 | :synopsis: Support for Python's regression test suite. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 196 | |
| 197 | |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 198 | The :mod:`test.support` module provides support for Python's regression |
Georg Brandl | eea6cda | 2011-07-30 09:00:48 +0200 | [diff] [blame] | 199 | test suite. |
| 200 | |
| 201 | .. note:: |
Larry Hastings | 3732ed2 | 2014-03-15 21:13:56 -0700 | [diff] [blame] | 202 | |
Georg Brandl | eea6cda | 2011-07-30 09:00:48 +0200 | [diff] [blame] | 203 | :mod:`test.support` is not a public module. It is documented here to help |
| 204 | Python developers write tests. The API of this module is subject to change |
| 205 | without backwards compatibility concerns between releases. |
| 206 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 207 | |
| 208 | This module defines the following exceptions: |
| 209 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 210 | .. exception:: TestFailed |
| 211 | |
| 212 | Exception to be raised when a test fails. This is deprecated in favor of |
| 213 | :mod:`unittest`\ -based tests and :class:`unittest.TestCase`'s assertion |
| 214 | methods. |
| 215 | |
| 216 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 217 | .. exception:: ResourceDenied |
| 218 | |
Florent Xicluna | 53b506be | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 219 | Subclass of :exc:`unittest.SkipTest`. Raised when a resource (such as a |
| 220 | network connection) is not available. Raised by the :func:`requires` |
| 221 | function. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 222 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 223 | |
Georg Brandl | eea6cda | 2011-07-30 09:00:48 +0200 | [diff] [blame] | 224 | The :mod:`test.support` module defines the following constants: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 225 | |
| 226 | .. data:: verbose |
| 227 | |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame] | 228 | ``True`` when verbose output is enabled. Should be checked when more |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 229 | detailed information is desired about a running test. *verbose* is set by |
| 230 | :mod:`test.regrtest`. |
| 231 | |
| 232 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 233 | .. data:: is_jython |
| 234 | |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame] | 235 | ``True`` if the running interpreter is Jython. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 236 | |
| 237 | |
| 238 | .. data:: TESTFN |
| 239 | |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 240 | Set to a name that is safe to use as the name of a temporary file. Any |
| 241 | temporary file that is created should be closed and unlinked (removed). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 242 | |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame] | 243 | |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 244 | The :mod:`test.support` module defines the following functions: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 245 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 246 | .. function:: forget(module_name) |
| 247 | |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 248 | Remove the module named *module_name* from ``sys.modules`` and delete any |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 249 | byte-compiled files of the module. |
| 250 | |
| 251 | |
| 252 | .. function:: is_resource_enabled(resource) |
| 253 | |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame] | 254 | Return ``True`` if *resource* is enabled and available. The list of |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 255 | available resources is only set when :mod:`test.regrtest` is executing the |
| 256 | tests. |
| 257 | |
| 258 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 259 | .. function:: requires(resource, msg=None) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 260 | |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 261 | Raise :exc:`ResourceDenied` if *resource* is not available. *msg* is the |
Florent Xicluna | 53b506be | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 262 | argument to :exc:`ResourceDenied` if it is raised. Always returns |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame] | 263 | ``True`` if called by a function whose ``__name__`` is ``'__main__'``. |
Florent Xicluna | 53b506be | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 264 | Used when tests are executed by :mod:`test.regrtest`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 265 | |
| 266 | |
Nick Coghlan | 0494c2a | 2013-09-08 11:40:34 +1000 | [diff] [blame] | 267 | .. function:: findfile(filename, subdir=None) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 268 | |
Florent Xicluna | 53b506be | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 269 | Return the path to the file named *filename*. If no match is found |
| 270 | *filename* is returned. This does not equal a failure since it could be the |
| 271 | path to the file. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 272 | |
Nick Coghlan | 0494c2a | 2013-09-08 11:40:34 +1000 | [diff] [blame] | 273 | Setting *subdir* indicates a relative path to use to find the file |
| 274 | rather than looking directly in the path directories. |
| 275 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 276 | |
Senthil Kumaran | 279b56d | 2010-10-15 15:21:19 +0000 | [diff] [blame] | 277 | .. function:: run_unittest(\*classes) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 278 | |
| 279 | Execute :class:`unittest.TestCase` subclasses passed to the function. The |
Florent Xicluna | 53b506be | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 280 | function scans the classes for methods starting with the prefix ``test_`` |
| 281 | and executes the tests individually. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 282 | |
| 283 | It is also legal to pass strings as parameters; these should be keys in |
| 284 | ``sys.modules``. Each associated module will be scanned by |
| 285 | ``unittest.TestLoader.loadTestsFromModule()``. This is usually seen in the |
| 286 | following :func:`test_main` function:: |
| 287 | |
| 288 | def test_main(): |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 289 | support.run_unittest(__name__) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 290 | |
| 291 | This will run all tests defined in the named module. |
| 292 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 293 | |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame] | 294 | .. function:: run_doctest(module, verbosity=None) |
| 295 | |
| 296 | Run :func:`doctest.testmod` on the given *module*. Return |
| 297 | ``(failure_count, test_count)``. |
| 298 | |
| 299 | If *verbosity* is ``None``, :func:`doctest.testmod` is run with verbosity |
| 300 | set to :data:`verbose`. Otherwise, it is run with verbosity set to |
| 301 | ``None``. |
| 302 | |
Senthil Kumaran | 279b56d | 2010-10-15 15:21:19 +0000 | [diff] [blame] | 303 | .. function:: check_warnings(\*filters, quiet=True) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 304 | |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 305 | A convenience wrapper for :func:`warnings.catch_warnings()` that makes it |
| 306 | easier to test that a warning was correctly raised. It is approximately |
| 307 | equivalent to calling ``warnings.catch_warnings(record=True)`` with |
| 308 | :meth:`warnings.simplefilter` set to ``always`` and with the option to |
| 309 | automatically validate the results that are recorded. |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 310 | |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 311 | ``check_warnings`` accepts 2-tuples of the form ``("message regexp", |
| 312 | WarningCategory)`` as positional arguments. If one or more *filters* are |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame] | 313 | provided, or if the optional keyword argument *quiet* is ``False``, |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 314 | it checks to make sure the warnings are as expected: each specified filter |
| 315 | must match at least one of the warnings raised by the enclosed code or the |
| 316 | test fails, and if any warnings are raised that do not match any of the |
| 317 | specified filters the test fails. To disable the first of these checks, |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame] | 318 | set *quiet* to ``True``. |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 319 | |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 320 | If no arguments are specified, it defaults to:: |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 321 | |
Florent Xicluna | 53b506be | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 322 | check_warnings(("", Warning), quiet=True) |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 323 | |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 324 | In this case all warnings are caught and no errors are raised. |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 325 | |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 326 | On entry to the context manager, a :class:`WarningRecorder` instance is |
| 327 | returned. The underlying warnings list from |
| 328 | :func:`~warnings.catch_warnings` is available via the recorder object's |
| 329 | :attr:`warnings` attribute. As a convenience, the attributes of the object |
| 330 | representing the most recent warning can also be accessed directly through |
| 331 | the recorder object (see example below). If no warning has been raised, |
| 332 | then any of the attributes that would otherwise be expected on an object |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame] | 333 | representing a warning will return ``None``. |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 334 | |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 335 | The recorder object also has a :meth:`reset` method, which clears the |
| 336 | warnings list. |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 337 | |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 338 | The context manager is designed to be used like this:: |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 339 | |
| 340 | with check_warnings(("assertion is always true", SyntaxWarning), |
| 341 | ("", UserWarning)): |
| 342 | exec('assert(False, "Hey!")') |
| 343 | warnings.warn(UserWarning("Hide me!")) |
| 344 | |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 345 | In this case if either warning was not raised, or some other warning was |
| 346 | raised, :func:`check_warnings` would raise an error. |
| 347 | |
| 348 | When a test needs to look more deeply into the warnings, rather than |
| 349 | just checking whether or not they occurred, code like this can be used:: |
| 350 | |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 351 | with check_warnings(quiet=True) as w: |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 352 | warnings.warn("foo") |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 353 | assert str(w.args[0]) == "foo" |
Nick Coghlan | b130493 | 2008-07-13 12:25:08 +0000 | [diff] [blame] | 354 | warnings.warn("bar") |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 355 | assert str(w.args[0]) == "bar" |
| 356 | assert str(w.warnings[0].args[0]) == "foo" |
| 357 | assert str(w.warnings[1].args[0]) == "bar" |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 358 | w.reset() |
| 359 | assert len(w.warnings) == 0 |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 360 | |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 361 | |
| 362 | Here all warnings will be caught, and the test code tests the captured |
| 363 | warnings directly. |
| 364 | |
Ezio Melotti | f8754a6 | 2010-03-21 07:16:43 +0000 | [diff] [blame] | 365 | .. versionchanged:: 3.2 |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 366 | New optional arguments *filters* and *quiet*. |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 367 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 368 | |
R David Murray | 5a33f81 | 2013-07-11 12:28:40 -0400 | [diff] [blame] | 369 | .. function:: captured_stdin() |
| 370 | captured_stdout() |
| 371 | captured_stderr() |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 372 | |
R David Murray | 5a33f81 | 2013-07-11 12:28:40 -0400 | [diff] [blame] | 373 | A context managers that temporarily replaces the named stream with |
| 374 | :class:`io.StringIO` object. |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 375 | |
R David Murray | 5a33f81 | 2013-07-11 12:28:40 -0400 | [diff] [blame] | 376 | Example use with output streams:: |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 377 | |
R David Murray | 5a33f81 | 2013-07-11 12:28:40 -0400 | [diff] [blame] | 378 | with captured_stdout() as stdout, captured_stderr() as stderr: |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 379 | print("hello") |
R David Murray | 5a33f81 | 2013-07-11 12:28:40 -0400 | [diff] [blame] | 380 | print("error", file=sys.stderr) |
| 381 | assert stdout.getvalue() == "hello\n" |
| 382 | assert stderr.getvalue() == "error\n" |
| 383 | |
| 384 | Example use with input stream:: |
| 385 | |
| 386 | with captured_stdin() as stdin: |
| 387 | stdin.write('hello\n') |
| 388 | stdin.seek(0) |
| 389 | # call test code that consumes from sys.stdin |
| 390 | captured = input() |
| 391 | self.assertEqual(captured, "hello") |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 392 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 393 | |
Nick Coghlan | 5517596 | 2013-07-28 22:11:50 +1000 | [diff] [blame] | 394 | .. function:: temp_dir(path=None, quiet=False) |
| 395 | |
| 396 | A context manager that creates a temporary directory at *path* and |
| 397 | yields the directory. |
| 398 | |
| 399 | If *path* is None, the temporary directory is created using |
| 400 | :func:`tempfile.mkdtemp`. If *quiet* is ``False``, the context manager |
| 401 | raises an exception on error. Otherwise, if *path* is specified and |
| 402 | cannot be created, only a warning is issued. |
| 403 | |
| 404 | |
| 405 | .. function:: change_cwd(path, quiet=False) |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame] | 406 | |
| 407 | A context manager that temporarily changes the current working |
Nick Coghlan | 5517596 | 2013-07-28 22:11:50 +1000 | [diff] [blame] | 408 | directory to *path* and yields the directory. |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame] | 409 | |
Nick Coghlan | 5517596 | 2013-07-28 22:11:50 +1000 | [diff] [blame] | 410 | If *quiet* is ``False``, the context manager raises an exception |
| 411 | on error. Otherwise, it issues only a warning and keeps the current |
| 412 | working directory the same. |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame] | 413 | |
Nick Coghlan | 5517596 | 2013-07-28 22:11:50 +1000 | [diff] [blame] | 414 | |
| 415 | .. function:: temp_cwd(name='tempcwd', quiet=False) |
| 416 | |
| 417 | A context manager that temporarily creates a new directory and |
| 418 | changes the current working directory (CWD). |
| 419 | |
| 420 | The context manager creates a temporary directory in the current |
| 421 | directory with name *name* before temporarily changing the current |
| 422 | working directory. If *name* is None, the temporary directory is |
| 423 | created using :func:`tempfile.mkdtemp`. |
| 424 | |
| 425 | If *quiet* is ``False`` and it is not possible to create or change |
| 426 | the CWD, an error is raised. Otherwise, only a warning is raised |
| 427 | and the original CWD is used. |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame] | 428 | |
| 429 | |
| 430 | .. function:: temp_umask(umask) |
| 431 | |
| 432 | A context manager that temporarily sets the process umask. |
| 433 | |
| 434 | |
| 435 | .. function:: can_symlink() |
| 436 | |
| 437 | Return ``True`` if the OS supports symbolic links, ``False`` |
| 438 | otherwise. |
| 439 | |
| 440 | |
Nick Coghlan | 2496f33 | 2011-09-19 20:26:31 +1000 | [diff] [blame] | 441 | .. decorator:: skip_unless_symlink() |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame] | 442 | |
| 443 | A decorator for running tests that require support for symbolic links. |
| 444 | |
| 445 | |
Nick Coghlan | 2496f33 | 2011-09-19 20:26:31 +1000 | [diff] [blame] | 446 | .. decorator:: anticipate_failure(condition) |
| 447 | |
| 448 | A decorator to conditionally mark tests with |
| 449 | :func:`unittest.expectedFailure`. Any use of this decorator should |
| 450 | have an associated comment identifying the relevant tracker issue. |
| 451 | |
| 452 | |
| 453 | .. decorator:: run_with_locale(catstr, *locales) |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame] | 454 | |
| 455 | A decorator for running a function in a different locale, correctly |
| 456 | resetting it after it has finished. *catstr* is the locale category as |
| 457 | a string (for example ``"LC_ALL"``). The *locales* passed will be tried |
| 458 | sequentially, and the first valid locale will be used. |
| 459 | |
| 460 | |
| 461 | .. function:: make_bad_fd() |
| 462 | |
| 463 | Create an invalid file descriptor by opening and closing a temporary file, |
Zachary Ware | f012ba4 | 2014-07-23 12:00:29 -0500 | [diff] [blame] | 464 | and returning its descriptor. |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame] | 465 | |
| 466 | |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 467 | .. function:: import_module(name, deprecated=False) |
| 468 | |
| 469 | This function imports and returns the named module. Unlike a normal |
| 470 | import, this function raises :exc:`unittest.SkipTest` if the module |
| 471 | cannot be imported. |
| 472 | |
| 473 | Module and package deprecation messages are suppressed during this import |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame] | 474 | if *deprecated* is ``True``. |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 475 | |
| 476 | .. versionadded:: 3.1 |
| 477 | |
| 478 | |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 479 | .. function:: import_fresh_module(name, fresh=(), blocked=(), deprecated=False) |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 480 | |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 481 | This function imports and returns a fresh copy of the named Python module |
| 482 | by removing the named module from ``sys.modules`` before doing the import. |
| 483 | Note that unlike :func:`reload`, the original module is not affected by |
| 484 | this operation. |
| 485 | |
| 486 | *fresh* is an iterable of additional module names that are also removed |
| 487 | from the ``sys.modules`` cache before doing the import. |
| 488 | |
Eli Bendersky | ba5517d | 2013-08-11 15:38:08 -0700 | [diff] [blame] | 489 | *blocked* is an iterable of module names that are replaced with ``None`` |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 490 | in the module cache during the import to ensure that attempts to import |
| 491 | them raise :exc:`ImportError`. |
| 492 | |
| 493 | The named module and any modules named in the *fresh* and *blocked* |
| 494 | parameters are saved before starting the import and then reinserted into |
| 495 | ``sys.modules`` when the fresh import is complete. |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 496 | |
| 497 | Module and package deprecation messages are suppressed during this import |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame] | 498 | if *deprecated* is ``True``. |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 499 | |
Eli Bendersky | ba5517d | 2013-08-11 15:38:08 -0700 | [diff] [blame] | 500 | This function will raise :exc:`ImportError` if the named module cannot be |
| 501 | imported. |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 502 | |
| 503 | Example use:: |
| 504 | |
Eli Bendersky | ba5517d | 2013-08-11 15:38:08 -0700 | [diff] [blame] | 505 | # Get copies of the warnings module for testing without affecting the |
| 506 | # version being used by the rest of the test suite. One copy uses the |
| 507 | # C implementation, the other is forced to use the pure Python fallback |
| 508 | # implementation |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 509 | py_warnings = import_fresh_module('warnings', blocked=['_warnings']) |
| 510 | c_warnings = import_fresh_module('warnings', fresh=['_warnings']) |
| 511 | |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 512 | .. versionadded:: 3.1 |
| 513 | |
| 514 | |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame] | 515 | .. function:: bind_port(sock, host=HOST) |
| 516 | |
| 517 | Bind the socket to a free port and return the port number. Relies on |
| 518 | ephemeral ports in order to ensure we are using an unbound port. This is |
| 519 | important as many tests may be running simultaneously, especially in a |
| 520 | buildbot environment. This method raises an exception if the |
| 521 | ``sock.family`` is :const:`~socket.AF_INET` and ``sock.type`` is |
| 522 | :const:`~socket.SOCK_STREAM`, and the socket has |
| 523 | :const:`~socket.SO_REUSEADDR` or :const:`~socket.SO_REUSEPORT` set on it. |
| 524 | Tests should never set these socket options for TCP/IP sockets. |
| 525 | The only case for setting these options is testing multicasting via |
| 526 | multiple UDP sockets. |
| 527 | |
| 528 | Additionally, if the :const:`~socket.SO_EXCLUSIVEADDRUSE` socket option is |
| 529 | available (i.e. on Windows), it will be set on the socket. This will |
| 530 | prevent anyone else from binding to our host/port for the duration of the |
| 531 | test. |
| 532 | |
| 533 | |
| 534 | .. function:: find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM) |
| 535 | |
| 536 | Returns an unused port that should be suitable for binding. This is |
| 537 | achieved by creating a temporary socket with the same family and type as |
| 538 | the ``sock`` parameter (default is :const:`~socket.AF_INET`, |
| 539 | :const:`~socket.SOCK_STREAM`), |
| 540 | and binding it to the specified host address (defaults to ``0.0.0.0``) |
| 541 | with the port set to 0, eliciting an unused ephemeral port from the OS. |
| 542 | The temporary socket is then closed and deleted, and the ephemeral port is |
| 543 | returned. |
| 544 | |
| 545 | Either this method or :func:`bind_port` should be used for any tests |
| 546 | where a server socket needs to be bound to a particular port for the |
| 547 | duration of the test. |
| 548 | Which one to use depends on whether the calling code is creating a python |
| 549 | socket, or if an unused port needs to be provided in a constructor |
| 550 | or passed to an external program (i.e. the ``-accept`` argument to |
| 551 | openssl's s_server mode). Always prefer :func:`bind_port` over |
| 552 | :func:`find_unused_port` where possible. Using a hard coded port is |
| 553 | discouraged since it can makes multiple instances of the test impossible to |
| 554 | run simultaneously, which is a problem for buildbots. |
| 555 | |
| 556 | |
Zachary Ware | f012ba4 | 2014-07-23 12:00:29 -0500 | [diff] [blame] | 557 | .. function:: load_package_tests(pkg_dir, loader, standard_tests, pattern) |
| 558 | |
| 559 | Generic implementation of the :mod:`unittest` ``load_tests`` protocol for |
| 560 | use in test packages. *pkg_dir* is the root directory of the package; |
| 561 | *loader*, *standard_tests*, and *pattern* are the arguments expected by |
| 562 | ``load_tests``. In simple cases, the test package's ``__init__.py`` |
| 563 | can be the following:: |
| 564 | |
| 565 | import os |
| 566 | from test.support import load_package_tests |
| 567 | |
| 568 | def load_tests(*args): |
| 569 | return load_package_tests(os.path.dirname(__file__), *args) |
| 570 | |
| 571 | |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 572 | The :mod:`test.support` module defines the following classes: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 573 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 574 | .. class:: TransientResource(exc, **kwargs) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 575 | |
| 576 | Instances are a context manager that raises :exc:`ResourceDenied` if the |
| 577 | specified exception type is raised. Any keyword arguments are treated as |
| 578 | attribute/value pairs to be compared against any exception raised within the |
| 579 | :keyword:`with` statement. Only if all pairs match properly against |
| 580 | attributes on the exception is :exc:`ResourceDenied` raised. |
| 581 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 582 | |
| 583 | .. class:: EnvironmentVarGuard() |
| 584 | |
Florent Xicluna | 53b506be | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 585 | Class used to temporarily set or unset environment variables. Instances can |
| 586 | be used as a context manager and have a complete dictionary interface for |
| 587 | querying/modifying the underlying ``os.environ``. After exit from the |
| 588 | context manager all changes to environment variables done through this |
| 589 | instance will be rolled back. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 590 | |
Georg Brandl | 705d9d5 | 2009-05-05 09:29:50 +0000 | [diff] [blame] | 591 | .. versionchanged:: 3.1 |
Walter Dörwald | 155374d | 2009-05-01 19:58:58 +0000 | [diff] [blame] | 592 | Added dictionary interface. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 593 | |
| 594 | .. method:: EnvironmentVarGuard.set(envvar, value) |
| 595 | |
Florent Xicluna | 53b506be | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 596 | Temporarily set the environment variable ``envvar`` to the value of |
| 597 | ``value``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 598 | |
| 599 | |
| 600 | .. method:: EnvironmentVarGuard.unset(envvar) |
| 601 | |
| 602 | Temporarily unset the environment variable ``envvar``. |
Nick Coghlan | b130493 | 2008-07-13 12:25:08 +0000 | [diff] [blame] | 603 | |
Walter Dörwald | 155374d | 2009-05-01 19:58:58 +0000 | [diff] [blame] | 604 | |
Antoine Pitrou | 77e904e | 2013-10-08 23:04:32 +0200 | [diff] [blame] | 605 | .. class:: SuppressCrashReport() |
| 606 | |
| 607 | A context manager used to try to prevent crash dialog popups on tests that |
| 608 | are expected to crash a subprocess. |
| 609 | |
| 610 | On Windows, it disables Windows Error Reporting dialogs using |
| 611 | `SetErrorMode <http://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx>`_. |
| 612 | |
| 613 | On UNIX, :func:`resource.setrlimit` is used to set |
| 614 | :attr:`resource.RLIMIT_CORE`'s soft limit to 0 to prevent coredump file |
| 615 | creation. |
| 616 | |
| 617 | On both platforms, the old value is restored by :meth:`__exit__`. |
| 618 | |
| 619 | |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 620 | .. class:: WarningsRecorder() |
| 621 | |
| 622 | Class used to record warnings for unit tests. See documentation of |
| 623 | :func:`check_warnings` above for more details. |