Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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

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