/External.LCA_RESTRICTED/Languages/IronPython/27/Doc/IronPythonDocs/library/test.rst

http://github.com/IronLanguages/main · ReStructuredText · 469 lines · 312 code · 157 blank · 0 comment · 0 complexity · 55db33882c403f150ff1620928794da9 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
  65. world 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
  69. are 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
  72. values 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
  87. basic 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
  109. be passed to the script. Specifying a single regression test (:program:`python
  110. regrtest.py` :option:`test_spam.py`) will minimize output and only print
  111. whether 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`
  125. :option:`test` at the top-level directory where Python was built. On Windows,
  126. executing :program:`rt.bat` from your :file:`PCBuild` directory will run all
  127. regression 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.x.
  135. The :mod:`test.test_support` module provides support for Python's regression
  136. tests.
  137. This module defines the following exceptions:
  138. .. exception:: TestFailed
  139. Exception to be raised when a test fails. This is deprecated in favor of
  140. :mod:`unittest`\ -based tests and :class:`unittest.TestCase`'s assertion
  141. methods.
  142. .. exception:: ResourceDenied
  143. Subclass of :exc:`unittest.SkipTest`. Raised when a resource (such as a
  144. network connection) is not available. Raised by the :func:`requires`
  145. function.
  146. The :mod:`test.test_support` module defines the following constants:
  147. .. data:: verbose
  148. :const:`True` when verbose output is enabled. Should be checked when more
  149. detailed information is desired about a running test. *verbose* is set by
  150. :mod:`test.regrtest`.
  151. .. data:: have_unicode
  152. :const:`True` when Unicode support is available.
  153. .. data:: is_jython
  154. :const:`True` if the running interpreter is Jython.
  155. .. data:: TESTFN
  156. Set to a name that is safe to use as the name of a temporary file. Any
  157. temporary file that is created should be closed and unlinked (removed).
  158. The :mod:`test.test_support` module defines the following functions:
  159. .. function:: forget(module_name)
  160. Remove the module named *module_name* from ``sys.modules`` and delete any
  161. byte-compiled files of the module.
  162. .. function:: is_resource_enabled(resource)
  163. Return :const:`True` if *resource* is enabled and available. The list of
  164. available resources is only set when :mod:`test.regrtest` is executing the
  165. tests.
  166. .. function:: requires(resource[, msg])
  167. Raise :exc:`ResourceDenied` if *resource* is not available. *msg* is the
  168. argument to :exc:`ResourceDenied` if it is raised. Always returns
  169. :const:`True` if called by a function whose ``__name__`` is ``'__main__'``.
  170. Used when tests are executed by :mod:`test.regrtest`.
  171. .. function:: findfile(filename)
  172. Return the path to the file named *filename*. If no match is found
  173. *filename* is returned. This does not equal a failure since it could be the
  174. path to the file.
  175. .. function:: run_unittest(*classes)
  176. Execute :class:`unittest.TestCase` subclasses passed to the function. The
  177. function scans the classes for methods starting with the prefix ``test_``
  178. and executes the tests individually.
  179. It is also legal to pass strings as parameters; these should be keys in
  180. ``sys.modules``. Each associated module will be scanned by
  181. ``unittest.TestLoader.loadTestsFromModule()``. This is usually seen in the
  182. following :func:`test_main` function::
  183. def test_main():
  184. test_support.run_unittest(__name__)
  185. This will run all tests defined in the named module.
  186. .. function:: check_warnings(*filters, quiet=True)
  187. A convenience wrapper for :func:`warnings.catch_warnings()` that makes it
  188. easier to test that a warning was correctly raised. It is approximately
  189. equivalent to calling ``warnings.catch_warnings(record=True)`` with
  190. :meth:`warnings.simplefilter` set to ``always`` and with the option to
  191. automatically validate the results that are recorded.
  192. ``check_warnings`` accepts 2-tuples of the form ``("message regexp",
  193. WarningCategory)`` as positional arguments. If one or more *filters* are
  194. provided, or if the optional keyword argument *quiet* is :const:`False`,
  195. it checks to make sure the warnings are as expected: each specified filter
  196. must match at least one of the warnings raised by the enclosed code or the
  197. test fails, and if any warnings are raised that do not match any of the
  198. specified filters the test fails. To disable the first of these checks,
  199. set *quiet* to :const:`True`.
  200. If no arguments are specified, it defaults to::
  201. check_warnings(("", Warning), quiet=True)
  202. In this case all warnings are caught and no errors are raised.
  203. On entry to the context manager, a :class:`WarningRecorder` instance is
  204. returned. The underlying warnings list from
  205. :func:`~warnings.catch_warnings` is available via the recorder object's
  206. :attr:`warnings` attribute. As a convenience, the attributes of the object
  207. representing the most recent warning can also be accessed directly through
  208. the recorder object (see example below). If no warning has been raised,
  209. then any of the attributes that would otherwise be expected on an object
  210. representing a warning will return :const:`None`.
  211. The recorder object also has a :meth:`reset` method, which clears the
  212. warnings list.
  213. The context manager is designed to be used like this::
  214. with check_warnings(("assertion is always true", SyntaxWarning),
  215. ("", UserWarning)):
  216. exec('assert(False, "Hey!")')
  217. warnings.warn(UserWarning("Hide me!"))
  218. In this case if either warning was not raised, or some other warning was
  219. raised, :func:`check_warnings` would raise an error.
  220. When a test needs to look more deeply into the warnings, rather than
  221. just checking whether or not they occurred, code like this can be used::
  222. with check_warnings(quiet=True) as w:
  223. warnings.warn("foo")
  224. assert str(w.args[0]) == "foo"
  225. warnings.warn("bar")
  226. assert str(w.args[0]) == "bar"
  227. assert str(w.warnings[0].args[0]) == "foo"
  228. assert str(w.warnings[1].args[0]) == "bar"
  229. w.reset()
  230. assert len(w.warnings) == 0
  231. Here all warnings will be caught, and the test code tests the captured
  232. warnings directly.
  233. .. versionadded:: 2.6
  234. .. versionchanged:: 2.7
  235. New optional arguments *filters* and *quiet*.
  236. .. function:: check_py3k_warnings(*filters, quiet=False)
  237. Similar to :func:`check_warnings`, but for Python 3 compatibility warnings.
  238. If ``sys.py3kwarning == 1``, it checks if the warning is effectively raised.
  239. If ``sys.py3kwarning == 0``, it checks that no warning is raised. It
  240. accepts 2-tuples of the form ``("message regexp", WarningCategory)`` as
  241. positional arguments. When the optional keyword argument *quiet* is
  242. :const:`True`, it does not fail if a filter catches nothing. Without
  243. arguments, it defaults to::
  244. check_py3k_warnings(("", DeprecationWarning), quiet=False)
  245. .. versionadded:: 2.7
  246. .. function:: captured_stdout()
  247. This is a context manager that runs the :keyword:`with` statement body using
  248. a :class:`StringIO.StringIO` object as sys.stdout. That object can be
  249. retrieved using the ``as`` clause of the :keyword:`with` statement.
  250. Example use::
  251. with captured_stdout() as s:
  252. print "hello"
  253. assert s.getvalue() == "hello"
  254. .. versionadded:: 2.6
  255. .. function:: import_module(name, deprecated=False)
  256. This function imports and returns the named module. Unlike a normal
  257. import, this function raises :exc:`unittest.SkipTest` if the module
  258. cannot be imported.
  259. Module and package deprecation messages are suppressed during this import
  260. if *deprecated* is :const:`True`.
  261. .. versionadded:: 2.7
  262. .. function:: import_fresh_module(name, fresh=(), blocked=(), deprecated=False)
  263. This function imports and returns a fresh copy of the named Python module
  264. by removing the named module from ``sys.modules`` before doing the import.
  265. Note that unlike :func:`reload`, the original module is not affected by
  266. this operation.
  267. *fresh* is an iterable of additional module names that are also removed
  268. from the ``sys.modules`` cache before doing the import.
  269. *blocked* is an iterable of module names that are replaced with :const:`0`
  270. in the module cache during the import to ensure that attempts to import
  271. them raise :exc:`ImportError`.
  272. The named module and any modules named in the *fresh* and *blocked*
  273. parameters are saved before starting the import and then reinserted into
  274. ``sys.modules`` when the fresh import is complete.
  275. Module and package deprecation messages are suppressed during this import
  276. if *deprecated* is :const:`True`.
  277. This function will raise :exc:`unittest.SkipTest` is the named module
  278. cannot be imported.
  279. Example use::
  280. # Get copies of the warnings module for testing without
  281. # affecting the version being used by the rest of the test suite
  282. # One copy uses the C implementation, the other is forced to use
  283. # the pure Python fallback implementation
  284. py_warnings = import_fresh_module('warnings', blocked=['_warnings'])
  285. c_warnings = import_fresh_module('warnings', fresh=['_warnings'])
  286. .. versionadded:: 2.7
  287. The :mod:`test.test_support` module defines the following classes:
  288. .. class:: TransientResource(exc[, **kwargs])
  289. Instances are a context manager that raises :exc:`ResourceDenied` if the
  290. specified exception type is raised. Any keyword arguments are treated as
  291. attribute/value pairs to be compared against any exception raised within the
  292. :keyword:`with` statement. Only if all pairs match properly against
  293. attributes on the exception is :exc:`ResourceDenied` raised.
  294. .. versionadded:: 2.6
  295. .. class:: EnvironmentVarGuard()
  296. Class used to temporarily set or unset environment variables. Instances can
  297. be used as a context manager and have a complete dictionary interface for
  298. querying/modifying the underlying ``os.environ``. After exit from the
  299. context manager all changes to environment variables done through this
  300. instance will be rolled back.
  301. .. versionadded:: 2.6
  302. .. versionchanged:: 2.7
  303. Added dictionary interface.
  304. .. method:: EnvironmentVarGuard.set(envvar, value)
  305. Temporarily set the environment variable ``envvar`` to the value of
  306. ``value``.
  307. .. method:: EnvironmentVarGuard.unset(envvar)
  308. Temporarily unset the environment variable ``envvar``.
  309. .. class:: WarningsRecorder()
  310. Class used to record warnings for unit tests. See documentation of
  311. :func:`check_warnings` above for more details.
  312. .. versionadded:: 2.6