/Doc/library/test.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 376 lines · 242 code · 134 blank · 0 comment · 0 complexity · 81ca9f2bebe5e28087a5ca6db95a1419 MD5 · raw file

  1. :mod:`test` --- Regression tests package for Python
  2. ===================================================
  3. .. module:: test
  4. :synopsis: Regression tests package containing the testing suite for Python.
  5. .. sectionauthor:: Brett Cannon <brett@python.org>
  6. The :mod:`test` package contains all regression tests for Python as well as the
  7. modules :mod:`test.test_support` and :mod:`test.regrtest`.
  8. :mod:`test.test_support` is used to enhance your tests while
  9. :mod:`test.regrtest` drives the testing suite.
  10. Each module in the :mod:`test` package whose name starts with ``test_`` is a
  11. testing suite for a specific module or feature. All new tests should be written
  12. using the :mod:`unittest` or :mod:`doctest` module. Some older tests are
  13. written using a "traditional" testing style that compares output printed to
  14. ``sys.stdout``; this style of test is considered deprecated.
  15. .. seealso::
  16. Module :mod:`unittest`
  17. Writing PyUnit regression tests.
  18. Module :mod:`doctest`
  19. Tests embedded in documentation strings.
  20. .. _writing-tests:
  21. Writing Unit Tests for the :mod:`test` package
  22. ----------------------------------------------
  23. It is preferred that tests that use the :mod:`unittest` module follow a few
  24. guidelines. One is to name the test module by starting it with ``test_`` and end
  25. it with the name of the module being tested. The test methods in the test module
  26. should start with ``test_`` and end with a description of what the method is
  27. testing. This is needed so that the methods are recognized by the test driver as
  28. test methods. Also, no documentation string for the method should be included. A
  29. comment (such as ``# Tests function returns only True or False``) should be used
  30. to provide documentation for test methods. This is done because documentation
  31. strings get printed out if they exist and thus what test is being run is not
  32. stated.
  33. A basic boilerplate is often used::
  34. import unittest
  35. from test import test_support
  36. class MyTestCase1(unittest.TestCase):
  37. # Only use setUp() and tearDown() if necessary
  38. def setUp(self):
  39. ... code to execute in preparation for tests ...
  40. def tearDown(self):
  41. ... code to execute to clean up after tests ...
  42. def test_feature_one(self):
  43. # Test feature one.
  44. ... testing code ...
  45. def test_feature_two(self):
  46. # Test feature two.
  47. ... testing code ...
  48. ... more test methods ...
  49. class MyTestCase2(unittest.TestCase):
  50. ... same structure as MyTestCase1 ...
  51. ... more test classes ...
  52. def test_main():
  53. test_support.run_unittest(MyTestCase1,
  54. MyTestCase2,
  55. ... list other tests ...
  56. )
  57. if __name__ == '__main__':
  58. test_main()
  59. This boilerplate code allows the testing suite to be run by :mod:`test.regrtest`
  60. as well as on its own as a script.
  61. The goal for regression testing is to try to break code. This leads to a few
  62. guidelines to be followed:
  63. * The testing suite should exercise all classes, functions, and constants. This
  64. includes not just the external API that is to be presented to the outside world
  65. but also "private" code.
  66. * Whitebox testing (examining the code being tested when the tests are being
  67. written) is preferred. Blackbox testing (testing only the published user
  68. interface) is not complete enough to make sure all boundary and edge cases are
  69. tested.
  70. * Make sure all possible values are tested including invalid ones. This makes
  71. sure that not only all valid values are acceptable but also that improper values
  72. are handled correctly.
  73. * Exhaust as many code paths as possible. Test where branching occurs and thus
  74. tailor input to make sure as many different paths through the code are taken.
  75. * Add an explicit test for any bugs discovered for the tested code. This will
  76. make sure that the error does not crop up again if the code is changed in the
  77. future.
  78. * Make sure to clean up after your tests (such as close and remove all temporary
  79. files).
  80. * If a test is dependent on a specific condition of the operating system then
  81. verify the condition already exists before attempting the test.
  82. * Import as few modules as possible and do it as soon as possible. This
  83. minimizes external dependencies of tests and also minimizes possible anomalous
  84. behavior from side-effects of importing a module.
  85. * Try to maximize code reuse. On occasion, tests will vary by something as small
  86. as what type of input is used. Minimize code duplication by subclassing a basic
  87. test class with a class that specifies the input::
  88. class TestFuncAcceptsSequences(unittest.TestCase):
  89. func = mySuperWhammyFunction
  90. def test_func(self):
  91. self.func(self.arg)
  92. class AcceptLists(TestFuncAcceptsSequences):
  93. arg = [1,2,3]
  94. class AcceptStrings(TestFuncAcceptsSequences):
  95. arg = 'abc'
  96. class AcceptTuples(TestFuncAcceptsSequences):
  97. arg = (1,2,3)
  98. .. seealso::
  99. Test Driven Development
  100. A book by Kent Beck on writing tests before code.
  101. .. _regrtest:
  102. Running tests using :mod:`test.regrtest`
  103. ----------------------------------------
  104. :mod:`test.regrtest` can be used as a script to drive Python's regression test
  105. suite. Running the script by itself automatically starts running all regression
  106. tests in the :mod:`test` package. It does this by finding all modules in the
  107. package whose name starts with ``test_``, importing them, and executing the
  108. function :func:`test_main` if present. The names of tests to execute may also be
  109. passed to the script. Specifying a single regression test (:program:`python
  110. regrtest.py` :option:`test_spam.py`) will minimize output and only print whether
  111. the test passed or failed and thus minimize output.
  112. Running :mod:`test.regrtest` directly allows what resources are available for
  113. tests to use to be set. You do this by using the :option:`-u` command-line
  114. option. Run :program:`python regrtest.py` :option:`-uall` to turn on all
  115. resources; specifying :option:`all` as an option for :option:`-u` enables all
  116. possible resources. If all but one resource is desired (a more common case), a
  117. comma-separated list of resources that are not desired may be listed after
  118. :option:`all`. The command :program:`python regrtest.py`
  119. :option:`-uall,-audio,-largefile` will run :mod:`test.regrtest` with all
  120. resources except the :option:`audio` and :option:`largefile` resources. For a
  121. list of all resources and more command-line options, run :program:`python
  122. regrtest.py` :option:`-h`.
  123. Some other ways to execute the regression tests depend on what platform the
  124. tests are being executed on. On Unix, you can run :program:`make` :option:`test`
  125. at the top-level directory where Python was built. On Windows, executing
  126. :program:`rt.bat` from your :file:`PCBuild` directory will run all regression
  127. tests.
  128. :mod:`test.test_support` --- Utility functions for tests
  129. ========================================================
  130. .. module:: test.test_support
  131. :synopsis: Support for Python regression tests.
  132. .. note::
  133. The :mod:`test.test_support` module has been renamed to :mod:`test.support`
  134. in Python 3.0. The :term:`2to3` tool will automatically adapt imports when
  135. converting your sources to 3.0.
  136. The :mod:`test.test_support` module provides support for Python's regression
  137. tests.
  138. This module defines the following exceptions:
  139. .. exception:: TestFailed
  140. Exception to be raised when a test fails. This is deprecated in favor of
  141. :mod:`unittest`\ -based tests and :class:`unittest.TestCase`'s assertion
  142. methods.
  143. .. exception:: TestSkipped
  144. Subclass of :exc:`TestFailed`. Raised when a test is skipped. This occurs when a
  145. needed resource (such as a network connection) is not available at the time of
  146. testing.
  147. .. exception:: ResourceDenied
  148. Subclass of :exc:`TestSkipped`. Raised when a resource (such as a network
  149. connection) is not available. Raised by the :func:`requires` function.
  150. The :mod:`test.test_support` module defines the following constants:
  151. .. data:: verbose
  152. :const:`True` when verbose output is enabled. Should be checked when more
  153. detailed information is desired about a running test. *verbose* is set by
  154. :mod:`test.regrtest`.
  155. .. data:: have_unicode
  156. :const:`True` when Unicode support is available.
  157. .. data:: is_jython
  158. :const:`True` if the running interpreter is Jython.
  159. .. data:: TESTFN
  160. Set to the path that a temporary file may be created at. Any temporary that is
  161. created should be closed and unlinked (removed).
  162. The :mod:`test.test_support` module defines the following functions:
  163. .. function:: forget(module_name)
  164. Removes the module named *module_name* from ``sys.modules`` and deletes any
  165. byte-compiled files of the module.
  166. .. function:: is_resource_enabled(resource)
  167. Returns :const:`True` if *resource* is enabled and available. The list of
  168. available resources is only set when :mod:`test.regrtest` is executing the
  169. tests.
  170. .. function:: requires(resource[, msg])
  171. Raises :exc:`ResourceDenied` if *resource* is not available. *msg* is the
  172. argument to :exc:`ResourceDenied` if it is raised. Always returns true if called
  173. by a function whose ``__name__`` is ``'__main__'``. Used when tests are executed
  174. by :mod:`test.regrtest`.
  175. .. function:: findfile(filename)
  176. Return the path to the file named *filename*. If no match is found *filename* is
  177. returned. This does not equal a failure since it could be the path to the file.
  178. .. function:: run_unittest(*classes)
  179. Execute :class:`unittest.TestCase` subclasses passed to the function. The
  180. function scans the classes for methods starting with the prefix ``test_`` and
  181. executes the tests individually.
  182. It is also legal to pass strings as parameters; these should be keys in
  183. ``sys.modules``. Each associated module will be scanned by
  184. ``unittest.TestLoader.loadTestsFromModule()``. This is usually seen in the
  185. following :func:`test_main` function::
  186. def test_main():
  187. test_support.run_unittest(__name__)
  188. This will run all tests defined in the named module.
  189. .. function:: check_warnings()
  190. A convenience wrapper for ``warnings.catch_warnings()`` that makes
  191. it easier to test that a warning was correctly raised with a single
  192. assertion. It is approximately equivalent to calling
  193. ``warnings.catch_warnings(record=True)``.
  194. The main difference is that on entry to the context manager, a
  195. :class:`WarningRecorder` instance is returned instead of a simple list.
  196. The underlying warnings list is available via the recorder object's
  197. :attr:`warnings` attribute, while the attributes of the last raised
  198. warning are also accessible directly on the object. If no warning has
  199. been raised, then the latter attributes will all be :const:`None`.
  200. A :meth:`reset` method is also provided on the recorder object. This
  201. method simply clears the warning list.
  202. The context manager is used like this::
  203. with check_warnings() as w:
  204. warnings.simplefilter("always")
  205. warnings.warn("foo")
  206. assert str(w.message) == "foo"
  207. warnings.warn("bar")
  208. assert str(w.message) == "bar"
  209. assert str(w.warnings[0].message) == "foo"
  210. assert str(w.warnings[1].message) == "bar"
  211. w.reset()
  212. assert len(w.warnings) == 0
  213. .. versionadded:: 2.6
  214. .. function:: captured_stdout()
  215. This is a context manager than runs the :keyword:`with` statement body using
  216. a :class:`StringIO.StringIO` object as sys.stdout. That object can be
  217. retrieved using the ``as`` clause of the :keyword:`with` statement.
  218. Example use::
  219. with captured_stdout() as s:
  220. print "hello"
  221. assert s.getvalue() == "hello"
  222. .. versionadded:: 2.6
  223. The :mod:`test.test_support` module defines the following classes:
  224. .. class:: TransientResource(exc[, **kwargs])
  225. Instances are a context manager that raises :exc:`ResourceDenied` if the
  226. specified exception type is raised. Any keyword arguments are treated as
  227. attribute/value pairs to be compared against any exception raised within the
  228. :keyword:`with` statement. Only if all pairs match properly against
  229. attributes on the exception is :exc:`ResourceDenied` raised.
  230. .. versionadded:: 2.6
  231. .. class:: EnvironmentVarGuard()
  232. Class used to temporarily set or unset environment variables. Instances can be
  233. used as a context manager.
  234. .. versionadded:: 2.6
  235. .. method:: EnvironmentVarGuard.set(envvar, value)
  236. Temporarily set the environment variable ``envvar`` to the value of ``value``.
  237. .. method:: EnvironmentVarGuard.unset(envvar)
  238. Temporarily unset the environment variable ``envvar``.
  239. .. class:: WarningsRecorder()
  240. Class used to record warnings for unit tests. See documentation of
  241. :func:`check_warnings` above for more details.
  242. .. versionadded:: 2.6