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_task.py 47KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Tests for L{twisted.internet.task}.
  5. """
  6. from twisted.internet import defer, error, interfaces, reactor, task
  7. from twisted.internet.main import installReactor
  8. from twisted.internet.test.modulehelpers import NoReactor
  9. from twisted.trial import unittest
  10. # Be compatible with any jerks who used our private stuff
  11. Clock = task.Clock
  12. from twisted.python import failure
  13. class TestableLoopingCall(task.LoopingCall):
  14. def __init__(self, clock, *a, **kw):
  15. super().__init__(*a, **kw)
  16. self.clock = clock
  17. class TestException(Exception):
  18. pass
  19. class ClockTests(unittest.TestCase):
  20. """
  21. Test the non-wallclock based clock implementation.
  22. """
  23. def testSeconds(self):
  24. """
  25. Test that the C{seconds} method of the fake clock returns fake time.
  26. """
  27. c = task.Clock()
  28. self.assertEqual(c.seconds(), 0)
  29. def testCallLater(self):
  30. """
  31. Test that calls can be scheduled for later with the fake clock and
  32. hands back an L{IDelayedCall}.
  33. """
  34. c = task.Clock()
  35. call = c.callLater(1, lambda a, b: None, 1, b=2)
  36. self.assertTrue(interfaces.IDelayedCall.providedBy(call))
  37. self.assertEqual(call.getTime(), 1)
  38. self.assertTrue(call.active())
  39. def testCallLaterCancelled(self):
  40. """
  41. Test that calls can be cancelled.
  42. """
  43. c = task.Clock()
  44. call = c.callLater(1, lambda a, b: None, 1, b=2)
  45. call.cancel()
  46. self.assertFalse(call.active())
  47. def test_callLaterOrdering(self):
  48. """
  49. Test that the DelayedCall returned is not one previously
  50. created.
  51. """
  52. c = task.Clock()
  53. call1 = c.callLater(10, lambda a, b: None, 1, b=2)
  54. call2 = c.callLater(1, lambda a, b: None, 3, b=4)
  55. self.assertFalse(call1 is call2)
  56. def testAdvance(self):
  57. """
  58. Test that advancing the clock will fire some calls.
  59. """
  60. events = []
  61. c = task.Clock()
  62. call = c.callLater(2, lambda: events.append(None))
  63. c.advance(1)
  64. self.assertEqual(events, [])
  65. c.advance(1)
  66. self.assertEqual(events, [None])
  67. self.assertFalse(call.active())
  68. def testAdvanceCancel(self):
  69. """
  70. Test attempting to cancel the call in a callback.
  71. AlreadyCalled should be raised, not for example a ValueError from
  72. removing the call from Clock.calls. This requires call.called to be
  73. set before the callback is called.
  74. """
  75. c = task.Clock()
  76. def cb():
  77. self.assertRaises(error.AlreadyCalled, call.cancel)
  78. call = c.callLater(1, cb)
  79. c.advance(1)
  80. def testCallLaterDelayed(self):
  81. """
  82. Test that calls can be delayed.
  83. """
  84. events = []
  85. c = task.Clock()
  86. call = c.callLater(1, lambda a, b: events.append((a, b)), 1, b=2)
  87. call.delay(1)
  88. self.assertEqual(call.getTime(), 2)
  89. c.advance(1.5)
  90. self.assertEqual(events, [])
  91. c.advance(1.0)
  92. self.assertEqual(events, [(1, 2)])
  93. def testCallLaterResetLater(self):
  94. """
  95. Test that calls can have their time reset to a later time.
  96. """
  97. events = []
  98. c = task.Clock()
  99. call = c.callLater(2, lambda a, b: events.append((a, b)), 1, b=2)
  100. c.advance(1)
  101. call.reset(3)
  102. self.assertEqual(call.getTime(), 4)
  103. c.advance(2)
  104. self.assertEqual(events, [])
  105. c.advance(1)
  106. self.assertEqual(events, [(1, 2)])
  107. def testCallLaterResetSooner(self):
  108. """
  109. Test that calls can have their time reset to an earlier time.
  110. """
  111. events = []
  112. c = task.Clock()
  113. call = c.callLater(4, lambda a, b: events.append((a, b)), 1, b=2)
  114. call.reset(3)
  115. self.assertEqual(call.getTime(), 3)
  116. c.advance(3)
  117. self.assertEqual(events, [(1, 2)])
  118. def test_getDelayedCalls(self):
  119. """
  120. Test that we can get a list of all delayed calls
  121. """
  122. c = task.Clock()
  123. call = c.callLater(1, lambda x: None)
  124. call2 = c.callLater(2, lambda x: None)
  125. calls = c.getDelayedCalls()
  126. self.assertEqual({call, call2}, set(calls))
  127. def test_getDelayedCallsEmpty(self):
  128. """
  129. Test that we get an empty list from getDelayedCalls on a newly
  130. constructed Clock.
  131. """
  132. c = task.Clock()
  133. self.assertEqual(c.getDelayedCalls(), [])
  134. def test_providesIReactorTime(self):
  135. c = task.Clock()
  136. self.assertTrue(
  137. interfaces.IReactorTime.providedBy(c), "Clock does not provide IReactorTime"
  138. )
  139. def test_callLaterKeepsCallsOrdered(self):
  140. """
  141. The order of calls scheduled by L{task.Clock.callLater} is honored when
  142. adding a new call via calling L{task.Clock.callLater} again.
  143. For example, if L{task.Clock.callLater} is invoked with a callable "A"
  144. and a time t0, and then the L{IDelayedCall} which results from that is
  145. C{reset} to a later time t2 which is greater than t0, and I{then}
  146. L{task.Clock.callLater} is invoked again with a callable "B", and time
  147. t1 which is less than t2 but greater than t0, "B" will be invoked before
  148. "A".
  149. """
  150. result = []
  151. expected = [("b", 2.0), ("a", 3.0)]
  152. clock = task.Clock()
  153. logtime = lambda n: result.append((n, clock.seconds()))
  154. call_a = clock.callLater(1.0, logtime, "a")
  155. call_a.reset(3.0)
  156. clock.callLater(2.0, logtime, "b")
  157. clock.pump([1] * 3)
  158. self.assertEqual(result, expected)
  159. def test_callLaterResetKeepsCallsOrdered(self):
  160. """
  161. The order of calls scheduled by L{task.Clock.callLater} is honored when
  162. re-scheduling an existing call via L{IDelayedCall.reset} on the result
  163. of a previous call to C{callLater}.
  164. For example, if L{task.Clock.callLater} is invoked with a callable "A"
  165. and a time t0, and then L{task.Clock.callLater} is invoked again with a
  166. callable "B", and time t1 greater than t0, and finally the
  167. L{IDelayedCall} for "A" is C{reset} to a later time, t2, which is
  168. greater than t1, "B" will be invoked before "A".
  169. """
  170. result = []
  171. expected = [("b", 2.0), ("a", 3.0)]
  172. clock = task.Clock()
  173. logtime = lambda n: result.append((n, clock.seconds()))
  174. call_a = clock.callLater(1.0, logtime, "a")
  175. clock.callLater(2.0, logtime, "b")
  176. call_a.reset(3.0)
  177. clock.pump([1] * 3)
  178. self.assertEqual(result, expected)
  179. def test_callLaterResetInsideCallKeepsCallsOrdered(self):
  180. """
  181. The order of calls scheduled by L{task.Clock.callLater} is honored when
  182. re-scheduling an existing call via L{IDelayedCall.reset} on the result
  183. of a previous call to C{callLater}, even when that call to C{reset}
  184. occurs within the callable scheduled by C{callLater} itself.
  185. """
  186. result = []
  187. expected = [("c", 3.0), ("b", 4.0)]
  188. clock = task.Clock()
  189. logtime = lambda n: result.append((n, clock.seconds()))
  190. call_b = clock.callLater(2.0, logtime, "b")
  191. def a():
  192. call_b.reset(3.0)
  193. clock.callLater(1.0, a)
  194. clock.callLater(3.0, logtime, "c")
  195. clock.pump([0.5] * 10)
  196. self.assertEqual(result, expected)
  197. class LoopTests(unittest.TestCase):
  198. """
  199. Tests for L{task.LoopingCall} based on a fake L{IReactorTime}
  200. implementation.
  201. """
  202. def test_defaultClock(self):
  203. """
  204. L{LoopingCall}'s default clock should be the reactor.
  205. """
  206. call = task.LoopingCall(lambda: None)
  207. self.assertEqual(call.clock, reactor)
  208. def test_callbackTimeSkips(self):
  209. """
  210. When more time than the defined interval passes during the execution
  211. of a callback, L{LoopingCall} should schedule the next call for the
  212. next interval which is still in the future.
  213. """
  214. times = []
  215. callDuration = None
  216. clock = task.Clock()
  217. def aCallback():
  218. times.append(clock.seconds())
  219. clock.advance(callDuration)
  220. call = task.LoopingCall(aCallback)
  221. call.clock = clock
  222. # Start a LoopingCall with a 0.5 second increment, and immediately call
  223. # the callable.
  224. callDuration = 2
  225. call.start(0.5)
  226. # Verify that the callable was called, and since it was immediate, with
  227. # no skips.
  228. self.assertEqual(times, [0])
  229. # The callback should have advanced the clock by the callDuration.
  230. self.assertEqual(clock.seconds(), callDuration)
  231. # An iteration should have occurred at 2, but since 2 is the present
  232. # and not the future, it is skipped.
  233. clock.advance(0)
  234. self.assertEqual(times, [0])
  235. # 2.5 is in the future, and is not skipped.
  236. callDuration = 1
  237. clock.advance(0.5)
  238. self.assertEqual(times, [0, 2.5])
  239. self.assertEqual(clock.seconds(), 3.5)
  240. # Another iteration should have occurred, but it is again the
  241. # present and not the future, so it is skipped as well.
  242. clock.advance(0)
  243. self.assertEqual(times, [0, 2.5])
  244. # 4 is in the future, and is not skipped.
  245. callDuration = 0
  246. clock.advance(0.5)
  247. self.assertEqual(times, [0, 2.5, 4])
  248. self.assertEqual(clock.seconds(), 4)
  249. def test_reactorTimeSkips(self):
  250. """
  251. When more time than the defined interval passes between when
  252. L{LoopingCall} schedules itself to run again and when it actually
  253. runs again, it should schedule the next call for the next interval
  254. which is still in the future.
  255. """
  256. times = []
  257. clock = task.Clock()
  258. def aCallback():
  259. times.append(clock.seconds())
  260. # Start a LoopingCall that tracks the time passed, with a 0.5 second
  261. # increment.
  262. call = task.LoopingCall(aCallback)
  263. call.clock = clock
  264. call.start(0.5)
  265. # Initially, no time should have passed!
  266. self.assertEqual(times, [0])
  267. # Advance the clock by 2 seconds (2 seconds should have passed)
  268. clock.advance(2)
  269. self.assertEqual(times, [0, 2])
  270. # Advance the clock by 1 second (3 total should have passed)
  271. clock.advance(1)
  272. self.assertEqual(times, [0, 2, 3])
  273. # Advance the clock by 0 seconds (this should have no effect!)
  274. clock.advance(0)
  275. self.assertEqual(times, [0, 2, 3])
  276. def test_reactorTimeCountSkips(self):
  277. """
  278. When L{LoopingCall} schedules itself to run again, if more than the
  279. specified interval has passed, it should schedule the next call for the
  280. next interval which is still in the future. If it was created
  281. using L{LoopingCall.withCount}, a positional argument will be
  282. inserted at the beginning of the argument list, indicating the number
  283. of calls that should have been made.
  284. """
  285. times = []
  286. clock = task.Clock()
  287. def aCallback(numCalls):
  288. times.append((clock.seconds(), numCalls))
  289. # Start a LoopingCall that tracks the time passed, and the number of
  290. # skips, with a 0.5 second increment.
  291. call = task.LoopingCall.withCount(aCallback)
  292. call.clock = clock
  293. INTERVAL = 0.5
  294. REALISTIC_DELAY = 0.01
  295. call.start(INTERVAL)
  296. # Initially, no seconds should have passed, and one calls should have
  297. # been made.
  298. self.assertEqual(times, [(0, 1)])
  299. # After the interval (plus a small delay, to account for the time that
  300. # the reactor takes to wake up and process the LoopingCall), we should
  301. # still have only made one call.
  302. clock.advance(INTERVAL + REALISTIC_DELAY)
  303. self.assertEqual(times, [(0, 1), (INTERVAL + REALISTIC_DELAY, 1)])
  304. # After advancing the clock by three intervals (plus a small delay to
  305. # account for the reactor), we should have skipped two calls; one less
  306. # than the number of intervals which have completely elapsed. Along
  307. # with the call we did actually make, the final number of calls is 3.
  308. clock.advance((3 * INTERVAL) + REALISTIC_DELAY)
  309. self.assertEqual(
  310. times,
  311. [
  312. (0, 1),
  313. (INTERVAL + REALISTIC_DELAY, 1),
  314. ((4 * INTERVAL) + (2 * REALISTIC_DELAY), 3),
  315. ],
  316. )
  317. # Advancing the clock by 0 seconds should not cause any changes!
  318. clock.advance(0)
  319. self.assertEqual(
  320. times,
  321. [
  322. (0, 1),
  323. (INTERVAL + REALISTIC_DELAY, 1),
  324. ((4 * INTERVAL) + (2 * REALISTIC_DELAY), 3),
  325. ],
  326. )
  327. def test_countLengthyIntervalCounts(self):
  328. """
  329. L{LoopingCall.withCount} counts only calls that were expected to be
  330. made. So, if more than one, but less than two intervals pass between
  331. invocations, it won't increase the count above 1. For example, a
  332. L{LoopingCall} with interval T expects to be invoked at T, 2T, 3T, etc.
  333. However, the reactor takes some time to get around to calling it, so in
  334. practice it will be called at T+something, 2T+something, 3T+something;
  335. and due to other things going on in the reactor, "something" is
  336. variable. It won't increase the count unless "something" is greater
  337. than T. So if the L{LoopingCall} is invoked at T, 2.75T, and 3T,
  338. the count has not increased, even though the distance between
  339. invocation 1 and invocation 2 is 1.75T.
  340. """
  341. times = []
  342. clock = task.Clock()
  343. def aCallback(count):
  344. times.append((clock.seconds(), count))
  345. # Start a LoopingCall that tracks the time passed, and the number of
  346. # calls, with a 0.5 second increment.
  347. call = task.LoopingCall.withCount(aCallback)
  348. call.clock = clock
  349. INTERVAL = 0.5
  350. REALISTIC_DELAY = 0.01
  351. call.start(INTERVAL)
  352. self.assertEqual(times.pop(), (0, 1))
  353. # About one interval... So far, so good
  354. clock.advance(INTERVAL + REALISTIC_DELAY)
  355. self.assertEqual(times.pop(), (INTERVAL + REALISTIC_DELAY, 1))
  356. # Oh no, something delayed us for a while.
  357. clock.advance(INTERVAL * 1.75)
  358. self.assertEqual(times.pop(), ((2.75 * INTERVAL) + REALISTIC_DELAY, 1))
  359. # Back on track! We got invoked when we expected this time.
  360. clock.advance(INTERVAL * 0.25)
  361. self.assertEqual(times.pop(), ((3.0 * INTERVAL) + REALISTIC_DELAY, 1))
  362. def test_withCountFloatingPointBoundary(self):
  363. """
  364. L{task.LoopingCall.withCount} should never invoke its callable with a
  365. zero. Specifically, if a L{task.LoopingCall} created with C{withCount}
  366. has its L{start <task.LoopingCall.start>} method invoked with a
  367. floating-point number which introduces decimal inaccuracy when
  368. multiplied or divided, such as "0.1", L{task.LoopingCall} will never
  369. invoke its callable with 0. Also, the sum of all the values passed to
  370. its callable as the "count" will be an integer, the number of intervals
  371. that have elapsed.
  372. This is a regression test for a particularly tricky case to implement.
  373. """
  374. clock = task.Clock()
  375. accumulator = []
  376. call = task.LoopingCall.withCount(accumulator.append)
  377. call.clock = clock
  378. # 'count': the number of ticks within the time span, the number of
  379. # calls that should be made. this should be a value which causes
  380. # floating-point inaccuracy as the denominator for the timespan.
  381. count = 10
  382. # 'timespan': the amount of virtual time that the test will take, in
  383. # seconds, as a floating point number
  384. timespan = 1.0
  385. # 'interval': the amount of time for one actual call.
  386. interval = timespan / count
  387. call.start(interval, now=False)
  388. for x in range(count):
  389. clock.advance(interval)
  390. # There is still an epsilon of inaccuracy here; 0.1 is not quite
  391. # exactly 1/10 in binary, so we need to push our clock over the
  392. # threshold.
  393. epsilon = timespan - sum([interval] * count)
  394. clock.advance(epsilon)
  395. secondsValue = clock.seconds()
  396. # The following two assertions are here to ensure that if the values of
  397. # count, timespan, and interval are changed, that the test remains
  398. # valid. First, the "epsilon" value here measures the floating-point
  399. # inaccuracy in question, and so if it doesn't exist then we are not
  400. # triggering an interesting condition.
  401. self.assertTrue(abs(epsilon) > 0.0, f"{epsilon} should be greater than zero")
  402. # Secondly, task.Clock should behave in such a way that once we have
  403. # advanced to this point, it has reached or exceeded the timespan.
  404. self.assertTrue(
  405. secondsValue >= timespan,
  406. f"{secondsValue} should be greater than or equal to {timespan}",
  407. )
  408. self.assertEqual(sum(accumulator), count)
  409. self.assertNotIn(0, accumulator)
  410. def test_withCountIntervalZero(self):
  411. """
  412. L{task.LoopingCall.withCount} with interval set to 0 calls the
  413. countCallable with a count of 1.
  414. """
  415. clock = task.Clock()
  416. accumulator = []
  417. def foo(cnt):
  418. accumulator.append(cnt)
  419. if len(accumulator) > 4:
  420. loop.stop()
  421. loop = task.LoopingCall.withCount(foo)
  422. loop.clock = clock
  423. deferred = loop.start(0, now=False)
  424. # Even though we have a no-delay loop,
  425. # a single iteration of the reactor will not trigger the looping call
  426. # multiple times.
  427. # This is why we explicitly iterate multiple times.
  428. clock.pump([0] * 5)
  429. self.successResultOf(deferred)
  430. self.assertEqual([1] * 5, accumulator)
  431. def test_withCountIntervalZeroDelay(self):
  432. """
  433. L{task.LoopingCall.withCount} with interval set to 0 and a delayed
  434. call during the loop run will still call the countCallable 1 as if
  435. no delay occurred.
  436. """
  437. clock = task.Clock()
  438. deferred = defer.Deferred()
  439. accumulator = []
  440. def foo(cnt):
  441. accumulator.append(cnt)
  442. if len(accumulator) == 2:
  443. return deferred
  444. if len(accumulator) > 4:
  445. loop.stop()
  446. loop = task.LoopingCall.withCount(foo)
  447. loop.clock = clock
  448. loop.start(0, now=False)
  449. clock.pump([0] * 2)
  450. # Loop will block at the third call.
  451. self.assertEqual([1] * 2, accumulator)
  452. # Even if more time pass, the loops is not
  453. # advanced.
  454. clock.pump([1] * 2)
  455. self.assertEqual([1] * 2, accumulator)
  456. # Once the waiting call got a result the loop continues without
  457. # observing any delay in countCallable.
  458. deferred.callback(None)
  459. clock.pump([0] * 4)
  460. self.assertEqual([1] * 5, accumulator)
  461. def test_withCountIntervalZeroDelayThenNonZeroInterval(self):
  462. """
  463. L{task.LoopingCall.withCount} with interval set to 0 will still keep
  464. the time when last called so when the interval is reset.
  465. """
  466. clock = task.Clock()
  467. deferred = defer.Deferred()
  468. accumulator = []
  469. # The amount of time to let pass (the number of 1 second steps to
  470. # take) before the looping function returns an unfired Deferred.
  471. stepsBeforeDelay = 2
  472. # The amount of time to let pass (the number of 1 second steps to
  473. # take) after the looping function returns an unfired Deferred before
  474. # fiddling with the loop interval.
  475. extraTimeAfterDelay = 5
  476. # The new value to set for the loop interval when fiddling with it.
  477. mutatedLoopInterval = 2
  478. # The amount of time to let pass (in one jump) after fiddling with the
  479. # loop interval.
  480. durationOfDelay = 9
  481. # This is the amount of time that passed between the
  482. # Deferred-returning call of the looping function and the next time it
  483. # gets a chance to run.
  484. skippedTime = extraTimeAfterDelay + durationOfDelay
  485. # This is the number of calls that would have been made to the
  486. # function in that amount of time if the unfired Deferred hadn't been
  487. # preventing calls and if the clock hadn't made a large jump after the
  488. # Deferred fired.
  489. expectedSkipCount = skippedTime // mutatedLoopInterval
  490. # Because of #5962 LoopingCall sees an unrealistic time for the second
  491. # call (it seems 1.0 but on a real reactor it will see 2.0) which
  492. # causes it to calculate the skip count incorrectly. Fudge our
  493. # expectation here until #5962 is fixed.
  494. expectedSkipCount += 1
  495. def foo(cnt):
  496. accumulator.append(cnt)
  497. if len(accumulator) == stepsBeforeDelay:
  498. return deferred
  499. loop = task.LoopingCall.withCount(foo)
  500. loop.clock = clock
  501. loop.start(0, now=False)
  502. # Even if a lot of time passes the loop will stop iterating once the
  503. # Deferred is returned. 1 * stepsBeforeDelay is enough time to get to
  504. # the Deferred result. The extraTimeAfterDelay shows us it isn't
  505. # still iterating afterwards.
  506. clock.pump([1] * (stepsBeforeDelay + extraTimeAfterDelay))
  507. self.assertEqual([1] * stepsBeforeDelay, accumulator)
  508. # When a new interval is set, once the waiting call got a result the
  509. # loop continues with the new interval.
  510. loop.interval = mutatedLoopInterval
  511. deferred.callback(None)
  512. clock.advance(durationOfDelay)
  513. # It will count skipped steps since the last loop call.
  514. self.assertEqual([1, 1, expectedSkipCount], accumulator)
  515. clock.advance(1 * mutatedLoopInterval)
  516. self.assertEqual([1, 1, expectedSkipCount, 1], accumulator)
  517. clock.advance(2 * mutatedLoopInterval)
  518. self.assertEqual([1, 1, expectedSkipCount, 1, 2], accumulator)
  519. def testBasicFunction(self):
  520. # Arrange to have time advanced enough so that our function is
  521. # called a few times.
  522. # Only need to go to 2.5 to get 3 calls, since the first call
  523. # happens before any time has elapsed.
  524. timings = [0.05, 0.1, 0.1]
  525. clock = task.Clock()
  526. L = []
  527. def foo(a, b, c=None, d=None):
  528. L.append((a, b, c, d))
  529. lc = TestableLoopingCall(clock, foo, "a", "b", d="d")
  530. D = lc.start(0.1)
  531. theResult = []
  532. def saveResult(result):
  533. theResult.append(result)
  534. D.addCallback(saveResult)
  535. clock.pump(timings)
  536. self.assertEqual(len(L), 3, "got %d iterations, not 3" % (len(L),))
  537. for (a, b, c, d) in L:
  538. self.assertEqual(a, "a")
  539. self.assertEqual(b, "b")
  540. self.assertIsNone(c)
  541. self.assertEqual(d, "d")
  542. lc.stop()
  543. self.assertIs(theResult[0], lc)
  544. # Make sure it isn't planning to do anything further.
  545. self.assertFalse(clock.calls)
  546. def testDelayedStart(self):
  547. timings = [0.05, 0.1, 0.1]
  548. clock = task.Clock()
  549. L = []
  550. lc = TestableLoopingCall(clock, L.append, None)
  551. d = lc.start(0.1, now=False)
  552. theResult = []
  553. def saveResult(result):
  554. theResult.append(result)
  555. d.addCallback(saveResult)
  556. clock.pump(timings)
  557. self.assertEqual(len(L), 2, "got %d iterations, not 2" % (len(L),))
  558. lc.stop()
  559. self.assertIs(theResult[0], lc)
  560. self.assertFalse(clock.calls)
  561. def testBadDelay(self):
  562. lc = task.LoopingCall(lambda: None)
  563. self.assertRaises(ValueError, lc.start, -1)
  564. # Make sure that LoopingCall.stop() prevents any subsequent calls.
  565. def _stoppingTest(self, delay):
  566. ran = []
  567. def foo():
  568. ran.append(None)
  569. clock = task.Clock()
  570. lc = TestableLoopingCall(clock, foo)
  571. lc.start(delay, now=False)
  572. lc.stop()
  573. self.assertFalse(ran)
  574. self.assertFalse(clock.calls)
  575. def testStopAtOnce(self):
  576. return self._stoppingTest(0)
  577. def testStoppingBeforeDelayedStart(self):
  578. return self._stoppingTest(10)
  579. def test_reset(self):
  580. """
  581. Test that L{LoopingCall} can be reset.
  582. """
  583. ran = []
  584. def foo():
  585. ran.append(None)
  586. c = task.Clock()
  587. lc = TestableLoopingCall(c, foo)
  588. lc.start(2, now=False)
  589. c.advance(1)
  590. lc.reset()
  591. c.advance(1)
  592. self.assertEqual(ran, [])
  593. c.advance(1)
  594. self.assertEqual(ran, [None])
  595. def test_reprFunction(self):
  596. """
  597. L{LoopingCall.__repr__} includes the wrapped function's name.
  598. """
  599. self.assertEqual(
  600. repr(task.LoopingCall(installReactor, 1, key=2)),
  601. "LoopingCall<None>(installReactor, *(1,), **{'key': 2})",
  602. )
  603. def test_reprMethod(self):
  604. """
  605. L{LoopingCall.__repr__} includes the wrapped method's full name.
  606. """
  607. self.assertEqual(
  608. repr(task.LoopingCall(TestableLoopingCall.__init__)),
  609. "LoopingCall<None>(TestableLoopingCall.__init__, *(), **{})",
  610. )
  611. def test_deferredDeprecation(self):
  612. """
  613. L{LoopingCall.deferred} is deprecated.
  614. """
  615. loop = task.LoopingCall(lambda: None)
  616. loop.deferred
  617. message = (
  618. "twisted.internet.task.LoopingCall.deferred was deprecated in "
  619. "Twisted 16.0.0; "
  620. "please use the deferred returned by start() instead"
  621. )
  622. warnings = self.flushWarnings([self.test_deferredDeprecation])
  623. self.assertEqual(1, len(warnings))
  624. self.assertEqual(DeprecationWarning, warnings[0]["category"])
  625. self.assertEqual(message, warnings[0]["message"])
  626. class ReactorLoopTests(unittest.TestCase):
  627. # Slightly inferior tests which exercise interactions with an actual
  628. # reactor.
  629. def testFailure(self):
  630. def foo(x):
  631. raise TestException(x)
  632. lc = task.LoopingCall(foo, "bar")
  633. return self.assertFailure(lc.start(0.1), TestException)
  634. def testFailAndStop(self):
  635. def foo(x):
  636. lc.stop()
  637. raise TestException(x)
  638. lc = task.LoopingCall(foo, "bar")
  639. return self.assertFailure(lc.start(0.1), TestException)
  640. def testEveryIteration(self):
  641. ran = []
  642. def foo():
  643. ran.append(None)
  644. if len(ran) > 5:
  645. lc.stop()
  646. lc = task.LoopingCall(foo)
  647. d = lc.start(0)
  648. def stopped(ign):
  649. self.assertEqual(len(ran), 6)
  650. return d.addCallback(stopped)
  651. def testStopAtOnceLater(self):
  652. # Ensure that even when LoopingCall.stop() is called from a
  653. # reactor callback, it still prevents any subsequent calls.
  654. d = defer.Deferred()
  655. def foo():
  656. d.errback(
  657. failure.DefaultException("This task also should never get called.")
  658. )
  659. self._lc = task.LoopingCall(foo)
  660. self._lc.start(1, now=False)
  661. reactor.callLater(0, self._callback_for_testStopAtOnceLater, d)
  662. return d
  663. def _callback_for_testStopAtOnceLater(self, d):
  664. self._lc.stop()
  665. reactor.callLater(0, d.callback, "success")
  666. def testWaitDeferred(self):
  667. # Tests if the callable isn't scheduled again before the returned
  668. # deferred has fired.
  669. timings = [0.2, 0.8]
  670. clock = task.Clock()
  671. def foo():
  672. d = defer.Deferred()
  673. d.addCallback(lambda _: lc.stop())
  674. clock.callLater(1, d.callback, None)
  675. return d
  676. lc = TestableLoopingCall(clock, foo)
  677. lc.start(0.2)
  678. clock.pump(timings)
  679. self.assertFalse(clock.calls)
  680. def testFailurePropagation(self):
  681. # Tests if the failure of the errback of the deferred returned by the
  682. # callable is propagated to the lc errback.
  683. #
  684. # To make sure this test does not hang trial when LoopingCall does not
  685. # wait for the callable's deferred, it also checks there are no
  686. # calls in the clock's callLater queue.
  687. timings = [0.3]
  688. clock = task.Clock()
  689. def foo():
  690. d = defer.Deferred()
  691. clock.callLater(0.3, d.errback, TestException())
  692. return d
  693. lc = TestableLoopingCall(clock, foo)
  694. d = lc.start(1)
  695. self.assertFailure(d, TestException)
  696. clock.pump(timings)
  697. self.assertFalse(clock.calls)
  698. return d
  699. def test_deferredWithCount(self):
  700. """
  701. In the case that the function passed to L{LoopingCall.withCount}
  702. returns a deferred, which does not fire before the next interval
  703. elapses, the function should not be run again. And if a function call
  704. is skipped in this fashion, the appropriate count should be
  705. provided.
  706. """
  707. testClock = task.Clock()
  708. d = defer.Deferred()
  709. deferredCounts = []
  710. def countTracker(possibleCount):
  711. # Keep a list of call counts
  712. deferredCounts.append(possibleCount)
  713. # Return a deferred, but only on the first request
  714. if len(deferredCounts) == 1:
  715. return d
  716. else:
  717. return None
  718. # Start a looping call for our countTracker function
  719. # Set the increment to 0.2, and do not call the function on startup.
  720. lc = task.LoopingCall.withCount(countTracker)
  721. lc.clock = testClock
  722. d = lc.start(0.2, now=False)
  723. # Confirm that nothing has happened yet.
  724. self.assertEqual(deferredCounts, [])
  725. # Advance the clock by 0.2 and then 0.4;
  726. testClock.pump([0.2, 0.4])
  727. # We should now have exactly one count (of 1 call)
  728. self.assertEqual(len(deferredCounts), 1)
  729. # Fire the deferred, and advance the clock by another 0.2
  730. d.callback(None)
  731. testClock.pump([0.2])
  732. # We should now have exactly 2 counts...
  733. self.assertEqual(len(deferredCounts), 2)
  734. # The first count should be 1 (one call)
  735. # The second count should be 3 (calls were missed at about 0.6 and 0.8)
  736. self.assertEqual(deferredCounts, [1, 3])
  737. class DeferLaterTests(unittest.TestCase):
  738. """
  739. Tests for L{task.deferLater}.
  740. """
  741. def test_callback(self):
  742. """
  743. The L{Deferred} returned by L{task.deferLater} is called back after
  744. the specified delay with the result of the function passed in.
  745. """
  746. results = []
  747. flag = object()
  748. def callable(foo, bar):
  749. results.append((foo, bar))
  750. return flag
  751. clock = task.Clock()
  752. d = task.deferLater(clock, 3, callable, "foo", bar="bar")
  753. d.addCallback(self.assertIs, flag)
  754. clock.advance(2)
  755. self.assertEqual(results, [])
  756. clock.advance(1)
  757. self.assertEqual(results, [("foo", "bar")])
  758. return d
  759. def test_errback(self):
  760. """
  761. The L{Deferred} returned by L{task.deferLater} is errbacked if the
  762. supplied function raises an exception.
  763. """
  764. def callable():
  765. raise TestException()
  766. clock = task.Clock()
  767. d = task.deferLater(clock, 1, callable)
  768. clock.advance(1)
  769. return self.assertFailure(d, TestException)
  770. def test_cancel(self):
  771. """
  772. The L{Deferred} returned by L{task.deferLater} can be
  773. cancelled to prevent the call from actually being performed.
  774. """
  775. called = []
  776. clock = task.Clock()
  777. d = task.deferLater(clock, 1, called.append, None)
  778. d.cancel()
  779. def cbCancelled(ignored):
  780. # Make sure there are no calls outstanding.
  781. self.assertEqual([], clock.getDelayedCalls())
  782. # And make sure the call didn't somehow happen already.
  783. self.assertFalse(called)
  784. self.assertFailure(d, defer.CancelledError)
  785. d.addCallback(cbCancelled)
  786. return d
  787. def test_noCallback(self):
  788. """
  789. The L{Deferred} returned by L{task.deferLater} fires with C{None}
  790. when no callback function is passed.
  791. """
  792. clock = task.Clock()
  793. d = task.deferLater(clock, 2.0)
  794. self.assertNoResult(d)
  795. clock.advance(2.0)
  796. self.assertIs(None, self.successResultOf(d))
  797. class _FakeReactor:
  798. def __init__(self):
  799. self._running = False
  800. self._clock = task.Clock()
  801. self.callLater = self._clock.callLater
  802. self.seconds = self._clock.seconds
  803. self.getDelayedCalls = self._clock.getDelayedCalls
  804. self._whenRunning = []
  805. self._shutdownTriggers = {"before": [], "during": []}
  806. def callWhenRunning(self, callable, *args, **kwargs):
  807. if self._whenRunning is None:
  808. callable(*args, **kwargs)
  809. else:
  810. self._whenRunning.append((callable, args, kwargs))
  811. def addSystemEventTrigger(self, phase, event, callable, *args):
  812. assert phase in ("before", "during")
  813. assert event == "shutdown"
  814. self._shutdownTriggers[phase].append((callable, args))
  815. def run(self):
  816. """
  817. Call timed events until there are no more or the reactor is stopped.
  818. @raise RuntimeError: When no timed events are left and the reactor is
  819. still running.
  820. """
  821. self._running = True
  822. whenRunning = self._whenRunning
  823. self._whenRunning = None
  824. for callable, args, kwargs in whenRunning:
  825. callable(*args, **kwargs)
  826. while self._running:
  827. calls = self.getDelayedCalls()
  828. if not calls:
  829. raise RuntimeError("No DelayedCalls left")
  830. self._clock.advance(calls[0].getTime() - self.seconds())
  831. shutdownTriggers = self._shutdownTriggers
  832. self._shutdownTriggers = None
  833. for (trigger, args) in shutdownTriggers["before"] + shutdownTriggers["during"]:
  834. trigger(*args)
  835. def stop(self):
  836. """
  837. Stop the reactor.
  838. """
  839. if not self._running:
  840. raise error.ReactorNotRunning()
  841. self._running = False
  842. class ReactTests(unittest.SynchronousTestCase):
  843. """
  844. Tests for L{twisted.internet.task.react}.
  845. """
  846. def test_runsUntilAsyncCallback(self):
  847. """
  848. L{task.react} runs the reactor until the L{Deferred} returned by the
  849. function it is passed is called back, then stops it.
  850. """
  851. timePassed = []
  852. def main(reactor):
  853. finished = defer.Deferred()
  854. reactor.callLater(1, timePassed.append, True)
  855. reactor.callLater(2, finished.callback, None)
  856. return finished
  857. r = _FakeReactor()
  858. exitError = self.assertRaises(SystemExit, task.react, main, _reactor=r)
  859. self.assertEqual(0, exitError.code)
  860. self.assertEqual(timePassed, [True])
  861. self.assertEqual(r.seconds(), 2)
  862. def test_runsUntilSyncCallback(self):
  863. """
  864. L{task.react} returns quickly if the L{Deferred} returned by the
  865. function it is passed has already been called back at the time it is
  866. returned.
  867. """
  868. def main(reactor):
  869. return defer.succeed(None)
  870. r = _FakeReactor()
  871. exitError = self.assertRaises(SystemExit, task.react, main, _reactor=r)
  872. self.assertEqual(0, exitError.code)
  873. self.assertEqual(r.seconds(), 0)
  874. def test_runsUntilAsyncErrback(self):
  875. """
  876. L{task.react} runs the reactor until the L{defer.Deferred} returned by
  877. the function it is passed is errbacked, then it stops the reactor and
  878. reports the error.
  879. """
  880. class ExpectedException(Exception):
  881. pass
  882. def main(reactor):
  883. finished = defer.Deferred()
  884. reactor.callLater(1, finished.errback, ExpectedException())
  885. return finished
  886. r = _FakeReactor()
  887. exitError = self.assertRaises(SystemExit, task.react, main, _reactor=r)
  888. self.assertEqual(1, exitError.code)
  889. errors = self.flushLoggedErrors(ExpectedException)
  890. self.assertEqual(len(errors), 1)
  891. def test_runsUntilSyncErrback(self):
  892. """
  893. L{task.react} returns quickly if the L{defer.Deferred} returned by the
  894. function it is passed has already been errbacked at the time it is
  895. returned.
  896. """
  897. class ExpectedException(Exception):
  898. pass
  899. def main(reactor):
  900. return defer.fail(ExpectedException())
  901. r = _FakeReactor()
  902. exitError = self.assertRaises(SystemExit, task.react, main, _reactor=r)
  903. self.assertEqual(1, exitError.code)
  904. self.assertEqual(r.seconds(), 0)
  905. errors = self.flushLoggedErrors(ExpectedException)
  906. self.assertEqual(len(errors), 1)
  907. def test_singleStopCallback(self):
  908. """
  909. L{task.react} doesn't try to stop the reactor if the L{defer.Deferred}
  910. the function it is passed is called back after the reactor has already
  911. been stopped.
  912. """
  913. def main(reactor):
  914. reactor.callLater(1, reactor.stop)
  915. finished = defer.Deferred()
  916. reactor.addSystemEventTrigger("during", "shutdown", finished.callback, None)
  917. return finished
  918. r = _FakeReactor()
  919. exitError = self.assertRaises(SystemExit, task.react, main, _reactor=r)
  920. self.assertEqual(r.seconds(), 1)
  921. self.assertEqual(0, exitError.code)
  922. def test_singleStopErrback(self):
  923. """
  924. L{task.react} doesn't try to stop the reactor if the L{defer.Deferred}
  925. the function it is passed is errbacked after the reactor has already
  926. been stopped.
  927. """
  928. class ExpectedException(Exception):
  929. pass
  930. def main(reactor):
  931. reactor.callLater(1, reactor.stop)
  932. finished = defer.Deferred()
  933. reactor.addSystemEventTrigger(
  934. "during", "shutdown", finished.errback, ExpectedException()
  935. )
  936. return finished
  937. r = _FakeReactor()
  938. exitError = self.assertRaises(SystemExit, task.react, main, _reactor=r)
  939. self.assertEqual(1, exitError.code)
  940. self.assertEqual(r.seconds(), 1)
  941. errors = self.flushLoggedErrors(ExpectedException)
  942. self.assertEqual(len(errors), 1)
  943. def test_arguments(self):
  944. """
  945. L{task.react} passes the elements of the list it is passed as
  946. positional arguments to the function it is passed.
  947. """
  948. args = []
  949. def main(reactor, x, y, z):
  950. args.extend((x, y, z))
  951. return defer.succeed(None)
  952. r = _FakeReactor()
  953. exitError = self.assertRaises(
  954. SystemExit, task.react, main, [1, 2, 3], _reactor=r
  955. )
  956. self.assertEqual(0, exitError.code)
  957. self.assertEqual(args, [1, 2, 3])
  958. def test_defaultReactor(self):
  959. """
  960. L{twisted.internet.reactor} is used if no reactor argument is passed to
  961. L{task.react}.
  962. """
  963. def main(reactor):
  964. self.passedReactor = reactor
  965. return defer.succeed(None)
  966. reactor = _FakeReactor()
  967. with NoReactor():
  968. installReactor(reactor)
  969. exitError = self.assertRaises(SystemExit, task.react, main, [])
  970. self.assertEqual(0, exitError.code)
  971. self.assertIs(reactor, self.passedReactor)
  972. def test_exitWithDefinedCode(self):
  973. """
  974. L{task.react} forwards the exit code specified by the C{SystemExit}
  975. error returned by the passed function, if any.
  976. """
  977. def main(reactor):
  978. return defer.fail(SystemExit(23))
  979. r = _FakeReactor()
  980. exitError = self.assertRaises(SystemExit, task.react, main, [], _reactor=r)
  981. self.assertEqual(23, exitError.code)
  982. def test_synchronousStop(self):
  983. """
  984. L{task.react} handles when the reactor is stopped just before the
  985. returned L{Deferred} fires.
  986. """
  987. def main(reactor):
  988. d = defer.Deferred()
  989. def stop():
  990. reactor.stop()
  991. d.callback(None)
  992. reactor.callWhenRunning(stop)
  993. return d
  994. r = _FakeReactor()
  995. exitError = self.assertRaises(SystemExit, task.react, main, [], _reactor=r)
  996. self.assertEqual(0, exitError.code)
  997. def test_asynchronousStop(self):
  998. """
  999. L{task.react} handles when the reactor is stopped and the
  1000. returned L{Deferred} doesn't fire.
  1001. """
  1002. def main(reactor):
  1003. reactor.callLater(1, reactor.stop)
  1004. return defer.Deferred()
  1005. r = _FakeReactor()
  1006. exitError = self.assertRaises(SystemExit, task.react, main, [], _reactor=r)
  1007. self.assertEqual(0, exitError.code)
  1008. class ReactCoroutineFunctionTests(unittest.SynchronousTestCase):
  1009. """
  1010. Tests for L{twisted.internet.task.react} with an C{async def} argument
  1011. """
  1012. def test_runsUntilAsyncCallback(self):
  1013. """
  1014. L{task.react} runs the reactor until the L{Deferred} returned by the
  1015. function it is passed is called back, then stops it.
  1016. """
  1017. timePassed = []
  1018. async def main(reactor):
  1019. finished = defer.Deferred()
  1020. reactor.callLater(1, timePassed.append, True)
  1021. reactor.callLater(2, finished.callback, None)
  1022. return await finished
  1023. r = _FakeReactor()
  1024. exitError = self.assertRaises(SystemExit, task.react, main, _reactor=r)
  1025. self.assertEqual(0, exitError.code)
  1026. self.assertEqual(timePassed, [True])
  1027. self.assertEqual(r.seconds(), 2)
  1028. def test_runsUntilSyncCallback(self):
  1029. """
  1030. L{task.react} returns quickly if the L{Deferred} returned by the
  1031. function it is passed has already been called back at the time it is
  1032. returned.
  1033. """
  1034. async def main(reactor):
  1035. return await defer.succeed(None)
  1036. r = _FakeReactor()
  1037. exitError = self.assertRaises(SystemExit, task.react, main, _reactor=r)
  1038. self.assertEqual(0, exitError.code)
  1039. self.assertEqual(r.seconds(), 0)
  1040. def test_runsUntilAsyncErrback(self):
  1041. """
  1042. L{task.react} runs the reactor until the L{defer.Deferred} returned by
  1043. the function it is passed is errbacked, then it stops the reactor and
  1044. reports the error.
  1045. """
  1046. class ExpectedException(Exception):
  1047. pass
  1048. async def main(reactor):
  1049. finished = defer.Deferred()
  1050. reactor.callLater(1, finished.errback, ExpectedException())
  1051. return await finished
  1052. r = _FakeReactor()
  1053. exitError = self.assertRaises(SystemExit, task.react, main, _reactor=r)
  1054. self.assertEqual(1, exitError.code)
  1055. errors = self.flushLoggedErrors(ExpectedException)
  1056. self.assertEqual(len(errors), 1)
  1057. def test_runsUntilSyncErrback(self):
  1058. """
  1059. L{task.react} returns quickly if the L{defer.Deferred} returned by the
  1060. function it is passed has already been errbacked at the time it is
  1061. returned.
  1062. """
  1063. class ExpectedException(Exception):
  1064. pass
  1065. async def main(reactor):
  1066. return await defer.fail(ExpectedException())
  1067. r = _FakeReactor()
  1068. exitError = self.assertRaises(SystemExit, task.react, main, _reactor=r)
  1069. self.assertEqual(1, exitError.code)
  1070. self.assertEqual(r.seconds(), 0)
  1071. errors = self.flushLoggedErrors(ExpectedException)
  1072. self.assertEqual(len(errors), 1)
  1073. def test_singleStopCallback(self):
  1074. """
  1075. L{task.react} doesn't try to stop the reactor if the L{defer.Deferred}
  1076. the function it is passed is called back after the reactor has already
  1077. been stopped.
  1078. """
  1079. async def main(reactor):
  1080. reactor.callLater(1, reactor.stop)
  1081. finished = defer.Deferred()
  1082. reactor.addSystemEventTrigger("during", "shutdown", finished.callback, None)
  1083. return await finished
  1084. r = _FakeReactor()
  1085. exitError = self.assertRaises(SystemExit, task.react, main, _reactor=r)
  1086. self.assertEqual(r.seconds(), 1)
  1087. self.assertEqual(0, exitError.code)
  1088. def test_singleStopErrback(self):
  1089. """
  1090. L{task.react} doesn't try to stop the reactor if the L{defer.Deferred}
  1091. the function it is passed is errbacked after the reactor has already
  1092. been stopped.
  1093. """
  1094. class ExpectedException(Exception):
  1095. pass
  1096. async def main(reactor):
  1097. reactor.callLater(1, reactor.stop)
  1098. finished = defer.Deferred()
  1099. reactor.addSystemEventTrigger(
  1100. "during", "shutdown", finished.errback, ExpectedException()
  1101. )
  1102. return await finished
  1103. r = _FakeReactor()
  1104. exitError = self.assertRaises(SystemExit, task.react, main, _reactor=r)
  1105. self.assertEqual(1, exitError.code)
  1106. self.assertEqual(r.seconds(), 1)
  1107. errors = self.flushLoggedErrors(ExpectedException)
  1108. self.assertEqual(len(errors), 1)
  1109. def test_arguments(self):
  1110. """
  1111. L{task.react} passes the elements of the list it is passed as
  1112. positional arguments to the function it is passed.
  1113. """
  1114. args = []
  1115. async def main(reactor, x, y, z):
  1116. args.extend((x, y, z))
  1117. return await defer.succeed(None)
  1118. r = _FakeReactor()
  1119. exitError = self.assertRaises(
  1120. SystemExit, task.react, main, [1, 2, 3], _reactor=r
  1121. )
  1122. self.assertEqual(0, exitError.code)
  1123. self.assertEqual(args, [1, 2, 3])
  1124. def test_defaultReactor(self):
  1125. """
  1126. L{twisted.internet.reactor} is used if no reactor argument is passed to
  1127. L{task.react}.
  1128. """
  1129. async def main(reactor):
  1130. self.passedReactor = reactor
  1131. return await defer.succeed(None)
  1132. reactor = _FakeReactor()
  1133. with NoReactor():
  1134. installReactor(reactor)
  1135. exitError = self.assertRaises(SystemExit, task.react, main, [])
  1136. self.assertEqual(0, exitError.code)
  1137. self.assertIs(reactor, self.passedReactor)
  1138. def test_exitWithDefinedCode(self):
  1139. """
  1140. L{task.react} forwards the exit code specified by the C{SystemExit}
  1141. error returned by the passed function, if any.
  1142. """
  1143. async def main(reactor):
  1144. return await defer.fail(SystemExit(23))
  1145. r = _FakeReactor()
  1146. exitError = self.assertRaises(SystemExit, task.react, main, [], _reactor=r)
  1147. self.assertEqual(23, exitError.code)
  1148. def test_synchronousStop(self):
  1149. """
  1150. L{task.react} handles when the reactor is stopped just before the
  1151. returned L{Deferred} fires.
  1152. """
  1153. async def main(reactor):
  1154. d = defer.Deferred()
  1155. def stop():
  1156. reactor.stop()
  1157. d.callback(None)
  1158. reactor.callWhenRunning(stop)
  1159. return await d
  1160. r = _FakeReactor()
  1161. exitError = self.assertRaises(SystemExit, task.react, main, [], _reactor=r)
  1162. self.assertEqual(0, exitError.code)
  1163. def test_asynchronousStop(self):
  1164. """
  1165. L{task.react} handles when the reactor is stopped and the
  1166. returned L{Deferred} doesn't fire.
  1167. """
  1168. async def main(reactor):
  1169. reactor.callLater(1, reactor.stop)
  1170. return await defer.Deferred()
  1171. r = _FakeReactor()
  1172. exitError = self.assertRaises(SystemExit, task.react, main, [], _reactor=r)
  1173. self.assertEqual(0, exitError.code)