Changeset 391 for python/trunk/Doc/library/test.rst
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
python/trunk
-
Property svn:mergeinfo
set to
/python/vendor/Python-2.7.6 merged eligible /python/vendor/current merged eligible
-
Property svn:mergeinfo
set to
-
python/trunk/Doc/library/test.rst
r2 r391 6 6 :synopsis: Regression tests package containing the testing suite for Python. 7 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. 8 15 9 16 … … 91 98 92 99 * The testing suite should exercise all classes, functions, and constants. This 93 includes not just the external API that is to be presented to the outside world94 but also "private" code.100 includes not just the external API that is to be presented to the outside 101 world but also "private" code. 95 102 96 103 * Whitebox testing (examining the code being tested when the tests are being 97 104 written) is preferred. Blackbox testing (testing only the published user 98 interface) is not complete enough to make sure all boundary and edge cases are99 tested.105 interface) is not complete enough to make sure all boundary and edge cases 106 are tested. 100 107 101 108 * Make sure all possible values are tested including invalid ones. This makes 102 sure that not only all valid values are acceptable but also that improper values103 are handled correctly.109 sure that not only all valid values are acceptable but also that improper 110 values are handled correctly. 104 111 105 112 * Exhaust as many code paths as possible. Test where branching occurs and thus … … 121 128 122 129 * Try to maximize code reuse. On occasion, tests will vary by something as small 123 as what type of input is used. Minimize code duplication by subclassing a basic124 test class with a class that specifies the input::130 as what type of input is used. Minimize code duplication by subclassing a 131 basic test class with a class that specifies the input:: 125 132 126 133 class TestFuncAcceptsSequences(unittest.TestCase): … … 132 139 133 140 class AcceptLists(TestFuncAcceptsSequences): 134 arg = [1, 2,3]141 arg = [1, 2, 3] 135 142 136 143 class AcceptStrings(TestFuncAcceptsSequences): … … 138 145 139 146 class AcceptTuples(TestFuncAcceptsSequences): 140 arg = (1, 2,3)147 arg = (1, 2, 3) 141 148 142 149 … … 149 156 .. _regrtest: 150 157 151 Running tests using :mod:`test.regrtest` 152 ---------------------------------------- 153 154 :mod:`test.regrtest` can be used as a script to drive Python's regression test 155 suite. Running the script by itself automatically starts running all regression 158 Running tests using the command-line interface 159 ---------------------------------------------- 160 161 The :mod:`test.regrtest` module can be run as a script to drive Python's regression 162 test suite, thanks to the :option:`-m` option: :program:`python -m test.regrtest`. 163 Running the script by itself automatically starts running all regression 156 164 tests in the :mod:`test` package. It does this by finding all modules in the 157 165 package whose name starts with ``test_``, importing them, and executing the 158 function :func:`test_main` if present. The names of tests to execute may also be159 passed to the script. Specifying a single regression test (:program:`python160 regrtest.py` :option:`test_spam.py`) will minimize output and only print whether166 function :func:`test_main` if present. The names of tests to execute may also 167 be passed to the script. Specifying a single regression test (:program:`python 168 -m test.regrtest test_spam`) will minimize output and only print whether 161 169 the test passed or failed and thus minimize output. 162 170 163 171 Running :mod:`test.regrtest` directly allows what resources are available for 164 tests to use to be set. You do this by using the :option:`-u` command-line165 option. Run :program:`python regrtest.py` :option:`-uall` to turn onall166 resources; specifying :option:`all` as an option for :option:`-u` enables all 167 possible resources.If all but one resource is desired (a more common case), a172 tests to use to be set. You do this by using the ``-u`` command-line 173 option. Specifying ``all`` as the value for the ``-u`` option enables all 174 possible resources: :program:`python -m test -uall`. 175 If all but one resource is desired (a more common case), a 168 176 comma-separated list of resources that are not desired may be listed after 169 :option:`all`. The command :program:`python regrtest.py` 170 :option:`-uall,-audio,-largefile` will run :mod:`test.regrtest` with all 171 resources except the :option:`audio` and :option:`largefile` resources. For a 172 list of all resources and more command-line options, run :program:`python 173 regrtest.py` :option:`-h`. 177 ``all``. The command :program:`python -m test.regrtest -uall,-audio,-largefile` 178 will run :mod:`test.regrtest` with all resources except the ``audio`` and 179 ``largefile`` resources. For a list of all resources and more command-line 180 options, run :program:`python -m test.regrtest -h`. 174 181 175 182 Some other ways to execute the regression tests depend on what platform the 176 tests are being executed on. On Unix, you can run :program:`make ` :option:`test`177 at thetop-level directory where Python was built. On Windows, executing183 tests are being executed on. On Unix, you can run :program:`make test` at the 184 top-level directory where Python was built. On Windows, executing 178 185 :program:`rt.bat` from your :file:`PCBuild` directory will run all regression 179 186 tests. … … 189 196 190 197 The :mod:`test.test_support` module has been renamed to :mod:`test.support` 191 in Python 3.0. The :term:`2to3` tool will automatically adapt imports when 192 converting your sources to 3.0. 193 194 195 198 in Python 3.x. 196 199 197 200 The :mod:`test.test_support` module provides support for Python's regression … … 208 211 209 212 210 .. exception:: TestSkipped211 212 Subclass of :exc:`TestFailed`. Raised when a test is skipped. This occurs when a213 needed resource (such as a network connection) is not available at the time of214 testing.215 216 217 213 .. exception:: ResourceDenied 218 214 219 Subclass of :exc:`TestSkipped`. Raised when a resource (such as a network 220 connection) is not available. Raised by the :func:`requires` function. 215 Subclass of :exc:`unittest.SkipTest`. Raised when a resource (such as a 216 network connection) is not available. Raised by the :func:`requires` 217 function. 221 218 222 219 The :mod:`test.test_support` module defines the following constants: … … 242 239 .. data:: TESTFN 243 240 244 Set to the path that a temporary file may be created at. Any temporary that is245 created should be closed and unlinked (removed).241 Set to a name that is safe to use as the name of a temporary file. Any 242 temporary file that is created should be closed and unlinked (removed). 246 243 247 244 The :mod:`test.test_support` module defines the following functions: … … 250 247 .. function:: forget(module_name) 251 248 252 Remove s the module named *module_name* from ``sys.modules`` and deletesany249 Remove the module named *module_name* from ``sys.modules`` and delete any 253 250 byte-compiled files of the module. 254 251 … … 256 253 .. function:: is_resource_enabled(resource) 257 254 258 Return s:const:`True` if *resource* is enabled and available. The list of255 Return :const:`True` if *resource* is enabled and available. The list of 259 256 available resources is only set when :mod:`test.regrtest` is executing the 260 257 tests. … … 263 260 .. function:: requires(resource[, msg]) 264 261 265 Raise s:exc:`ResourceDenied` if *resource* is not available. *msg* is the266 argument to :exc:`ResourceDenied` if it is raised. Always returns true if called267 by a function whose ``__name__`` is ``'__main__'``. Used when tests are executed268 by :mod:`test.regrtest`.262 Raise :exc:`ResourceDenied` if *resource* is not available. *msg* is the 263 argument to :exc:`ResourceDenied` if it is raised. Always returns 264 :const:`True` if called by a function whose ``__name__`` is ``'__main__'``. 265 Used when tests are executed by :mod:`test.regrtest`. 269 266 270 267 271 268 .. function:: findfile(filename) 272 269 273 Return the path to the file named *filename*. If no match is found *filename* is 274 returned. This does not equal a failure since it could be the path to the file. 270 Return the path to the file named *filename*. If no match is found 271 *filename* is returned. This does not equal a failure since it could be the 272 path to the file. 275 273 276 274 … … 278 276 279 277 Execute :class:`unittest.TestCase` subclasses passed to the function. The 280 function scans the classes for methods starting with the prefix ``test_`` and281 executes the tests individually.278 function scans the classes for methods starting with the prefix ``test_`` 279 and executes the tests individually. 282 280 283 281 It is also legal to pass strings as parameters; these should be keys in … … 292 290 293 291 294 .. function:: check_warnings() 295 296 A convenience wrapper for ``warnings.catch_warnings()`` that makes 297 it easier to test that a warning was correctly raised with a single 298 assertion. It is approximately equivalent to calling 299 ``warnings.catch_warnings(record=True)``. 300 301 The main difference is that on entry to the context manager, a 302 :class:`WarningRecorder` instance is returned instead of a simple list. 303 The underlying warnings list is available via the recorder object's 304 :attr:`warnings` attribute, while the attributes of the last raised 305 warning are also accessible directly on the object. If no warning has 306 been raised, then the latter attributes will all be :const:`None`. 307 308 A :meth:`reset` method is also provided on the recorder object. This 309 method simply clears the warning list. 310 311 The context manager is used like this:: 312 313 with check_warnings() as w: 314 warnings.simplefilter("always") 292 .. function:: check_warnings(*filters, quiet=True) 293 294 A convenience wrapper for :func:`warnings.catch_warnings()` that makes it 295 easier to test that a warning was correctly raised. It is approximately 296 equivalent to calling ``warnings.catch_warnings(record=True)`` with 297 :meth:`warnings.simplefilter` set to ``always`` and with the option to 298 automatically validate the results that are recorded. 299 300 ``check_warnings`` accepts 2-tuples of the form ``("message regexp", 301 WarningCategory)`` as positional arguments. If one or more *filters* are 302 provided, or if the optional keyword argument *quiet* is :const:`False`, 303 it checks to make sure the warnings are as expected: each specified filter 304 must match at least one of the warnings raised by the enclosed code or the 305 test fails, and if any warnings are raised that do not match any of the 306 specified filters the test fails. To disable the first of these checks, 307 set *quiet* to :const:`True`. 308 309 If no arguments are specified, it defaults to:: 310 311 check_warnings(("", Warning), quiet=True) 312 313 In this case all warnings are caught and no errors are raised. 314 315 On entry to the context manager, a :class:`WarningRecorder` instance is 316 returned. The underlying warnings list from 317 :func:`~warnings.catch_warnings` is available via the recorder object's 318 :attr:`warnings` attribute. As a convenience, the attributes of the object 319 representing the most recent warning can also be accessed directly through 320 the recorder object (see example below). If no warning has been raised, 321 then any of the attributes that would otherwise be expected on an object 322 representing a warning will return :const:`None`. 323 324 The recorder object also has a :meth:`reset` method, which clears the 325 warnings list. 326 327 The context manager is designed to be used like this:: 328 329 with check_warnings(("assertion is always true", SyntaxWarning), 330 ("", UserWarning)): 331 exec('assert(False, "Hey!")') 332 warnings.warn(UserWarning("Hide me!")) 333 334 In this case if either warning was not raised, or some other warning was 335 raised, :func:`check_warnings` would raise an error. 336 337 When a test needs to look more deeply into the warnings, rather than 338 just checking whether or not they occurred, code like this can be used:: 339 340 with check_warnings(quiet=True) as w: 315 341 warnings.warn("foo") 316 assert str(w. message) == "foo"342 assert str(w.args[0]) == "foo" 317 343 warnings.warn("bar") 318 assert str(w. message) == "bar"319 assert str(w.warnings[0]. message) == "foo"320 assert str(w.warnings[1]. message) == "bar"344 assert str(w.args[0]) == "bar" 345 assert str(w.warnings[0].args[0]) == "foo" 346 assert str(w.warnings[1].args[0]) == "bar" 321 347 w.reset() 322 348 assert len(w.warnings) == 0 323 349 350 Here all warnings will be caught, and the test code tests the captured 351 warnings directly. 352 324 353 .. versionadded:: 2.6 354 .. versionchanged:: 2.7 355 New optional arguments *filters* and *quiet*. 356 357 358 .. function:: check_py3k_warnings(*filters, quiet=False) 359 360 Similar to :func:`check_warnings`, but for Python 3 compatibility warnings. 361 If ``sys.py3kwarning == 1``, it checks if the warning is effectively raised. 362 If ``sys.py3kwarning == 0``, it checks that no warning is raised. It 363 accepts 2-tuples of the form ``("message regexp", WarningCategory)`` as 364 positional arguments. When the optional keyword argument *quiet* is 365 :const:`True`, it does not fail if a filter catches nothing. Without 366 arguments, it defaults to:: 367 368 check_py3k_warnings(("", DeprecationWarning), quiet=False) 369 370 .. versionadded:: 2.7 325 371 326 372 327 373 .. function:: captured_stdout() 328 374 329 This is a context manager tha nruns the :keyword:`with` statement body using375 This is a context manager that runs the :keyword:`with` statement body using 330 376 a :class:`StringIO.StringIO` object as sys.stdout. That object can be 331 377 retrieved using the ``as`` clause of the :keyword:`with` statement. … … 335 381 with captured_stdout() as s: 336 382 print "hello" 337 assert s.getvalue() == "hello "383 assert s.getvalue() == "hello\n" 338 384 339 385 .. versionadded:: 2.6 386 387 388 .. function:: import_module(name, deprecated=False) 389 390 This function imports and returns the named module. Unlike a normal 391 import, this function raises :exc:`unittest.SkipTest` if the module 392 cannot be imported. 393 394 Module and package deprecation messages are suppressed during this import 395 if *deprecated* is :const:`True`. 396 397 .. versionadded:: 2.7 398 399 400 .. function:: import_fresh_module(name, fresh=(), blocked=(), deprecated=False) 401 402 This function imports and returns a fresh copy of the named Python module 403 by removing the named module from ``sys.modules`` before doing the import. 404 Note that unlike :func:`reload`, the original module is not affected by 405 this operation. 406 407 *fresh* is an iterable of additional module names that are also removed 408 from the ``sys.modules`` cache before doing the import. 409 410 *blocked* is an iterable of module names that are replaced with :const:`0` 411 in the module cache during the import to ensure that attempts to import 412 them raise :exc:`ImportError`. 413 414 The named module and any modules named in the *fresh* and *blocked* 415 parameters are saved before starting the import and then reinserted into 416 ``sys.modules`` when the fresh import is complete. 417 418 Module and package deprecation messages are suppressed during this import 419 if *deprecated* is :const:`True`. 420 421 This function will raise :exc:`unittest.SkipTest` is the named module 422 cannot be imported. 423 424 Example use:: 425 426 # Get copies of the warnings module for testing without 427 # affecting the version being used by the rest of the test suite 428 # One copy uses the C implementation, the other is forced to use 429 # the pure Python fallback implementation 430 py_warnings = import_fresh_module('warnings', blocked=['_warnings']) 431 c_warnings = import_fresh_module('warnings', fresh=['_warnings']) 432 433 .. versionadded:: 2.7 340 434 341 435 … … 353 447 .. class:: EnvironmentVarGuard() 354 448 355 Class used to temporarily set or unset environment variables. Instances can be 356 used as a context manager. 449 Class used to temporarily set or unset environment variables. Instances can 450 be used as a context manager and have a complete dictionary interface for 451 querying/modifying the underlying ``os.environ``. After exit from the 452 context manager all changes to environment variables done through this 453 instance will be rolled back. 357 454 358 455 .. versionadded:: 2.6 456 .. versionchanged:: 2.7 457 Added dictionary interface. 359 458 360 459 361 460 .. method:: EnvironmentVarGuard.set(envvar, value) 362 461 363 Temporarily set the environment variable ``envvar`` to the value of ``value``. 462 Temporarily set the environment variable ``envvar`` to the value of 463 ``value``. 364 464 365 465 … … 367 467 368 468 Temporarily unset the environment variable ``envvar``. 469 369 470 370 471 .. class:: WarningsRecorder() … … 374 475 375 476 .. versionadded:: 2.6 376
Note:
See TracChangeset
for help on using the changeset viewer.