DESCRIPTION.rst 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. testresources: extensions to python unittest to allow declarative use
  2. of resources by test cases.
  3. Copyright (C) 2005-2013 Robert Collins <robertc@robertcollins.net>
  4. Licensed under either the Apache License, Version 2.0 or the BSD 3-clause
  5. license at the users choice. A copy of both licenses are available in the
  6. project source as Apache-2.0 and BSD. You may not use this file except in
  7. compliance with one of these two licences.
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under these licenses is distributed on an "AS IS" BASIS, WITHOUT
  10. WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  11. license you chose for the specific language governing permissions and
  12. limitations under that license.
  13. See the COPYING file for full details on the licensing of Testresources.
  14. Testresources
  15. +++++++++++++
  16. testresources extends unittest with a clean and simple api to provide test
  17. optimisation where expensive common resources are needed for test cases - for
  18. example sample working trees for VCS systems, reference databases for
  19. enterprise applications, or web servers ... let imagination run wild.
  20. Dependencies to build/selftest
  21. ==============================
  22. * Python 2.6+ (or 3.3+)
  23. * docutils
  24. * testtools (http://pypi.python.org/pypi/testtools/)
  25. * fixtures (http://pypi.python.org/pypi/fixtures)
  26. Dependencies to use testresources
  27. =================================
  28. * Python 2.6+ (or 3.3+)
  29. For older versions of Python, testresources <= 1.0.0 supported 2.4, 2.5 and
  30. 3.2.
  31. How testresources Works
  32. =======================
  33. The basic idea of testresources is:
  34. * Tests declare the resources they need in a ``resources`` attribute.
  35. * When the test is run, the required resource objects are allocated (either
  36. newly constructed, or reused), and assigned to attributes of the TestCase.
  37. testresources distinguishes a 'resource manager' (a subclass of
  38. ``TestResourceManager``) which acts as a kind of factory, and a 'resource'
  39. which can be any kind of object returned from the manager class's
  40. ``getResource`` method.
  41. Resources are either clean or dirty. Being clean means they have same state in
  42. all important ways as a newly constructed instance and they can therefore be
  43. safely reused.
  44. At this time, testresources is incompatible with setUpClass and setUpModule -
  45. when an OptimisingTestSuite is wrapped around a test suite using those
  46. features, the result will be flattened for optimisation and those setup's will
  47. not run at all.
  48. Main Classes
  49. ============
  50. testresources.ResourcedTestCase
  51. -------------------------------
  52. By extending or mixing-in this class, tests can have necessary resources
  53. automatically allocated and disposed or recycled.
  54. ResourceTestCase can be used as a base class for tests, and when that is done
  55. tests will have their ``resources`` attribute automatically checked for
  56. resources by both OptimisingTestSuite and their own setUp() and tearDown()
  57. methods. (This allows tests to remain functional without needing this specific
  58. TestSuite as a container). Alternatively, you can call setUpResources(self,
  59. resources, test_result) and tearDownResources(self, resources, test_result)
  60. from your own classes setUp and tearDown and the same behaviour will be
  61. activated.
  62. To declare the use of a resource, set the ``resources`` attribute to a list of
  63. tuples of ``(attribute_name, resource_manager)``.
  64. During setUp, for each declared requirement, the test gains an attribute
  65. pointing to an allocated resource, which is the result of calling
  66. ``resource_manager.getResource()``. ``finishedWith`` will be called on each
  67. resource during tearDown().
  68. For example::
  69. class TestLog(testresources.ResourcedTestCase):
  70. resources = [('branch', BzrPopulatedBranch())]
  71. def test_log(self):
  72. show_log(self.branch, ...)
  73. testresources.TestResourceManager
  74. ---------------------------------
  75. A TestResourceManager is an object that tests can use to create resources. It
  76. can be overridden to manage different types of resources. Normally test code
  77. doesn't need to call any methods on it, as this will be arranged by the
  78. testresources machinery.
  79. When implementing a new ``TestResourceManager`` subclass you should consider
  80. overriding these methods:
  81. ``make``
  82. Must be overridden in every concrete subclass.
  83. Returns a new instance of the resource object
  84. (the actual resource, not the TestResourceManager). Doesn't need to worry about
  85. reuse, which is taken care of separately. This method is only called when a
  86. new resource is definitely needed.
  87. ``make`` is called by ``getResource``; you should not normally need to override
  88. the latter.
  89. ``clean``
  90. Cleans up an existing resource instance, eg by deleting a directory or
  91. closing a network connection. By default this does nothing, which may be
  92. appropriate for resources that are automatically garbage collected.
  93. ``_reset``
  94. Reset a no-longer-used dirty resource to a clean state. By default this
  95. just discards it and creates a new one, but for some resources there may be a
  96. faster way to reset them.
  97. ``isDirty``
  98. Check whether an existing resource is dirty. By default this just reports
  99. whether ``TestResourceManager.dirtied`` has been called or any of the
  100. dependency resources are dirty.
  101. For instance::
  102. class TemporaryDirectoryResource(TestResourceManager):
  103. def clean(self, resource):
  104. shutil.rmtree(resource)
  105. def make(self):
  106. return tempfile.mkdtemp()
  107. def isDirty(self, resource):
  108. # Can't detect when the directory is written to, so assume it
  109. # can never be reused. We could list the directory, but that might
  110. # not catch it being open as a cwd etc.
  111. return True
  112. The ``resources`` list on the TestResourceManager object is used to declare
  113. dependencies. For instance, a DataBaseResource that needs a TemporaryDirectory
  114. might be declared with a resources list::
  115. class DataBaseResource(TestResourceManager):
  116. resources = [("scratchdir", TemporaryDirectoryResource())]
  117. Most importantly, two getResources to the same TestResourceManager with no
  118. finishedWith call in the middle, will return the same object as long as it is
  119. not dirty.
  120. When a Test has a dependency and that dependency successfully completes but
  121. returns None, the framework does *not* consider this an error: be sure to always
  122. return a valid resource, or raise an error. Error handling hasn't been heavily
  123. exercised, but any bugs in this area will be promptly dealt with.
  124. A sample TestResourceManager can be found in the doc/ folder.
  125. See pydoc testresources.TestResourceManager for details.
  126. testresources.GenericResource
  127. -----------------------------
  128. Glue to adapt testresources to an existing resource-like class.
  129. testresources.FixtureResource
  130. -----------------------------
  131. Glue to adapt testresources to the simpler fixtures.Fixture API. Long
  132. term testresources is likely to consolidate on that simpler API as the
  133. recommended method of writing resources.
  134. testresources.OptimisingTestSuite
  135. ---------------------------------
  136. This TestSuite will introspect all the test cases it holds directly and if
  137. they declare needed resources, will run the tests in an order that attempts to
  138. minimise the number of setup and tear downs required. It attempts to achieve
  139. this by callling getResource() and finishedWith() around the sequence of tests
  140. that use a specific resource.
  141. Tests are added to an OptimisingTestSuite as normal. Any standard library
  142. TestSuite objects will be flattened, while any custom TestSuite subclasses
  143. will be distributed across their member tests. This means that any custom
  144. logic in test suites should be preserved, at the price of some level of
  145. optimisation.
  146. Because the test suite does the optimisation, you can control the amount of
  147. optimising that takes place by adding more or fewer tests to a single
  148. OptimisingTestSuite. You could add everything to a single OptimisingTestSuite,
  149. getting global optimisation or you could use several smaller
  150. OptimisingTestSuites.
  151. testresources.TestLoader
  152. ------------------------
  153. This is a trivial TestLoader that creates OptimisingTestSuites by default.
  154. unittest.TestResult
  155. -------------------
  156. testresources will log activity about resource creation and destruction to the
  157. result object tests are run with. 6 extension methods are looked for:
  158. ``startCleanResource``, ``stopCleanResource``, ``startMakeResource``,
  159. ``stopMakeResource``, ``startResetResource`` and finally ``stopResetResource``.
  160. ``testresources.tests.ResultWithResourceExtensions`` is
  161. an example of a ``TestResult`` with these methods present.
  162. Controlling Resource Reuse
  163. ==========================
  164. When or how do I mark the resource dirtied?
  165. The simplest approach is to have ``TestResourceManager.make`` call ``self.dirtied``:
  166. the resource is always immediately dirty and will never be reused without first
  167. being reset. This is appropriate when the underlying resource is cheap to
  168. reset or recreate, or when it's hard to detect whether it's been dirtied or to
  169. trap operations that change it.
  170. Alternatively, override ``TestResourceManager.isDirty`` and inspect the resource to
  171. see if it is safe to reuse.
  172. Finally, you can arrange for the returned resource to always call back to
  173. ``TestResourceManager.dirtied`` on the first operation that mutates it.
  174. FAQ
  175. ===
  176. * Can I dynamically request resources inside a test method?
  177. Generally, no, you shouldn't do this. The idea is that the resources are
  178. declared statically, so that testresources can "smooth" resource usage across
  179. several tests.
  180. But, you may be able to find some object that is statically declared and reusable
  181. to act as the resource, which can then provide methods to generate sub-elements
  182. of itself during a test.
  183. * If the resource is held inside the TestResourceManager object, and the
  184. TestResourceManager is typically constructed inline in the test case
  185. ``resources`` attribute, how can they be shared across different test
  186. classes?
  187. Good question.
  188. I guess you should arrange for a single instance to be held in an appropriate
  189. module scope, then referenced by the test classes that want to share it.
  190. Releasing
  191. =========
  192. 1. Add a section to NEWS (after In Development).
  193. 2. git tag -s
  194. 3. python setup.py sdist bdist_wheel upload -s