You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

util.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. # -*- test-case-name: twisted.trial.test.test_util -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. #
  5. """
  6. A collection of utility functions and classes, used internally by Trial.
  7. This code is for Trial's internal use. Do NOT use this code if you are writing
  8. tests. It is subject to change at the Trial maintainer's whim. There is
  9. nothing here in this module for you to use unless you are maintaining Trial.
  10. Any non-Trial Twisted code that uses this module will be shot.
  11. Maintainer: Jonathan Lange
  12. @var DEFAULT_TIMEOUT_DURATION: The default timeout which will be applied to
  13. asynchronous (ie, Deferred-returning) test methods, in seconds.
  14. """
  15. from __future__ import division, absolute_import, print_function
  16. from random import randrange
  17. from twisted.internet import defer, utils, interfaces
  18. from twisted.python.failure import Failure
  19. from twisted.python.filepath import FilePath
  20. from twisted.python.lockfile import FilesystemLock
  21. __all__ = [
  22. 'DEFAULT_TIMEOUT_DURATION',
  23. 'excInfoOrFailureToExcInfo', 'suppress', 'acquireAttribute']
  24. DEFAULT_TIMEOUT = object()
  25. DEFAULT_TIMEOUT_DURATION = 120.0
  26. class DirtyReactorAggregateError(Exception):
  27. """
  28. Passed to L{twisted.trial.itrial.IReporter.addError} when the reactor is
  29. left in an unclean state after a test.
  30. @ivar delayedCalls: The L{DelayedCall<twisted.internet.base.DelayedCall>}
  31. objects which weren't cleaned up.
  32. @ivar selectables: The selectables which weren't cleaned up.
  33. """
  34. def __init__(self, delayedCalls, selectables=None):
  35. self.delayedCalls = delayedCalls
  36. self.selectables = selectables
  37. def __str__(self):
  38. """
  39. Return a multi-line message describing all of the unclean state.
  40. """
  41. msg = "Reactor was unclean."
  42. if self.delayedCalls:
  43. msg += ("\nDelayedCalls: (set "
  44. "twisted.internet.base.DelayedCall.debug = True to "
  45. "debug)\n")
  46. msg += "\n".join(map(str, self.delayedCalls))
  47. if self.selectables:
  48. msg += "\nSelectables:\n"
  49. msg += "\n".join(map(str, self.selectables))
  50. return msg
  51. class _Janitor(object):
  52. """
  53. The guy that cleans up after you.
  54. @ivar test: The L{TestCase} to report errors about.
  55. @ivar result: The L{IReporter} to report errors to.
  56. @ivar reactor: The reactor to use. If None, the global reactor
  57. will be used.
  58. """
  59. def __init__(self, test, result, reactor=None):
  60. """
  61. @param test: See L{_Janitor.test}.
  62. @param result: See L{_Janitor.result}.
  63. @param reactor: See L{_Janitor.reactor}.
  64. """
  65. self.test = test
  66. self.result = result
  67. self.reactor = reactor
  68. def postCaseCleanup(self):
  69. """
  70. Called by L{unittest.TestCase} after a test to catch any logged errors
  71. or pending L{DelayedCall<twisted.internet.base.DelayedCall>}s.
  72. """
  73. calls = self._cleanPending()
  74. if calls:
  75. aggregate = DirtyReactorAggregateError(calls)
  76. self.result.addError(self.test, Failure(aggregate))
  77. return False
  78. return True
  79. def postClassCleanup(self):
  80. """
  81. Called by L{unittest.TestCase} after the last test in a C{TestCase}
  82. subclass. Ensures the reactor is clean by murdering the threadpool,
  83. catching any pending
  84. L{DelayedCall<twisted.internet.base.DelayedCall>}s, open sockets etc.
  85. """
  86. selectables = self._cleanReactor()
  87. calls = self._cleanPending()
  88. if selectables or calls:
  89. aggregate = DirtyReactorAggregateError(calls, selectables)
  90. self.result.addError(self.test, Failure(aggregate))
  91. self._cleanThreads()
  92. def _getReactor(self):
  93. """
  94. Get either the passed-in reactor or the global reactor.
  95. """
  96. if self.reactor is not None:
  97. reactor = self.reactor
  98. else:
  99. from twisted.internet import reactor
  100. return reactor
  101. def _cleanPending(self):
  102. """
  103. Cancel all pending calls and return their string representations.
  104. """
  105. reactor = self._getReactor()
  106. # flush short-range timers
  107. reactor.iterate(0)
  108. reactor.iterate(0)
  109. delayedCallStrings = []
  110. for p in reactor.getDelayedCalls():
  111. if p.active():
  112. delayedString = str(p)
  113. p.cancel()
  114. else:
  115. print("WEIRDNESS! pending timed call not active!")
  116. delayedCallStrings.append(delayedString)
  117. return delayedCallStrings
  118. _cleanPending = utils.suppressWarnings(
  119. _cleanPending, (('ignore',), {'category': DeprecationWarning,
  120. 'message':
  121. r'reactor\.iterate cannot be used.*'}))
  122. def _cleanThreads(self):
  123. reactor = self._getReactor()
  124. if interfaces.IReactorThreads.providedBy(reactor):
  125. if reactor.threadpool is not None:
  126. # Stop the threadpool now so that a new one is created.
  127. # This improves test isolation somewhat (although this is a
  128. # post class cleanup hook, so it's only isolating classes
  129. # from each other, not methods from each other).
  130. reactor._stopThreadPool()
  131. def _cleanReactor(self):
  132. """
  133. Remove all selectables from the reactor, kill any of them that were
  134. processes, and return their string representation.
  135. """
  136. reactor = self._getReactor()
  137. selectableStrings = []
  138. for sel in reactor.removeAll():
  139. if interfaces.IProcessTransport.providedBy(sel):
  140. sel.signalProcess('KILL')
  141. selectableStrings.append(repr(sel))
  142. return selectableStrings
  143. _DEFAULT = object()
  144. def acquireAttribute(objects, attr, default=_DEFAULT):
  145. """
  146. Go through the list 'objects' sequentially until we find one which has
  147. attribute 'attr', then return the value of that attribute. If not found,
  148. return 'default' if set, otherwise, raise AttributeError.
  149. """
  150. for obj in objects:
  151. if hasattr(obj, attr):
  152. return getattr(obj, attr)
  153. if default is not _DEFAULT:
  154. return default
  155. raise AttributeError('attribute %r not found in %r' % (attr, objects))
  156. def excInfoOrFailureToExcInfo(err):
  157. """
  158. Coerce a Failure to an _exc_info, if err is a Failure.
  159. @param err: Either a tuple such as returned by L{sys.exc_info} or a
  160. L{Failure} object.
  161. @return: A tuple like the one returned by L{sys.exc_info}. e.g.
  162. C{exception_type, exception_object, traceback_object}.
  163. """
  164. if isinstance(err, Failure):
  165. # Unwrap the Failure into an exc_info tuple.
  166. err = (err.type, err.value, err.getTracebackObject())
  167. return err
  168. def suppress(action='ignore', **kwarg):
  169. """
  170. Sets up the .suppress tuple properly, pass options to this method as you
  171. would the stdlib warnings.filterwarnings()
  172. So, to use this with a .suppress magic attribute you would do the
  173. following:
  174. >>> from twisted.trial import unittest, util
  175. >>> import warnings
  176. >>>
  177. >>> class TestFoo(unittest.TestCase):
  178. ... def testFooBar(self):
  179. ... warnings.warn("i am deprecated", DeprecationWarning)
  180. ... testFooBar.suppress = [util.suppress(message='i am deprecated')]
  181. ...
  182. >>>
  183. Note that as with the todo and timeout attributes: the module level
  184. attribute acts as a default for the class attribute which acts as a default
  185. for the method attribute. The suppress attribute can be overridden at any
  186. level by specifying C{.suppress = []}
  187. """
  188. return ((action,), kwarg)
  189. # This should be deleted, and replaced with twisted.application's code; see
  190. # #6016:
  191. def profiled(f, outputFile):
  192. def _(*args, **kwargs):
  193. import profile
  194. prof = profile.Profile()
  195. try:
  196. result = prof.runcall(f, *args, **kwargs)
  197. prof.dump_stats(outputFile)
  198. except SystemExit:
  199. pass
  200. prof.print_stats()
  201. return result
  202. return _
  203. @defer.inlineCallbacks
  204. def _runSequentially(callables, stopOnFirstError=False):
  205. """
  206. Run the given callables one after the other. If a callable returns a
  207. Deferred, wait until it has finished before running the next callable.
  208. @param callables: An iterable of callables that take no parameters.
  209. @param stopOnFirstError: If True, then stop running callables as soon as
  210. one raises an exception or fires an errback. False by default.
  211. @return: A L{Deferred} that fires a list of C{(flag, value)} tuples. Each
  212. tuple will be either C{(SUCCESS, <return value>)} or C{(FAILURE,
  213. <Failure>)}.
  214. """
  215. results = []
  216. for f in callables:
  217. d = defer.maybeDeferred(f)
  218. try:
  219. thing = yield d
  220. results.append((defer.SUCCESS, thing))
  221. except Exception:
  222. results.append((defer.FAILURE, Failure()))
  223. if stopOnFirstError:
  224. break
  225. defer.returnValue(results)
  226. class _NoTrialMarker(Exception):
  227. """
  228. No trial marker file could be found.
  229. Raised when trial attempts to remove a trial temporary working directory
  230. that does not contain a marker file.
  231. """
  232. def _removeSafely(path):
  233. """
  234. Safely remove a path, recursively.
  235. If C{path} does not contain a node named C{_trial_marker}, a
  236. L{_NoTrialMarker} exception is raised and the path is not removed.
  237. """
  238. if not path.child(b'_trial_marker').exists():
  239. raise _NoTrialMarker(
  240. '%r is not a trial temporary path, refusing to remove it'
  241. % (path,))
  242. try:
  243. path.remove()
  244. except OSError as e:
  245. print ("could not remove %r, caught OSError [Errno %s]: %s"
  246. % (path, e.errno, e.strerror))
  247. try:
  248. newPath = FilePath(b'_trial_temp_old' +
  249. str(randrange(10000000)).encode("utf-8"))
  250. path.moveTo(newPath)
  251. except OSError as e:
  252. print ("could not rename path, caught OSError [Errno %s]: %s"
  253. % (e.errno,e.strerror))
  254. raise
  255. class _WorkingDirectoryBusy(Exception):
  256. """
  257. A working directory was specified to the runner, but another test run is
  258. currently using that directory.
  259. """
  260. def _unusedTestDirectory(base):
  261. """
  262. Find an unused directory named similarly to C{base}.
  263. Once a directory is found, it will be locked and a marker dropped into it
  264. to identify it as a trial temporary directory.
  265. @param base: A template path for the discovery process. If this path
  266. exactly cannot be used, a path which varies only in a suffix of the
  267. basename will be used instead.
  268. @type base: L{FilePath}
  269. @return: A two-tuple. The first element is a L{FilePath} representing the
  270. directory which was found and created. The second element is a locked
  271. L{FilesystemLock<twisted.python.lockfile.FilesystemLock>}. Another
  272. call to C{_unusedTestDirectory} will not be able to reused the
  273. same name until the lock is released, either explicitly or by this
  274. process exiting.
  275. """
  276. counter = 0
  277. while True:
  278. if counter:
  279. testdir = base.sibling('%s-%d' % (base.basename(), counter))
  280. else:
  281. testdir = base
  282. testDirLock = FilesystemLock(testdir.path + '.lock')
  283. if testDirLock.lock():
  284. # It is not in use
  285. if testdir.exists():
  286. # It exists though - delete it
  287. _removeSafely(testdir)
  288. # Create it anew and mark it as ours so the next _removeSafely on
  289. # it succeeds.
  290. testdir.makedirs()
  291. testdir.child(b'_trial_marker').setContent(b'')
  292. return testdir, testDirLock
  293. else:
  294. # It is in use
  295. if base.basename() == '_trial_temp':
  296. counter += 1
  297. else:
  298. raise _WorkingDirectoryBusy()
  299. def _listToPhrase(things, finalDelimiter, delimiter=', '):
  300. """
  301. Produce a string containing each thing in C{things},
  302. separated by a C{delimiter}, with the last couple being separated
  303. by C{finalDelimiter}
  304. @param things: The elements of the resulting phrase
  305. @type things: L{list} or L{tuple}
  306. @param finalDelimiter: What to put between the last two things
  307. (typically 'and' or 'or')
  308. @type finalDelimiter: L{str}
  309. @param delimiter: The separator to use between each thing,
  310. not including the last two. Should typically include a trailing space.
  311. @type delimiter: L{str}
  312. @return: The resulting phrase
  313. @rtype: L{str}
  314. """
  315. if not isinstance(things, (list, tuple)):
  316. raise TypeError("Things must be a list or a tuple")
  317. if not things:
  318. return ''
  319. if len(things) == 1:
  320. return str(things[0])
  321. if len(things) == 2:
  322. return "%s %s %s" % (str(things[0]), finalDelimiter, str(things[1]))
  323. else:
  324. strThings = []
  325. for thing in things:
  326. strThings.append(str(thing))
  327. return "%s%s%s %s" % (delimiter.join(strThings[:-1]),
  328. delimiter, finalDelimiter, strThings[-1])