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

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