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.

test_threads.py 13KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Test methods in twisted.internet.threads and reactor thread APIs.
  5. """
  6. import os
  7. import sys
  8. import time
  9. from unittest import skipIf
  10. from twisted.internet import defer, error, interfaces, protocol, reactor, threads
  11. from twisted.python import failure, log, threadable, threadpool
  12. from twisted.trial.unittest import TestCase
  13. try:
  14. import threading
  15. except ImportError:
  16. pass
  17. @skipIf(
  18. not interfaces.IReactorThreads(reactor, None),
  19. "No thread support, nothing to test here.",
  20. )
  21. class ReactorThreadsTests(TestCase):
  22. """
  23. Tests for the reactor threading API.
  24. """
  25. def test_suggestThreadPoolSize(self):
  26. """
  27. Try to change maximum number of threads.
  28. """
  29. reactor.suggestThreadPoolSize(34)
  30. self.assertEqual(reactor.threadpool.max, 34)
  31. reactor.suggestThreadPoolSize(4)
  32. self.assertEqual(reactor.threadpool.max, 4)
  33. def _waitForThread(self):
  34. """
  35. The reactor's threadpool is only available when the reactor is running,
  36. so to have a sane behavior during the tests we make a dummy
  37. L{threads.deferToThread} call.
  38. """
  39. return threads.deferToThread(time.sleep, 0)
  40. def test_callInThread(self):
  41. """
  42. Test callInThread functionality: set a C{threading.Event}, and check
  43. that it's not in the main thread.
  44. """
  45. def cb(ign):
  46. waiter = threading.Event()
  47. result = []
  48. def threadedFunc():
  49. result.append(threadable.isInIOThread())
  50. waiter.set()
  51. reactor.callInThread(threadedFunc)
  52. waiter.wait(120)
  53. if not waiter.isSet():
  54. self.fail("Timed out waiting for event.")
  55. else:
  56. self.assertEqual(result, [False])
  57. return self._waitForThread().addCallback(cb)
  58. def test_callFromThread(self):
  59. """
  60. Test callFromThread functionality: from the main thread, and from
  61. another thread.
  62. """
  63. def cb(ign):
  64. firedByReactorThread = defer.Deferred()
  65. firedByOtherThread = defer.Deferred()
  66. def threadedFunc():
  67. reactor.callFromThread(firedByOtherThread.callback, None)
  68. reactor.callInThread(threadedFunc)
  69. reactor.callFromThread(firedByReactorThread.callback, None)
  70. return defer.DeferredList(
  71. [firedByReactorThread, firedByOtherThread], fireOnOneErrback=True
  72. )
  73. return self._waitForThread().addCallback(cb)
  74. def test_wakerOverflow(self):
  75. """
  76. Try to make an overflow on the reactor waker using callFromThread.
  77. """
  78. def cb(ign):
  79. self.failure = None
  80. waiter = threading.Event()
  81. def threadedFunction():
  82. # Hopefully a hundred thousand queued calls is enough to
  83. # trigger the error condition
  84. for i in range(100000):
  85. try:
  86. reactor.callFromThread(lambda: None)
  87. except BaseException:
  88. self.failure = failure.Failure()
  89. break
  90. waiter.set()
  91. reactor.callInThread(threadedFunction)
  92. waiter.wait(120)
  93. if not waiter.isSet():
  94. self.fail("Timed out waiting for event")
  95. if self.failure is not None:
  96. return defer.fail(self.failure)
  97. return self._waitForThread().addCallback(cb)
  98. def _testBlockingCallFromThread(self, reactorFunc):
  99. """
  100. Utility method to test L{threads.blockingCallFromThread}.
  101. """
  102. waiter = threading.Event()
  103. results = []
  104. errors = []
  105. def cb1(ign):
  106. def threadedFunc():
  107. try:
  108. r = threads.blockingCallFromThread(reactor, reactorFunc)
  109. except Exception as e:
  110. errors.append(e)
  111. else:
  112. results.append(r)
  113. waiter.set()
  114. reactor.callInThread(threadedFunc)
  115. return threads.deferToThread(waiter.wait, self.getTimeout())
  116. def cb2(ign):
  117. if not waiter.isSet():
  118. self.fail("Timed out waiting for event")
  119. return results, errors
  120. return self._waitForThread().addCallback(cb1).addBoth(cb2)
  121. def test_blockingCallFromThread(self):
  122. """
  123. Test blockingCallFromThread facility: create a thread, call a function
  124. in the reactor using L{threads.blockingCallFromThread}, and verify the
  125. result returned.
  126. """
  127. def reactorFunc():
  128. return defer.succeed("foo")
  129. def cb(res):
  130. self.assertEqual(res[0][0], "foo")
  131. return self._testBlockingCallFromThread(reactorFunc).addCallback(cb)
  132. def test_asyncBlockingCallFromThread(self):
  133. """
  134. Test blockingCallFromThread as above, but be sure the resulting
  135. Deferred is not already fired.
  136. """
  137. def reactorFunc():
  138. d = defer.Deferred()
  139. reactor.callLater(0.1, d.callback, "egg")
  140. return d
  141. def cb(res):
  142. self.assertEqual(res[0][0], "egg")
  143. return self._testBlockingCallFromThread(reactorFunc).addCallback(cb)
  144. def test_errorBlockingCallFromThread(self):
  145. """
  146. Test error report for blockingCallFromThread.
  147. """
  148. def reactorFunc():
  149. return defer.fail(RuntimeError("bar"))
  150. def cb(res):
  151. self.assertIsInstance(res[1][0], RuntimeError)
  152. self.assertEqual(res[1][0].args[0], "bar")
  153. return self._testBlockingCallFromThread(reactorFunc).addCallback(cb)
  154. def test_asyncErrorBlockingCallFromThread(self):
  155. """
  156. Test error report for blockingCallFromThread as above, but be sure the
  157. resulting Deferred is not already fired.
  158. """
  159. def reactorFunc():
  160. d = defer.Deferred()
  161. reactor.callLater(0.1, d.errback, RuntimeError("spam"))
  162. return d
  163. def cb(res):
  164. self.assertIsInstance(res[1][0], RuntimeError)
  165. self.assertEqual(res[1][0].args[0], "spam")
  166. return self._testBlockingCallFromThread(reactorFunc).addCallback(cb)
  167. class Counter:
  168. index = 0
  169. problem = 0
  170. def add(self):
  171. """A non thread-safe method."""
  172. next = self.index + 1
  173. # another thread could jump in here and increment self.index on us
  174. if next != self.index + 1:
  175. self.problem = 1
  176. raise ValueError
  177. # or here, same issue but we wouldn't catch it. We'd overwrite
  178. # their results, and the index will have lost a count. If
  179. # several threads get in here, we will actually make the count
  180. # go backwards when we overwrite it.
  181. self.index = next
  182. @skipIf(
  183. not interfaces.IReactorThreads(reactor, None),
  184. "No thread support, nothing to test here.",
  185. )
  186. class DeferredResultTests(TestCase):
  187. """
  188. Test twisted.internet.threads.
  189. """
  190. def setUp(self):
  191. reactor.suggestThreadPoolSize(8)
  192. def tearDown(self):
  193. reactor.suggestThreadPoolSize(0)
  194. def test_callMultiple(self):
  195. """
  196. L{threads.callMultipleInThread} calls multiple functions in a thread.
  197. """
  198. L = []
  199. N = 10
  200. d = defer.Deferred()
  201. def finished():
  202. self.assertEqual(L, list(range(N)))
  203. d.callback(None)
  204. threads.callMultipleInThread(
  205. [(L.append, (i,), {}) for i in range(N)]
  206. + [(reactor.callFromThread, (finished,), {})]
  207. )
  208. return d
  209. def test_deferredResult(self):
  210. """
  211. L{threads.deferToThread} executes the function passed, and correctly
  212. handles the positional and keyword arguments given.
  213. """
  214. d = threads.deferToThread(lambda x, y=5: x + y, 3, y=4)
  215. d.addCallback(self.assertEqual, 7)
  216. return d
  217. def test_deferredFailure(self):
  218. """
  219. Check that L{threads.deferToThread} return a failure object
  220. with an appropriate exception instance when the called
  221. function raises an exception.
  222. """
  223. class NewError(Exception):
  224. pass
  225. def raiseError():
  226. raise NewError()
  227. d = threads.deferToThread(raiseError)
  228. return self.assertFailure(d, NewError)
  229. def test_deferredFailureAfterSuccess(self):
  230. """
  231. Check that a successful L{threads.deferToThread} followed by a one
  232. that raises an exception correctly result as a failure.
  233. """
  234. # set up a condition that causes cReactor to hang. These conditions
  235. # can also be set by other tests when the full test suite is run in
  236. # alphabetical order (test_flow.FlowTest.testThreaded followed by
  237. # test_internet.ReactorCoreTestCase.testStop, to be precise). By
  238. # setting them up explicitly here, we can reproduce the hang in a
  239. # single precise test case instead of depending upon side effects of
  240. # other tests.
  241. #
  242. # alas, this test appears to flunk the default reactor too
  243. d = threads.deferToThread(lambda: None)
  244. d.addCallback(lambda ign: threads.deferToThread(lambda: 1 // 0))
  245. return self.assertFailure(d, ZeroDivisionError)
  246. class DeferToThreadPoolTests(TestCase):
  247. """
  248. Test L{twisted.internet.threads.deferToThreadPool}.
  249. """
  250. def setUp(self):
  251. self.tp = threadpool.ThreadPool(0, 8)
  252. self.tp.start()
  253. def tearDown(self):
  254. self.tp.stop()
  255. def test_deferredResult(self):
  256. """
  257. L{threads.deferToThreadPool} executes the function passed, and
  258. correctly handles the positional and keyword arguments given.
  259. """
  260. d = threads.deferToThreadPool(reactor, self.tp, lambda x, y=5: x + y, 3, y=4)
  261. d.addCallback(self.assertEqual, 7)
  262. return d
  263. def test_deferredFailure(self):
  264. """
  265. Check that L{threads.deferToThreadPool} return a failure object with an
  266. appropriate exception instance when the called function raises an
  267. exception.
  268. """
  269. class NewError(Exception):
  270. pass
  271. def raiseError():
  272. raise NewError()
  273. d = threads.deferToThreadPool(reactor, self.tp, raiseError)
  274. return self.assertFailure(d, NewError)
  275. _callBeforeStartupProgram = """
  276. import time
  277. import %(reactor)s
  278. %(reactor)s.install()
  279. from twisted.internet import reactor
  280. def threadedCall():
  281. print('threaded call')
  282. reactor.callInThread(threadedCall)
  283. # Spin very briefly to try to give the thread a chance to run, if it
  284. # is going to. Is there a better way to achieve this behavior?
  285. for i in range(100):
  286. time.sleep(0.0)
  287. """
  288. class ThreadStartupProcessProtocol(protocol.ProcessProtocol):
  289. def __init__(self, finished):
  290. self.finished = finished
  291. self.out = []
  292. self.err = []
  293. def outReceived(self, out):
  294. self.out.append(out)
  295. def errReceived(self, err):
  296. self.err.append(err)
  297. def processEnded(self, reason):
  298. self.finished.callback((self.out, self.err, reason))
  299. @skipIf(
  300. not interfaces.IReactorThreads(reactor, None),
  301. "No thread support, nothing to test here.",
  302. )
  303. @skipIf(
  304. not interfaces.IReactorProcess(reactor, None),
  305. "No process support, cannot run subprocess thread tests.",
  306. )
  307. class StartupBehaviorTests(TestCase):
  308. """
  309. Test cases for the behavior of the reactor threadpool near startup
  310. boundary conditions.
  311. In particular, this asserts that no threaded calls are attempted
  312. until the reactor starts up, that calls attempted before it starts
  313. are in fact executed once it has started, and that in both cases,
  314. the reactor properly cleans itself up (which is tested for
  315. somewhat implicitly, by requiring a child process be able to exit,
  316. something it cannot do unless the threadpool has been properly
  317. torn down).
  318. """
  319. def testCallBeforeStartupUnexecuted(self):
  320. progname = self.mktemp()
  321. with open(progname, "w") as progfile:
  322. progfile.write(_callBeforeStartupProgram % {"reactor": reactor.__module__})
  323. def programFinished(result):
  324. (out, err, reason) = result
  325. if reason.check(error.ProcessTerminated):
  326. self.fail(f"Process did not exit cleanly (out: {out} err: {err})")
  327. if err:
  328. log.msg(f"Unexpected output on standard error: {err}")
  329. self.assertFalse(out, f"Expected no output, instead received:\n{out}")
  330. def programTimeout(err):
  331. err.trap(error.TimeoutError)
  332. proto.signalProcess("KILL")
  333. return err
  334. env = os.environ.copy()
  335. env["PYTHONPATH"] = os.pathsep.join(sys.path)
  336. d = defer.Deferred().addCallbacks(programFinished, programTimeout)
  337. proto = ThreadStartupProcessProtocol(d)
  338. reactor.spawnProcess(proto, sys.executable, ("python", progname), env)
  339. return d