Ignore:
Timestamp:
Mar 19, 2014, 11:31:01 PM (11 years ago)
Author:
dmik
Message:

python: Merge vendor 2.7.6 to trunk.

Location:
python/trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • python/trunk

  • python/trunk/Doc/library/test.rst

    r2 r391  
    66   :synopsis: Regression tests package containing the testing suite for Python.
    77.. 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.
    815
    916
     
    9198
    9299* 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 world
    94   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.
    95102
    96103* Whitebox testing (examining the code being tested when the tests are being
    97104  written) is preferred. Blackbox testing (testing only the published user
    98   interface) is not complete enough to make sure all boundary and edge cases are
    99   tested.
     105  interface) is not complete enough to make sure all boundary and edge cases
     106  are tested.
    100107
    101108* 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 values
    103   are handled correctly.
     109  sure that not only all valid values are acceptable but also that improper
     110  values are handled correctly.
    104111
    105112* Exhaust as many code paths as possible. Test where branching occurs and thus
     
    121128
    122129* 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 basic
    124   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::
    125132
    126133     class TestFuncAcceptsSequences(unittest.TestCase):
     
    132139
    133140     class AcceptLists(TestFuncAcceptsSequences):
    134          arg = [1,2,3]
     141         arg = [1, 2, 3]
    135142
    136143     class AcceptStrings(TestFuncAcceptsSequences):
     
    138145
    139146     class AcceptTuples(TestFuncAcceptsSequences):
    140          arg = (1,2,3)
     147         arg = (1, 2, 3)
    141148
    142149
     
    149156.. _regrtest:
    150157
    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
     158Running tests using the command-line interface
     159----------------------------------------------
     160
     161The :mod:`test.regrtest` module can be run as a script to drive Python's regression
     162test suite, thanks to the :option:`-m` option: :program:`python -m test.regrtest`.
     163Running the script by itself automatically starts running all regression
    156164tests in the :mod:`test` package. It does this by finding all modules in the
    157165package 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 be
    159 passed to the script. Specifying a single regression test (:program:`python
    160 regrtest.py` :option:`test_spam.py`) will minimize output and only print whether
     166function :func:`test_main` if present. The names of tests to execute may also
     167be passed to the script. Specifying a single regression test (:program:`python
     168-m test.regrtest test_spam`) will minimize output and only print whether
    161169the test passed or failed and thus minimize output.
    162170
    163171Running :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-line
    165 option. Run :program:`python regrtest.py` :option:`-uall` to turn on all
    166 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), a
     172tests to use to be set. You do this by using the ``-u`` command-line
     173option. Specifying ``all`` as the value for the ``-u`` option enables all
     174possible resources: :program:`python -m test -uall`.
     175If all but one resource is desired (a more common case), a
    168176comma-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`
     178will run :mod:`test.regrtest` with all resources except the ``audio`` and
     179``largefile`` resources. For a list of all resources and more command-line
     180options, run :program:`python -m test.regrtest -h`.
    174181
    175182Some 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 the top-level directory where Python was built. On Windows, executing
     183tests are being executed on. On Unix, you can run :program:`make test` at the
     184top-level directory where Python was built. On Windows, executing
    178185:program:`rt.bat` from your :file:`PCBuild` directory will run all regression
    179186tests.
     
    189196
    190197   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.
    196199
    197200The :mod:`test.test_support` module provides support for Python's regression
     
    208211
    209212
    210 .. exception:: TestSkipped
    211 
    212    Subclass of :exc:`TestFailed`. Raised when a test is skipped. This occurs when a
    213    needed resource (such as a network connection) is not available at the time of
    214    testing.
    215 
    216 
    217213.. exception:: ResourceDenied
    218214
    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.
    221218
    222219The :mod:`test.test_support` module defines the following constants:
     
    242239.. data:: TESTFN
    243240
    244    Set to the path that a temporary file may be created at. Any temporary that is
    245    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).
    246243
    247244The :mod:`test.test_support` module defines the following functions:
     
    250247.. function:: forget(module_name)
    251248
    252    Removes the module named *module_name* from ``sys.modules`` and deletes any
     249   Remove the module named *module_name* from ``sys.modules`` and delete any
    253250   byte-compiled files of the module.
    254251
     
    256253.. function:: is_resource_enabled(resource)
    257254
    258    Returns :const:`True` if *resource* is enabled and available. The list of
     255   Return :const:`True` if *resource* is enabled and available. The list of
    259256   available resources is only set when :mod:`test.regrtest` is executing the
    260257   tests.
     
    263260.. function:: requires(resource[, msg])
    264261
    265    Raises :exc:`ResourceDenied` if *resource* is not available. *msg* is the
    266    argument to :exc:`ResourceDenied` if it is raised. Always returns true if called
    267    by a function whose ``__name__`` is ``'__main__'``. Used when tests are executed
    268    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`.
    269266
    270267
    271268.. function:: findfile(filename)
    272269
    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.
    275273
    276274
     
    278276
    279277   Execute :class:`unittest.TestCase` subclasses passed to the function. The
    280    function scans the classes for methods starting with the prefix ``test_`` and
    281    executes the tests individually.
     278   function scans the classes for methods starting with the prefix ``test_``
     279   and executes the tests individually.
    282280
    283281   It is also legal to pass strings as parameters; these should be keys in
     
    292290
    293291
    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:
    315341          warnings.warn("foo")
    316           assert str(w.message) == "foo"
     342          assert str(w.args[0]) == "foo"
    317343          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"
    321347          w.reset()
    322348          assert len(w.warnings) == 0
    323349
     350   Here all warnings will be caught, and the test code tests the captured
     351   warnings directly.
     352
    324353   .. 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
    325371
    326372
    327373.. function:: captured_stdout()
    328374
    329    This is a context manager than runs the :keyword:`with` statement body using
     375   This is a context manager that runs the :keyword:`with` statement body using
    330376   a :class:`StringIO.StringIO` object as sys.stdout.  That object can be
    331377   retrieved using the ``as`` clause of the :keyword:`with` statement.
     
    335381      with captured_stdout() as s:
    336382          print "hello"
    337       assert s.getvalue() == "hello"
     383      assert s.getvalue() == "hello\n"
    338384
    339385   .. 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
    340434
    341435
     
    353447.. class:: EnvironmentVarGuard()
    354448
    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.
    357454
    358455   .. versionadded:: 2.6
     456   .. versionchanged:: 2.7
     457      Added dictionary interface.
    359458
    360459
    361460.. method:: EnvironmentVarGuard.set(envvar, value)
    362461
    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``.
    364464
    365465
     
    367467
    368468   Temporarily unset the environment variable ``envvar``.
     469
    369470
    370471.. class:: WarningsRecorder()
     
    374475
    375476   .. versionadded:: 2.6
    376 
Note: See TracChangeset for help on using the changeset viewer.