__init__.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  1. # testresources: extensions to python unittest to allow declaritive use
  2. # of resources by test cases.
  3. #
  4. # Copyright (c) 2005-2010 Testresources Contributors
  5. #
  6. # Licensed under either the Apache License, Version 2.0 or the BSD 3-clause
  7. # license at the users choice. A copy of both licenses are available in the
  8. # project source as Apache-2.0 and BSD. You may not use this file except in
  9. # compliance with one of these two licences.
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under these licenses is distributed on an "AS IS" BASIS, WITHOUT
  13. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. # license you chose for the specific language governing permissions and
  15. # limitations under that license.
  16. #
  17. """TestResources: declarative management of external resources for tests."""
  18. import heapq
  19. import inspect
  20. import unittest
  21. try:
  22. import unittest2
  23. except ImportError:
  24. unittest2 = None
  25. # same format as sys.version_info: "A tuple containing the five components of
  26. # the version number: major, minor, micro, releaselevel, and serial. All
  27. # values except releaselevel are integers; the release level is 'alpha',
  28. # 'beta', 'candidate', or 'final'. The version_info value corresponding to the
  29. # Python version 2.0 is (2, 0, 0, 'final', 0)." Additionally we use a
  30. # releaselevel of 'dev' for unreleased under-development code.
  31. #
  32. # If the releaselevel is 'alpha' then the major/minor/micro components are not
  33. # established at this point, and setup.py will use a version of next-$(revno).
  34. # If the releaselevel is 'final', then the tarball will be major.minor.micro.
  35. # Otherwise it is major.minor.micro~$(revno).
  36. from pbr.version import VersionInfo
  37. _version = VersionInfo('testresources')
  38. __version__ = _version.semantic_version().version_tuple()
  39. version = _version.release_string()
  40. def test_suite():
  41. import testresources.tests
  42. return testresources.tests.test_suite()
  43. def _digraph_to_graph(digraph, prime_node_mapping):
  44. """Convert digraph to a graph.
  45. :param digraph: A directed graph in the form
  46. {from:{to:value}}.
  47. :param prime_node_mapping: A mapping from every
  48. node in digraph to a new unique and not in digraph node.
  49. :return: A symmetric graph in the form {from:to:value}} created by
  50. creating edges in the result between every N to M-prime with the
  51. original N-M value and from every N to N-prime with a cost of 0.
  52. No other edges are created.
  53. """
  54. result = {}
  55. for from_node, from_prime_node in prime_node_mapping.items():
  56. result[from_node] = {from_prime_node: 0}
  57. result[from_prime_node] = {from_node: 0}
  58. for from_node, to_nodes in digraph.items():
  59. from_prime = prime_node_mapping[from_node]
  60. for to_node, value in to_nodes.items():
  61. to_prime = prime_node_mapping[to_node]
  62. result[from_prime][to_node] = value
  63. result[to_node][from_prime] = value
  64. return result
  65. def _kruskals_graph_MST(graph):
  66. """Find the minimal spanning tree in graph using Kruskals algorithm.
  67. See http://en.wikipedia.org/wiki/Kruskal%27s_algorithm.
  68. :param graph: A graph in {from:{to:value}} form. Every node present in
  69. graph must be in the outer dict (because graph is not a directed graph.
  70. :return: A graph with all nodes and those vertices that are part of the MST
  71. for graph. If graph is not connected, then the result will also be a
  72. forest.
  73. """
  74. # forest contains all the nodes -> graph that node is in.
  75. forest = {}
  76. # graphs is the count of graphs we have yet to combine.
  77. for node in graph:
  78. forest[node] = {node: {}}
  79. graphs = len(forest)
  80. # collect edges: every edge is present twice (due to the graph
  81. # representation), so normalise.
  82. edges = set()
  83. for from_node, to_nodes in graph.items():
  84. for to_node, value in to_nodes.items():
  85. edge = (value,) + tuple(sorted([from_node, to_node]))
  86. edges.add(edge)
  87. edges = list(edges)
  88. heapq.heapify(edges)
  89. while edges and graphs > 1:
  90. # more edges to go and we haven't gotten a spanning tree yet.
  91. edge = heapq.heappop(edges)
  92. g1 = forest[edge[1]]
  93. g2 = forest[edge[2]]
  94. if g1 is g2:
  95. continue # already joined
  96. # combine g1 and g2 into g1
  97. graphs -= 1
  98. for from_node, to_nodes in g2.items():
  99. #remember its symmetric, don't need to do 'to'.
  100. forest[from_node] = g1
  101. g1.setdefault(from_node, {}).update(to_nodes)
  102. # add edge
  103. g1[edge[1]][edge[2]] = edge[0]
  104. g1[edge[2]][edge[1]] = edge[0]
  105. # union the remaining graphs
  106. _, result = forest.popitem()
  107. for _, g2 in forest.items():
  108. if g2 is result: # common case
  109. continue
  110. for from_node, to_nodes in g2.items():
  111. result.setdefault(from_node, {}).update(to_nodes)
  112. return result
  113. def _resource_graph(resource_sets):
  114. """Convert an iterable of resource_sets into a graph.
  115. Each resource_set in the iterable is treated as a node, and each resource
  116. in that resource_set is used as an edge to other nodes.
  117. """
  118. nodes = {}
  119. edges = {}
  120. for resource_set in resource_sets:
  121. # put node in nodes
  122. node = frozenset(resource_set)
  123. nodes[node] = set()
  124. # put its contents in as edges
  125. for resource in resource_set:
  126. edges.setdefault(resource, []).append(node)
  127. # populate the adjacent members of nodes
  128. for node, connected in nodes.items():
  129. for resource in node:
  130. connected.update(edges[resource])
  131. connected.discard(node)
  132. return nodes
  133. def split_by_resources(tests):
  134. """Split a list of tests by the resources that the tests use.
  135. :return: a dictionary mapping sets of resources to lists of tests
  136. using that combination of resources. The dictionary always
  137. contains an entry for "no resources".
  138. """
  139. no_resources = frozenset()
  140. resource_set_tests = {no_resources: []}
  141. for test in tests:
  142. resources = getattr(test, "resources", ())
  143. all_resources = list(resource.neededResources()
  144. for _, resource in resources)
  145. resource_set = set()
  146. for resource_list in all_resources:
  147. resource_set.update(resource_list)
  148. resource_set_tests.setdefault(frozenset(resource_set), []).append(test)
  149. return resource_set_tests
  150. def _strongly_connected_components(graph, no_resources):
  151. """Find the strongly connected components in graph.
  152. This is essentially a nonrecursive flatterning of Tarjan's method. It
  153. may be worth profiling against an actual Tarjan's implementation at some
  154. point, but sets are often faster than python calls.
  155. graph gets consumed, but that could be changed easily enough.
  156. """
  157. partitions = []
  158. while graph:
  159. node, pending = graph.popitem()
  160. current_partition = set([node])
  161. while pending:
  162. # add all the nodes connected to a connected node to pending.
  163. node = pending.pop()
  164. current_partition.add(node)
  165. pending.update(graph.pop(node, []))
  166. # don't try to process things we've allready processed.
  167. pending.difference_update(current_partition)
  168. partitions.append(current_partition)
  169. return partitions
  170. class OptimisingTestSuite(unittest.TestSuite):
  171. """A resource creation optimising TestSuite."""
  172. known_suite_classes = None
  173. def adsorbSuite(self, test_case_or_suite):
  174. """Deprecated. Use addTest instead."""
  175. self.addTest(test_case_or_suite)
  176. def addTest(self, test_case_or_suite):
  177. """Add `test_case_or_suite`, unwrapping standard TestSuites.
  178. This means that any containing unittest.TestSuites will be removed,
  179. while any custom test suites will be 'distributed' across their
  180. members. Thus addTest(CustomSuite([a, b])) will result in
  181. CustomSuite([a]) and CustomSuite([b]) being added to this suite.
  182. """
  183. try:
  184. tests = iter(test_case_or_suite)
  185. except TypeError:
  186. unittest.TestSuite.addTest(self, test_case_or_suite)
  187. return
  188. if test_case_or_suite.__class__ in self.__class__.known_suite_classes:
  189. for test in tests:
  190. self.adsorbSuite(test)
  191. else:
  192. for test in tests:
  193. unittest.TestSuite.addTest(
  194. self, test_case_or_suite.__class__([test]))
  195. def cost_of_switching(self, old_resource_set, new_resource_set):
  196. """Cost of switching from 'old_resource_set' to 'new_resource_set'.
  197. This is calculated by adding the cost of tearing down unnecessary
  198. resources to the cost of setting up the newly-needed resources.
  199. Note that resources which are always dirtied may skew the predicted
  200. skew the cost of switching because they are considered common, even
  201. when reusing them may actually be equivalent to a teardown+setup
  202. operation.
  203. """
  204. new_resources = new_resource_set - old_resource_set
  205. gone_resources = old_resource_set - new_resource_set
  206. return (sum(resource.setUpCost for resource in new_resources) +
  207. sum(resource.tearDownCost for resource in gone_resources))
  208. def switch(self, old_resource_set, new_resource_set, result):
  209. """Switch from 'old_resource_set' to 'new_resource_set'.
  210. Tear down resources in old_resource_set that aren't in
  211. new_resource_set and set up resources that are in new_resource_set but
  212. not in old_resource_set.
  213. :param result: TestResult object to report activity on.
  214. """
  215. new_resources = new_resource_set - old_resource_set
  216. old_resources = old_resource_set - new_resource_set
  217. for resource in old_resources:
  218. resource.finishedWith(resource._currentResource, result)
  219. for resource in new_resources:
  220. resource.getResource(result)
  221. def run(self, result):
  222. self.sortTests()
  223. current_resources = set()
  224. for test in self._tests:
  225. if result.shouldStop:
  226. break
  227. resources = getattr(test, 'resources', [])
  228. new_resources = set()
  229. for name, resource in resources:
  230. new_resources.update(resource.neededResources())
  231. self.switch(current_resources, new_resources, result)
  232. current_resources = new_resources
  233. test(result)
  234. self.switch(current_resources, set(), result)
  235. return result
  236. def sortTests(self):
  237. """Attempt to topographically sort the contained tests.
  238. This function biases to reusing a resource: it assumes that resetting
  239. a resource is usually cheaper than a teardown + setup; and that most
  240. resources are not dirtied by most tests.
  241. Feel free to override to improve the sort behaviour.
  242. """
  243. # We group the tests by the resource combinations they use,
  244. # since there will usually be fewer resource combinations than
  245. # actual tests and there can never be more: This gives us 'nodes' or
  246. # 'resource_sets' that represent many tests using the same set of
  247. # resources.
  248. resource_set_tests = split_by_resources(self._tests)
  249. # Partition into separate sets of resources, there is no ordering
  250. # preference between sets that do not share members. Rationale:
  251. # If resource_set A and B have no common resources, AB and BA are
  252. # equally good - the global setup/teardown sums are identical. Secondly
  253. # if A shares one or more resources with C, then pairing AC|CA is
  254. # better than having B between A and C, because the shared resources
  255. # can be reset or reused. Having partitioned we can use connected graph
  256. # logic on each partition.
  257. resource_set_graph = _resource_graph(resource_set_tests)
  258. no_resources = frozenset()
  259. # A list of resource_set_tests, all fully internally connected.
  260. partitions = _strongly_connected_components(resource_set_graph,
  261. no_resources)
  262. result = []
  263. for partition in partitions:
  264. # we process these at the end for no particularly good reason (it
  265. # makes testing slightly easier).
  266. if partition == [no_resources]:
  267. continue
  268. order = self._makeOrder(partition)
  269. # Spit this partition out into result
  270. for resource_set in order:
  271. result.extend(resource_set_tests[resource_set])
  272. result.extend(resource_set_tests[no_resources])
  273. self._tests = result
  274. def _getGraph(self, resource_sets):
  275. """Build a graph of the resource-using nodes.
  276. This special cases set(['root']) to be a node with no resources and
  277. edges to everything.
  278. :return: A complete directed graph of the switching costs
  279. between each resource combination. Note that links from N to N are
  280. not included.
  281. """
  282. no_resources = frozenset()
  283. graph = {}
  284. root = set(['root'])
  285. # bottom = set(['bottom'])
  286. for from_set in resource_sets:
  287. graph[from_set] = {}
  288. if from_set == root:
  289. from_resources = no_resources
  290. #elif from_set == bottom:
  291. # continue # no links from bottom
  292. else:
  293. from_resources = from_set
  294. for to_set in resource_sets:
  295. if from_set is to_set:
  296. continue # no self-edges
  297. #if to_set == bottom:
  298. # if from_set == root:
  299. # continue # no short cuts!
  300. # to_resources = no_resources
  301. #el
  302. if to_set == root:
  303. continue # no links to root
  304. else:
  305. to_resources = to_set
  306. graph[from_set][to_set] = self.cost_of_switching(
  307. from_resources, to_resources)
  308. return graph
  309. def _makeOrder(self, partition):
  310. """Return a order for the resource sets in partition."""
  311. # This problem is NP-C - find the lowest cost hamiltonian path. It
  312. # also meets the triangle inequality, so we can use an approximation.
  313. # TODO: implement Christofides.
  314. # See:
  315. # http://en.wikipedia.org/wiki/Travelling_salesman_problem#Metric_TSP
  316. # We need a root
  317. root = frozenset(['root'])
  318. partition.add(root)
  319. # and an end
  320. # partition.add(frozenset(['bottom']))
  321. # get rid of 'noresources'
  322. partition.discard(frozenset())
  323. digraph = self._getGraph(partition)
  324. # build a prime map
  325. primes = {}
  326. prime = frozenset(['prime'])
  327. for node in digraph:
  328. primes[node] = node.union(prime)
  329. graph = _digraph_to_graph(digraph, primes)
  330. mst = _kruskals_graph_MST(graph)
  331. # Because the representation is a digraph, we can build an Eulerian
  332. # cycle directly from the representation by just following the links:
  333. # a node with only 1 'edge' has two directed edges; and we can only
  334. # enter and leave it once, so the edge lookups will match precisely.
  335. # As the mst is a spanning tree, the graph will become disconnected
  336. # (we choose non-disconnecting edges first)
  337. # - for a stub node (1 outgoing link): when exiting it unless it is
  338. # the first node started at
  339. # - for a non-stub node if choosing an outgoing link where some other
  340. # endpoints incoming link has not been traversed. [exit by a
  341. # different node than entering, until all exits taken].
  342. # We don't need the mst after, so it gets modified in place.
  343. node = root
  344. cycle = [node]
  345. steps = 2 * (len(mst) - 1)
  346. for step in range(steps):
  347. found = False
  348. outgoing = None # For clearer debugging.
  349. for outgoing in mst[node]:
  350. if node in mst[outgoing]:
  351. # we have a return path: take it
  352. # print node, '->', outgoing, ' can return'
  353. del mst[node][outgoing]
  354. node = outgoing
  355. cycle.append(node)
  356. found = True
  357. break
  358. if not found:
  359. # none of the outgoing links have an incoming, so follow an
  360. # arbitrary one (the last examined outgoing)
  361. # print node, '->', outgoing
  362. del mst[node][outgoing]
  363. node = outgoing
  364. cycle.append(node)
  365. # Convert to a path:
  366. visited = set()
  367. order = []
  368. for node in cycle:
  369. if node in visited:
  370. continue
  371. if node in primes:
  372. order.append(node)
  373. visited.add(node)
  374. assert order[0] == root
  375. return order[1:]
  376. OptimisingTestSuite.known_suite_classes = (
  377. unittest.TestSuite, OptimisingTestSuite)
  378. if unittest2 is not None:
  379. OptimisingTestSuite.known_suite_classes += (unittest2.TestSuite,)
  380. class TestLoader(unittest.TestLoader):
  381. """Custom TestLoader to set the right TestSuite class."""
  382. suiteClass = OptimisingTestSuite
  383. class TestResourceManager(object):
  384. """A manager for resources that can be shared across tests.
  385. ResourceManagers can report activity to a TestResult. The methods
  386. - startCleanResource(resource)
  387. - stopCleanResource(resource)
  388. - startMakeResource(resource)
  389. - stopMakeResource(resource)
  390. will be looked for and if present invoked before and after cleaning or
  391. creation of resource objects takes place.
  392. :cvar resources: The same as the resources list on an instance, the default
  393. constructor will look for the class instance and copy it. This is a
  394. convenience to avoid needing to define __init__ solely to alter the
  395. dependencies list.
  396. :ivar resources: The resources that this resource needs. Calling
  397. neededResources will return the closure of this resource and its needed
  398. resources. The resources list is in the same format as resources on a
  399. test case - a list of tuples (attribute_name, resource).
  400. :ivar setUpCost: The relative cost to construct a resource of this type.
  401. One good approach is to set this to the number of seconds it normally
  402. takes to set up the resource.
  403. :ivar tearDownCost: The relative cost to tear down a resource of this
  404. type. One good approach is to set this to the number of seconds it
  405. normally takes to tear down the resource.
  406. """
  407. setUpCost = 1
  408. tearDownCost = 1
  409. def __init__(self):
  410. """Create a TestResourceManager object."""
  411. self._dirty = False
  412. self._uses = 0
  413. self._currentResource = None
  414. self.resources = list(getattr(self.__class__, "resources", []))
  415. def _call_result_method_if_exists(self, result, methodname, *args):
  416. """Call a method on a TestResult that may exist."""
  417. method = getattr(result, methodname, None)
  418. if callable(method):
  419. method(*args)
  420. def _clean_all(self, resource, result):
  421. """Clean the dependencies from resource, and then resource itself."""
  422. self._call_result_method_if_exists(result, "startCleanResource", self)
  423. self.clean(resource)
  424. for name, manager in self.resources:
  425. manager.finishedWith(getattr(resource, name))
  426. self._call_result_method_if_exists(result, "stopCleanResource", self)
  427. def clean(self, resource):
  428. """Override this to class method to hook into resource removal."""
  429. def dirtied(self, resource):
  430. """Mark the resource as having been 'dirtied'.
  431. A resource is dirty when it is no longer suitable for use by other
  432. tests.
  433. e.g. a shared database that has had rows changed.
  434. """
  435. self._dirty = True
  436. def finishedWith(self, resource, result=None):
  437. """Indicate that 'resource' has one less user.
  438. If there are no more registered users of 'resource' then we trigger
  439. the `clean` hook, which should do any resource-specific
  440. cleanup.
  441. :param resource: A resource returned by
  442. `TestResourceManager.getResource`.
  443. :param result: An optional TestResult to report resource changes to.
  444. """
  445. self._uses -= 1
  446. if self._uses == 0:
  447. self._clean_all(resource, result)
  448. self._setResource(None)
  449. def getResource(self, result=None):
  450. """Get the resource for this class and record that it's being used.
  451. The resource is constructed using the `make` hook.
  452. Once done with the resource, pass it to `finishedWith` to indicated
  453. that it is no longer needed.
  454. :param result: An optional TestResult to report resource changes to.
  455. """
  456. if self._uses == 0:
  457. self._setResource(self._make_all(result))
  458. elif self.isDirty():
  459. self._setResource(self.reset(self._currentResource, result))
  460. self._uses += 1
  461. return self._currentResource
  462. def isDirty(self):
  463. """Return True if this managers cached resource is dirty.
  464. Calling when the resource is not currently held has undefined
  465. behaviour.
  466. """
  467. if self._dirty:
  468. return True
  469. for name, mgr in self.resources:
  470. if mgr.isDirty():
  471. return True
  472. res = mgr.getResource()
  473. try:
  474. if res is not getattr(self._currentResource, name):
  475. return True
  476. finally:
  477. mgr.finishedWith(res)
  478. def _make_all(self, result):
  479. """Make the dependencies of this resource and this resource."""
  480. self._call_result_method_if_exists(result, "startMakeResource", self)
  481. dependency_resources = {}
  482. for name, resource in self.resources:
  483. dependency_resources[name] = resource.getResource()
  484. resource = self.make(dependency_resources)
  485. for name, value in dependency_resources.items():
  486. setattr(resource, name, value)
  487. self._call_result_method_if_exists(result, "stopMakeResource", self)
  488. return resource
  489. def make(self, dependency_resources):
  490. """Override this to construct resources.
  491. :param dependency_resources: A dict mapping name -> resource instance
  492. for the resources specified as dependencies.
  493. :return: The made resource.
  494. """
  495. raise NotImplementedError(
  496. "Override make to construct resources.")
  497. def neededResources(self):
  498. """Return the resources needed for this resource, including self.
  499. :return: A list of needed resources, in topological deepest-first
  500. order.
  501. """
  502. seen = set([self])
  503. result = []
  504. for name, resource in self.resources:
  505. for resource in resource.neededResources():
  506. if resource in seen:
  507. continue
  508. seen.add(resource)
  509. result.append(resource)
  510. result.append(self)
  511. return result
  512. def reset(self, old_resource, result=None):
  513. """Return a clean version of old_resource.
  514. By default, the resource will be cleaned then remade if it had
  515. previously been `dirtied` by the helper self._reset() - which is the
  516. extension point folk should override to customise reset behaviour.
  517. This function takes the dependent resource stack into consideration as
  518. _make_all and _clean_all do. The inconsistent naming is because reset
  519. is part of the public interface, but _make_all and _clean_all is not.
  520. Note that if a resource A holds a lock or other blocking thing on
  521. a dependency D, reset will result in this call sequence over a
  522. getResource(), dirty(), getResource(), finishedWith(), finishedWith()
  523. sequence:
  524. B.make(), A.make(), B.reset(), A.reset(), A.clean(), B.clean()
  525. Thus it is important that B.reset not assume that A has been cleaned or
  526. reset before B is reset: it should arrange to reference count, lazy
  527. cleanup or forcibly reset resource in some fashion.
  528. As an example, consider that B is a database with sample data, and
  529. A is an application server serving content from it. B._reset() should
  530. disconnect all database clients, reset the state of the database, and
  531. A._reset() should tell the application server to dump any internal
  532. caches it might have.
  533. In principle we might make a richer API to allow before-and-after
  534. reset actions, but so far that hasn't been needed.
  535. :return: The possibly new resource.
  536. :param result: An optional TestResult to report resource changes to.
  537. """
  538. # Core logic:
  539. # - if neither we nor any parent is dirty, do nothing.
  540. # otherwise
  541. # - emit a signal to the test result
  542. # - reset all dependencies all, getting new attributes.
  543. # - call self._reset(old_resource, dependency_attributes)
  544. # [the default implementation does a clean + make]
  545. if not self.isDirty():
  546. return old_resource
  547. self._call_result_method_if_exists(result, "startResetResource", self)
  548. dependency_resources = {}
  549. for name, mgr in self.resources:
  550. dependency_resources[name] = mgr.reset(
  551. getattr(old_resource, name), result)
  552. resource = self._reset(old_resource, dependency_resources)
  553. for name, value in dependency_resources.items():
  554. setattr(resource, name, value)
  555. self._call_result_method_if_exists(result, "stopResetResource", self)
  556. return resource
  557. def _reset(self, resource, dependency_resources):
  558. """Override this to reset resources other than via clean+make.
  559. This method should reset the self._dirty flag (assuming the manager can
  560. ever be clean) and return either the old resource cleaned or a fresh
  561. one.
  562. :param resource: The resource to reset.
  563. :param dependency_resources: A dict mapping name -> resource instance
  564. for the resources specified as dependencies.
  565. """
  566. self.clean(resource)
  567. return self.make(dependency_resources)
  568. def _setResource(self, new_resource):
  569. """Set the current resource to a new value."""
  570. self._currentResource = new_resource
  571. self._dirty = False
  572. TestResource = TestResourceManager
  573. class GenericResource(TestResourceManager):
  574. """A TestResourceManager that decorates an external helper of some kind.
  575. GenericResource can be used to adapt an external resource so that
  576. testresources can use it. By default the setUp and tearDown methods are
  577. called when making and cleaning the resource, and the resource is
  578. considered permanently dirty, so it is torn down and brought up again
  579. between every use.
  580. The constructor method is called with the dependency resources dict::
  581. resource_factory(**dependency_resources)
  582. This permits naming those resources to match the contract of the setUp
  583. method.
  584. """
  585. def __init__(self, resource_factory, setup_method_name='setUp',
  586. teardown_method_name='tearDown'):
  587. """Create a GenericResource
  588. :param resource_factory: A factory to create a new resource.
  589. :param setup_method_name: Optional method name to call to setup the
  590. resource. Defaults to 'setUp'.
  591. :param teardown_method_name: Optional method name to call to tear down
  592. the resource. Defaults to 'tearDown'.
  593. """
  594. super(GenericResource, self).__init__()
  595. self.resource_factory = resource_factory
  596. self.setup_method_name = setup_method_name
  597. self.teardown_method_name = teardown_method_name
  598. def clean(self, resource):
  599. getattr(resource, self.teardown_method_name)()
  600. def make(self, dependency_resources):
  601. result = self.resource_factory(**dependency_resources)
  602. getattr(result, self.setup_method_name)()
  603. return result
  604. def isDirty(self):
  605. return True
  606. class FixtureResource(TestResourceManager):
  607. """A TestResourceManager that decorates a ``fixtures.Fixture``.
  608. The fixture has its setUp and cleanUp called as expected, and
  609. reset is called between uses.
  610. Due to the API of fixtures, dependency_resources are not
  611. accessible to the wrapped fixture. However, if you are using
  612. resource optimisation, you should wrap any dependencies in a
  613. FixtureResource and set the resources attribute appropriately.
  614. Note that when this is done, testresources will take care of
  615. calling setUp and cleanUp on the dependency fixtures and so
  616. the fixtures should not implicitly setUp or cleanUp their
  617. dependencies (that have been mapped).
  618. See the ``fixtures`` documentation for information on managing
  619. dependencies within the ``fixtures`` API.
  620. :ivar fixture: The wrapped fixture.
  621. """
  622. def __init__(self, fixture):
  623. """Create a FixtureResource
  624. :param fixture: The fixture to wrap.
  625. """
  626. super(FixtureResource, self).__init__()
  627. self.fixture = fixture
  628. def clean(self, resource):
  629. resource.cleanUp()
  630. def make(self, dependency_resources):
  631. self.fixture.setUp()
  632. return self.fixture
  633. def _reset(self, resource, dependency_resources):
  634. self.fixture.reset()
  635. return self.fixture
  636. def isDirty(self):
  637. return True
  638. _dirty = property(lambda _:True, lambda _, _1:None)
  639. class ResourcedTestCase(unittest.TestCase):
  640. """A TestCase parent or utility that enables cross-test resource usage.
  641. ResourcedTestCase is a thin wrapper around the
  642. testresources.setUpResources and testresources.tearDownResources helper
  643. functions. It should be trivially reimplemented where a different base
  644. class is neded, or you can use multiple inheritance and call into
  645. ResourcedTestCase.setUpResources and ResourcedTestCase.tearDownResources
  646. from your setUp and tearDown (or whatever cleanup idiom is used).
  647. :ivar resources: A list of (name, resource) pairs, where 'resource' is a
  648. subclass of `TestResourceManager` and 'name' is the name of the
  649. attribute that the resource should be stored on.
  650. """
  651. resources = []
  652. def setUp(self):
  653. super(ResourcedTestCase, self).setUp()
  654. self.setUpResources()
  655. def setUpResources(self):
  656. setUpResources(self, self.resources, _get_result())
  657. def tearDown(self):
  658. self.tearDownResources()
  659. super(ResourcedTestCase, self).tearDown()
  660. def tearDownResources(self):
  661. tearDownResources(self, self.resources, _get_result())
  662. def setUpResources(test, resources, result):
  663. """Set up resources for test.
  664. :param test: The test to setup resources for.
  665. :param resources: The resources to setup.
  666. :param result: A result object for tracing resource activity.
  667. """
  668. for resource in resources:
  669. setattr(test, resource[0], resource[1].getResource(result))
  670. def tearDownResources(test, resources, result):
  671. """Tear down resources for test.
  672. :param test: The test to tear down resources from.
  673. :param resources: The resources to tear down.
  674. :param result: A result object for tracing resource activity.
  675. """
  676. for resource in resources:
  677. resource[1].finishedWith(getattr(test, resource[0]), result)
  678. delattr(test, resource[0])
  679. def _get_result():
  680. """Find a TestResult in the stack.
  681. unittest hides the result. This forces us to look up the stack.
  682. The result is passed to a run() or a __call__ method 4 or more frames
  683. up: that method is what calls setUp and tearDown, and they call their
  684. parent setUp etc. Its not guaranteed that the parameter to run will
  685. be calls result as its not required to be a keyword parameter in
  686. TestCase. However, in practice, this works.
  687. """
  688. stack = inspect.stack()
  689. for frame in stack[2:]:
  690. if frame[3] in ('run', '__call__'):
  691. # Not all frames called 'run' will be unittest. It could be a
  692. # reactor in trial, for instance.
  693. result = frame[0].f_locals.get('result')
  694. if (result is not None and
  695. getattr(result, 'startTest', None) is not None):
  696. return result