util.py 13 KB

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