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 | |
| 83 | def test_main(): |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 84 | support.run_unittest(MyTestCase1, |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 85 | MyTestCase2, |
| 86 | ... list other tests ... |
| 87 | ) |
| 88 | |
| 89 | if __name__ == '__main__': |
| 90 | test_main() |
| 91 | |
| 92 | This boilerplate code allows the testing suite to be run by :mod:`test.regrtest` |
| 93 | as well as on its own as a script. |
| 94 | |
| 95 | The goal for regression testing is to try to break code. This leads to a few |
| 96 | guidelines to be followed: |
| 97 | |
| 98 | * The testing suite should exercise all classes, functions, and constants. This |
Florent Xicluna | 53b506b | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 99 | includes not just the external API that is to be presented to the outside |
| 100 | world but also "private" code. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 101 | |
| 102 | * Whitebox testing (examining the code being tested when the tests are being |
| 103 | written) is preferred. Blackbox testing (testing only the published user |
Florent Xicluna | 53b506b | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 104 | interface) is not complete enough to make sure all boundary and edge cases |
| 105 | are tested. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 106 | |
| 107 | * Make sure all possible values are tested including invalid ones. This makes |
Florent Xicluna | 53b506b | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 108 | sure that not only all valid values are acceptable but also that improper |
| 109 | values are handled correctly. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 110 | |
| 111 | * Exhaust as many code paths as possible. Test where branching occurs and thus |
| 112 | tailor input to make sure as many different paths through the code are taken. |
| 113 | |
| 114 | * Add an explicit test for any bugs discovered for the tested code. This will |
| 115 | make sure that the error does not crop up again if the code is changed in the |
| 116 | future. |
| 117 | |
| 118 | * Make sure to clean up after your tests (such as close and remove all temporary |
| 119 | files). |
| 120 | |
| 121 | * If a test is dependent on a specific condition of the operating system then |
| 122 | verify the condition already exists before attempting the test. |
| 123 | |
| 124 | * Import as few modules as possible and do it as soon as possible. This |
| 125 | minimizes external dependencies of tests and also minimizes possible anomalous |
| 126 | behavior from side-effects of importing a module. |
| 127 | |
| 128 | * Try to maximize code reuse. On occasion, tests will vary by something as small |
Florent Xicluna | 53b506b | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 129 | as what type of input is used. Minimize code duplication by subclassing a |
| 130 | basic test class with a class that specifies the input:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 131 | |
| 132 | class TestFuncAcceptsSequences(unittest.TestCase): |
| 133 | |
| 134 | func = mySuperWhammyFunction |
| 135 | |
| 136 | def test_func(self): |
| 137 | self.func(self.arg) |
| 138 | |
| 139 | class AcceptLists(TestFuncAcceptsSequences): |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 140 | arg = [1, 2, 3] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 141 | |
| 142 | class AcceptStrings(TestFuncAcceptsSequences): |
| 143 | arg = 'abc' |
| 144 | |
| 145 | class AcceptTuples(TestFuncAcceptsSequences): |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 146 | arg = (1, 2, 3) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 147 | |
| 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 |
| 163 | test.regrtest` used in previous Python versions still works). |
| 164 | Running the script by itself automatically starts running all regression |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 165 | tests in the :mod:`test` package. It does this by finding all modules in the |
| 166 | package whose name starts with ``test_``, importing them, and executing the |
Florent Xicluna | 53b506b | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 167 | function :func:`test_main` if present. The names of tests to execute may also |
| 168 | be passed to the script. Specifying a single regression test (:program:`python |
Éric Araujo | 1d55c7e | 2010-12-16 01:40:26 +0000 | [diff] [blame] | 169 | -m test test_spam`) will minimize output and only print |
Florent Xicluna | 53b506b | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 170 | whether the test passed or failed and thus minimize output. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 171 | |
Éric Araujo | 1d55c7e | 2010-12-16 01:40:26 +0000 | [diff] [blame] | 172 | Running :mod:`test` directly allows what resources are available for |
Éric Araujo | 713d303 | 2010-11-18 16:38:46 +0000 | [diff] [blame] | 173 | tests to use to be set. You do this by using the ``-u`` command-line |
Éric Araujo | 1d55c7e | 2010-12-16 01:40:26 +0000 | [diff] [blame] | 174 | option. Run :program:`python -m test -uall` to turn on all |
Éric Araujo | 713d303 | 2010-11-18 16:38:46 +0000 | [diff] [blame] | 175 | resources; specifying ``all`` as an option for ``-u`` enables all |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 176 | possible resources. If all but one resource is desired (a more common case), a |
| 177 | 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] | 178 | ``all``. The command :program:`python -m test -uall,-audio,-largefile` |
| 179 | will run :mod:`test` with all resources except the ``audio`` and |
Éric Araujo | 713d303 | 2010-11-18 16:38:46 +0000 | [diff] [blame] | 180 | ``largefile`` resources. For a list of all resources and more command-line |
Éric Araujo | 1d55c7e | 2010-12-16 01:40:26 +0000 | [diff] [blame] | 181 | options, run :program:`python -m test -h`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 182 | |
| 183 | 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] | 184 | tests are being executed on. On Unix, you can run :program:`make test` at the |
| 185 | top-level directory where Python was built. On Windows, |
Florent Xicluna | 53b506b | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 186 | executing :program:`rt.bat` from your :file:`PCBuild` directory will run all |
| 187 | regression tests. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 188 | |
| 189 | |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 190 | :mod:`test.support` --- Utility functions for tests |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 191 | =================================================== |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 192 | |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 193 | .. module:: test.support |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 194 | :synopsis: Support for Python regression tests. |
| 195 | |
| 196 | |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 197 | The :mod:`test.support` module provides support for Python's regression |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 198 | tests. |
| 199 | |
| 200 | This module defines the following exceptions: |
| 201 | |
| 202 | |
| 203 | .. exception:: TestFailed |
| 204 | |
| 205 | Exception to be raised when a test fails. This is deprecated in favor of |
| 206 | :mod:`unittest`\ -based tests and :class:`unittest.TestCase`'s assertion |
| 207 | methods. |
| 208 | |
| 209 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 210 | .. exception:: ResourceDenied |
| 211 | |
Florent Xicluna | 53b506b | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 212 | Subclass of :exc:`unittest.SkipTest`. Raised when a resource (such as a |
| 213 | network connection) is not available. Raised by the :func:`requires` |
| 214 | function. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 215 | |
Nick Coghlan | b130493 | 2008-07-13 12:25:08 +0000 | [diff] [blame] | 216 | The :mod:`test.support` module defines the following constants: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 217 | |
| 218 | |
| 219 | .. data:: verbose |
| 220 | |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame^] | 221 | ``True`` when verbose output is enabled. Should be checked when more |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 222 | detailed information is desired about a running test. *verbose* is set by |
| 223 | :mod:`test.regrtest`. |
| 224 | |
| 225 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 226 | .. data:: is_jython |
| 227 | |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame^] | 228 | ``True`` if the running interpreter is Jython. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 229 | |
| 230 | |
| 231 | .. data:: TESTFN |
| 232 | |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 233 | Set to a name that is safe to use as the name of a temporary file. Any |
| 234 | temporary file that is created should be closed and unlinked (removed). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 235 | |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame^] | 236 | |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 237 | The :mod:`test.support` module defines the following functions: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 238 | |
| 239 | |
| 240 | .. function:: forget(module_name) |
| 241 | |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 242 | Remove the module named *module_name* from ``sys.modules`` and delete any |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 243 | byte-compiled files of the module. |
| 244 | |
| 245 | |
| 246 | .. function:: is_resource_enabled(resource) |
| 247 | |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame^] | 248 | Return ``True`` if *resource* is enabled and available. The list of |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 249 | available resources is only set when :mod:`test.regrtest` is executing the |
| 250 | tests. |
| 251 | |
| 252 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 253 | .. function:: requires(resource, msg=None) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 254 | |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 255 | Raise :exc:`ResourceDenied` if *resource* is not available. *msg* is the |
Florent Xicluna | 53b506b | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 256 | argument to :exc:`ResourceDenied` if it is raised. Always returns |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame^] | 257 | ``True`` if called by a function whose ``__name__`` is ``'__main__'``. |
Florent Xicluna | 53b506b | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 258 | Used when tests are executed by :mod:`test.regrtest`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 259 | |
| 260 | |
| 261 | .. function:: findfile(filename) |
| 262 | |
Florent Xicluna | 53b506b | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 263 | Return the path to the file named *filename*. If no match is found |
| 264 | *filename* is returned. This does not equal a failure since it could be the |
| 265 | path to the file. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 266 | |
| 267 | |
Senthil Kumaran | 279b56d | 2010-10-15 15:21:19 +0000 | [diff] [blame] | 268 | .. function:: run_unittest(\*classes) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 269 | |
| 270 | Execute :class:`unittest.TestCase` subclasses passed to the function. The |
Florent Xicluna | 53b506b | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 271 | function scans the classes for methods starting with the prefix ``test_`` |
| 272 | and executes the tests individually. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 273 | |
| 274 | It is also legal to pass strings as parameters; these should be keys in |
| 275 | ``sys.modules``. Each associated module will be scanned by |
| 276 | ``unittest.TestLoader.loadTestsFromModule()``. This is usually seen in the |
| 277 | following :func:`test_main` function:: |
| 278 | |
| 279 | def test_main(): |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 280 | support.run_unittest(__name__) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 281 | |
| 282 | This will run all tests defined in the named module. |
| 283 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 284 | |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame^] | 285 | .. function:: run_doctest(module, verbosity=None) |
| 286 | |
| 287 | Run :func:`doctest.testmod` on the given *module*. Return |
| 288 | ``(failure_count, test_count)``. |
| 289 | |
| 290 | If *verbosity* is ``None``, :func:`doctest.testmod` is run with verbosity |
| 291 | set to :data:`verbose`. Otherwise, it is run with verbosity set to |
| 292 | ``None``. |
| 293 | |
Senthil Kumaran | 279b56d | 2010-10-15 15:21:19 +0000 | [diff] [blame] | 294 | .. function:: check_warnings(\*filters, quiet=True) |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 295 | |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 296 | A convenience wrapper for :func:`warnings.catch_warnings()` that makes it |
| 297 | easier to test that a warning was correctly raised. It is approximately |
| 298 | equivalent to calling ``warnings.catch_warnings(record=True)`` with |
| 299 | :meth:`warnings.simplefilter` set to ``always`` and with the option to |
| 300 | automatically validate the results that are recorded. |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 301 | |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 302 | ``check_warnings`` accepts 2-tuples of the form ``("message regexp", |
| 303 | WarningCategory)`` as positional arguments. If one or more *filters* are |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame^] | 304 | provided, or if the optional keyword argument *quiet* is ``False``, |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 305 | it checks to make sure the warnings are as expected: each specified filter |
| 306 | must match at least one of the warnings raised by the enclosed code or the |
| 307 | test fails, and if any warnings are raised that do not match any of the |
| 308 | specified filters the test fails. To disable the first of these checks, |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame^] | 309 | set *quiet* to ``True``. |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 310 | |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 311 | If no arguments are specified, it defaults to:: |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 312 | |
Florent Xicluna | 53b506b | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 313 | check_warnings(("", Warning), quiet=True) |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 314 | |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 315 | In this case all warnings are caught and no errors are raised. |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 316 | |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 317 | On entry to the context manager, a :class:`WarningRecorder` instance is |
| 318 | returned. The underlying warnings list from |
| 319 | :func:`~warnings.catch_warnings` is available via the recorder object's |
| 320 | :attr:`warnings` attribute. As a convenience, the attributes of the object |
| 321 | representing the most recent warning can also be accessed directly through |
| 322 | the recorder object (see example below). If no warning has been raised, |
| 323 | 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^] | 324 | representing a warning will return ``None``. |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 325 | |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 326 | The recorder object also has a :meth:`reset` method, which clears the |
| 327 | warnings list. |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 328 | |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 329 | The context manager is designed to be used like this:: |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 330 | |
| 331 | with check_warnings(("assertion is always true", SyntaxWarning), |
| 332 | ("", UserWarning)): |
| 333 | exec('assert(False, "Hey!")') |
| 334 | warnings.warn(UserWarning("Hide me!")) |
| 335 | |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 336 | In this case if either warning was not raised, or some other warning was |
| 337 | raised, :func:`check_warnings` would raise an error. |
| 338 | |
| 339 | When a test needs to look more deeply into the warnings, rather than |
| 340 | just checking whether or not they occurred, code like this can be used:: |
| 341 | |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 342 | with check_warnings(quiet=True) as w: |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 343 | warnings.warn("foo") |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 344 | assert str(w.args[0]) == "foo" |
Nick Coghlan | b130493 | 2008-07-13 12:25:08 +0000 | [diff] [blame] | 345 | warnings.warn("bar") |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 346 | assert str(w.args[0]) == "bar" |
| 347 | assert str(w.warnings[0].args[0]) == "foo" |
| 348 | assert str(w.warnings[1].args[0]) == "bar" |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 349 | w.reset() |
| 350 | assert len(w.warnings) == 0 |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 351 | |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 352 | |
| 353 | Here all warnings will be caught, and the test code tests the captured |
| 354 | warnings directly. |
| 355 | |
Ezio Melotti | f8754a6 | 2010-03-21 07:16:43 +0000 | [diff] [blame] | 356 | .. versionchanged:: 3.2 |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 357 | New optional arguments *filters* and *quiet*. |
Florent Xicluna | b14930c | 2010-03-13 15:26:44 +0000 | [diff] [blame] | 358 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 359 | |
| 360 | .. function:: captured_stdout() |
| 361 | |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame^] | 362 | A context manager that runs the :keyword:`with` statement body using |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 363 | a :class:`StringIO.StringIO` object as sys.stdout. That object can be |
Guido van Rossum | 7736b5b | 2008-01-15 21:44:53 +0000 | [diff] [blame] | 364 | retrieved using the ``as`` clause of the :keyword:`with` statement. |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 365 | |
| 366 | Example use:: |
| 367 | |
| 368 | with captured_stdout() as s: |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 369 | print("hello") |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 370 | assert s.getvalue() == "hello" |
| 371 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 372 | |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame^] | 373 | .. function:: temp_cwd(name='tempcwd', quiet=False, path=None) |
| 374 | |
| 375 | A context manager that temporarily changes the current working |
| 376 | directory (CWD). |
| 377 | |
| 378 | An existing path may be provided as *path*, in which case this function |
| 379 | makes no changes to the file system. |
| 380 | |
| 381 | Otherwise, the new CWD is created in the current directory and it's named |
| 382 | *name*. If *quiet* is ``False`` and it's not possible to create or |
| 383 | change the CWD, an error is raised. If it's ``True``, only a warning |
| 384 | is raised and the original CWD is used. |
| 385 | |
| 386 | |
| 387 | .. function:: temp_umask(umask) |
| 388 | |
| 389 | A context manager that temporarily sets the process umask. |
| 390 | |
| 391 | |
| 392 | .. function:: can_symlink() |
| 393 | |
| 394 | Return ``True`` if the OS supports symbolic links, ``False`` |
| 395 | otherwise. |
| 396 | |
| 397 | |
| 398 | .. function:: skip_unless_symlink() |
| 399 | |
| 400 | A decorator for running tests that require support for symbolic links. |
| 401 | |
| 402 | |
| 403 | .. function:: run_with_locale(catstr, *locales) |
| 404 | |
| 405 | A decorator for running a function in a different locale, correctly |
| 406 | resetting it after it has finished. *catstr* is the locale category as |
| 407 | a string (for example ``"LC_ALL"``). The *locales* passed will be tried |
| 408 | sequentially, and the first valid locale will be used. |
| 409 | |
| 410 | |
| 411 | .. function:: make_bad_fd() |
| 412 | |
| 413 | Create an invalid file descriptor by opening and closing a temporary file, |
| 414 | and returning its descripor. |
| 415 | |
| 416 | |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 417 | .. function:: import_module(name, deprecated=False) |
| 418 | |
| 419 | This function imports and returns the named module. Unlike a normal |
| 420 | import, this function raises :exc:`unittest.SkipTest` if the module |
| 421 | cannot be imported. |
| 422 | |
| 423 | Module and package deprecation messages are suppressed during this import |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame^] | 424 | if *deprecated* is ``True``. |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 425 | |
| 426 | .. versionadded:: 3.1 |
| 427 | |
| 428 | |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 429 | .. function:: import_fresh_module(name, fresh=(), blocked=(), deprecated=False) |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 430 | |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 431 | This function imports and returns a fresh copy of the named Python module |
| 432 | by removing the named module from ``sys.modules`` before doing the import. |
| 433 | Note that unlike :func:`reload`, the original module is not affected by |
| 434 | this operation. |
| 435 | |
| 436 | *fresh* is an iterable of additional module names that are also removed |
| 437 | from the ``sys.modules`` cache before doing the import. |
| 438 | |
| 439 | *blocked* is an iterable of module names that are replaced with :const:`0` |
| 440 | in the module cache during the import to ensure that attempts to import |
| 441 | them raise :exc:`ImportError`. |
| 442 | |
| 443 | The named module and any modules named in the *fresh* and *blocked* |
| 444 | parameters are saved before starting the import and then reinserted into |
| 445 | ``sys.modules`` when the fresh import is complete. |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 446 | |
| 447 | Module and package deprecation messages are suppressed during this import |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame^] | 448 | if *deprecated* is ``True``. |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 449 | |
Nick Coghlan | 4738470 | 2009-04-22 16:13:36 +0000 | [diff] [blame] | 450 | This function will raise :exc:`unittest.SkipTest` is the named module |
| 451 | cannot be imported. |
| 452 | |
| 453 | Example use:: |
| 454 | |
| 455 | # Get copies of the warnings module for testing without |
| 456 | # affecting the version being used by the rest of the test suite |
| 457 | # One copy uses the C implementation, the other is forced to use |
| 458 | # the pure Python fallback implementation |
| 459 | py_warnings = import_fresh_module('warnings', blocked=['_warnings']) |
| 460 | c_warnings = import_fresh_module('warnings', fresh=['_warnings']) |
| 461 | |
Nick Coghlan | fce769e | 2009-04-11 14:30:59 +0000 | [diff] [blame] | 462 | .. versionadded:: 3.1 |
| 463 | |
| 464 | |
Eli Bendersky | e168965 | 2011-05-06 09:29:27 +0300 | [diff] [blame^] | 465 | .. function:: bind_port(sock, host=HOST) |
| 466 | |
| 467 | Bind the socket to a free port and return the port number. Relies on |
| 468 | ephemeral ports in order to ensure we are using an unbound port. This is |
| 469 | important as many tests may be running simultaneously, especially in a |
| 470 | buildbot environment. This method raises an exception if the |
| 471 | ``sock.family`` is :const:`~socket.AF_INET` and ``sock.type`` is |
| 472 | :const:`~socket.SOCK_STREAM`, and the socket has |
| 473 | :const:`~socket.SO_REUSEADDR` or :const:`~socket.SO_REUSEPORT` set on it. |
| 474 | Tests should never set these socket options for TCP/IP sockets. |
| 475 | The only case for setting these options is testing multicasting via |
| 476 | multiple UDP sockets. |
| 477 | |
| 478 | Additionally, if the :const:`~socket.SO_EXCLUSIVEADDRUSE` socket option is |
| 479 | available (i.e. on Windows), it will be set on the socket. This will |
| 480 | prevent anyone else from binding to our host/port for the duration of the |
| 481 | test. |
| 482 | |
| 483 | |
| 484 | .. function:: find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM) |
| 485 | |
| 486 | Returns an unused port that should be suitable for binding. This is |
| 487 | achieved by creating a temporary socket with the same family and type as |
| 488 | the ``sock`` parameter (default is :const:`~socket.AF_INET`, |
| 489 | :const:`~socket.SOCK_STREAM`), |
| 490 | and binding it to the specified host address (defaults to ``0.0.0.0``) |
| 491 | with the port set to 0, eliciting an unused ephemeral port from the OS. |
| 492 | The temporary socket is then closed and deleted, and the ephemeral port is |
| 493 | returned. |
| 494 | |
| 495 | Either this method or :func:`bind_port` should be used for any tests |
| 496 | where a server socket needs to be bound to a particular port for the |
| 497 | duration of the test. |
| 498 | Which one to use depends on whether the calling code is creating a python |
| 499 | socket, or if an unused port needs to be provided in a constructor |
| 500 | or passed to an external program (i.e. the ``-accept`` argument to |
| 501 | openssl's s_server mode). Always prefer :func:`bind_port` over |
| 502 | :func:`find_unused_port` where possible. Using a hard coded port is |
| 503 | discouraged since it can makes multiple instances of the test impossible to |
| 504 | run simultaneously, which is a problem for buildbots. |
| 505 | |
| 506 | |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 507 | The :mod:`test.support` module defines the following classes: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 508 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 509 | .. class:: TransientResource(exc, **kwargs) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 510 | |
| 511 | Instances are a context manager that raises :exc:`ResourceDenied` if the |
| 512 | specified exception type is raised. Any keyword arguments are treated as |
| 513 | attribute/value pairs to be compared against any exception raised within the |
| 514 | :keyword:`with` statement. Only if all pairs match properly against |
| 515 | attributes on the exception is :exc:`ResourceDenied` raised. |
| 516 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 517 | |
| 518 | .. class:: EnvironmentVarGuard() |
| 519 | |
Florent Xicluna | 53b506b | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 520 | Class used to temporarily set or unset environment variables. Instances can |
| 521 | be used as a context manager and have a complete dictionary interface for |
| 522 | querying/modifying the underlying ``os.environ``. After exit from the |
| 523 | context manager all changes to environment variables done through this |
| 524 | instance will be rolled back. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 525 | |
Georg Brandl | 705d9d5 | 2009-05-05 09:29:50 +0000 | [diff] [blame] | 526 | .. versionchanged:: 3.1 |
Walter Dörwald | 155374d | 2009-05-01 19:58:58 +0000 | [diff] [blame] | 527 | Added dictionary interface. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 528 | |
| 529 | .. method:: EnvironmentVarGuard.set(envvar, value) |
| 530 | |
Florent Xicluna | 53b506b | 2010-03-18 20:00:57 +0000 | [diff] [blame] | 531 | Temporarily set the environment variable ``envvar`` to the value of |
| 532 | ``value``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 533 | |
| 534 | |
| 535 | .. method:: EnvironmentVarGuard.unset(envvar) |
| 536 | |
| 537 | Temporarily unset the environment variable ``envvar``. |
Nick Coghlan | b130493 | 2008-07-13 12:25:08 +0000 | [diff] [blame] | 538 | |
Walter Dörwald | 155374d | 2009-05-01 19:58:58 +0000 | [diff] [blame] | 539 | |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 540 | .. class:: WarningsRecorder() |
| 541 | |
| 542 | Class used to record warnings for unit tests. See documentation of |
| 543 | :func:`check_warnings` above for more details. |