locks_test.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  2. # not use this file except in compliance with the License. You may obtain
  3. # a copy of the License at
  4. #
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. #
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  9. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  10. # License for the specific language governing permissions and limitations
  11. # under the License.
  12. from __future__ import absolute_import, division, print_function
  13. from datetime import timedelta
  14. from tornado import gen, locks
  15. from tornado.gen import TimeoutError
  16. from tornado.testing import gen_test, AsyncTestCase
  17. from tornado.test.util import unittest, skipBefore35, exec_test
  18. class ConditionTest(AsyncTestCase):
  19. def setUp(self):
  20. super(ConditionTest, self).setUp()
  21. self.history = []
  22. def record_done(self, future, key):
  23. """Record the resolution of a Future returned by Condition.wait."""
  24. def callback(_):
  25. if not future.result():
  26. # wait() resolved to False, meaning it timed out.
  27. self.history.append('timeout')
  28. else:
  29. self.history.append(key)
  30. future.add_done_callback(callback)
  31. def loop_briefly(self):
  32. """Run all queued callbacks on the IOLoop.
  33. In these tests, this method is used after calling notify() to
  34. preserve the pre-5.0 behavior in which callbacks ran
  35. synchronously.
  36. """
  37. self.io_loop.add_callback(self.stop)
  38. self.wait()
  39. def test_repr(self):
  40. c = locks.Condition()
  41. self.assertIn('Condition', repr(c))
  42. self.assertNotIn('waiters', repr(c))
  43. c.wait()
  44. self.assertIn('waiters', repr(c))
  45. @gen_test
  46. def test_notify(self):
  47. c = locks.Condition()
  48. self.io_loop.call_later(0.01, c.notify)
  49. yield c.wait()
  50. def test_notify_1(self):
  51. c = locks.Condition()
  52. self.record_done(c.wait(), 'wait1')
  53. self.record_done(c.wait(), 'wait2')
  54. c.notify(1)
  55. self.loop_briefly()
  56. self.history.append('notify1')
  57. c.notify(1)
  58. self.loop_briefly()
  59. self.history.append('notify2')
  60. self.assertEqual(['wait1', 'notify1', 'wait2', 'notify2'],
  61. self.history)
  62. def test_notify_n(self):
  63. c = locks.Condition()
  64. for i in range(6):
  65. self.record_done(c.wait(), i)
  66. c.notify(3)
  67. self.loop_briefly()
  68. # Callbacks execute in the order they were registered.
  69. self.assertEqual(list(range(3)), self.history)
  70. c.notify(1)
  71. self.loop_briefly()
  72. self.assertEqual(list(range(4)), self.history)
  73. c.notify(2)
  74. self.loop_briefly()
  75. self.assertEqual(list(range(6)), self.history)
  76. def test_notify_all(self):
  77. c = locks.Condition()
  78. for i in range(4):
  79. self.record_done(c.wait(), i)
  80. c.notify_all()
  81. self.loop_briefly()
  82. self.history.append('notify_all')
  83. # Callbacks execute in the order they were registered.
  84. self.assertEqual(
  85. list(range(4)) + ['notify_all'],
  86. self.history)
  87. @gen_test
  88. def test_wait_timeout(self):
  89. c = locks.Condition()
  90. wait = c.wait(timedelta(seconds=0.01))
  91. self.io_loop.call_later(0.02, c.notify) # Too late.
  92. yield gen.sleep(0.03)
  93. self.assertFalse((yield wait))
  94. @gen_test
  95. def test_wait_timeout_preempted(self):
  96. c = locks.Condition()
  97. # This fires before the wait times out.
  98. self.io_loop.call_later(0.01, c.notify)
  99. wait = c.wait(timedelta(seconds=0.02))
  100. yield gen.sleep(0.03)
  101. yield wait # No TimeoutError.
  102. @gen_test
  103. def test_notify_n_with_timeout(self):
  104. # Register callbacks 0, 1, 2, and 3. Callback 1 has a timeout.
  105. # Wait for that timeout to expire, then do notify(2) and make
  106. # sure everyone runs. Verifies that a timed-out callback does
  107. # not count against the 'n' argument to notify().
  108. c = locks.Condition()
  109. self.record_done(c.wait(), 0)
  110. self.record_done(c.wait(timedelta(seconds=0.01)), 1)
  111. self.record_done(c.wait(), 2)
  112. self.record_done(c.wait(), 3)
  113. # Wait for callback 1 to time out.
  114. yield gen.sleep(0.02)
  115. self.assertEqual(['timeout'], self.history)
  116. c.notify(2)
  117. yield gen.sleep(0.01)
  118. self.assertEqual(['timeout', 0, 2], self.history)
  119. self.assertEqual(['timeout', 0, 2], self.history)
  120. c.notify()
  121. yield
  122. self.assertEqual(['timeout', 0, 2, 3], self.history)
  123. @gen_test
  124. def test_notify_all_with_timeout(self):
  125. c = locks.Condition()
  126. self.record_done(c.wait(), 0)
  127. self.record_done(c.wait(timedelta(seconds=0.01)), 1)
  128. self.record_done(c.wait(), 2)
  129. # Wait for callback 1 to time out.
  130. yield gen.sleep(0.02)
  131. self.assertEqual(['timeout'], self.history)
  132. c.notify_all()
  133. yield
  134. self.assertEqual(['timeout', 0, 2], self.history)
  135. @gen_test
  136. def test_nested_notify(self):
  137. # Ensure no notifications lost, even if notify() is reentered by a
  138. # waiter calling notify().
  139. c = locks.Condition()
  140. # Three waiters.
  141. futures = [c.wait() for _ in range(3)]
  142. # First and second futures resolved. Second future reenters notify(),
  143. # resolving third future.
  144. futures[1].add_done_callback(lambda _: c.notify())
  145. c.notify(2)
  146. yield
  147. self.assertTrue(all(f.done() for f in futures))
  148. @gen_test
  149. def test_garbage_collection(self):
  150. # Test that timed-out waiters are occasionally cleaned from the queue.
  151. c = locks.Condition()
  152. for _ in range(101):
  153. c.wait(timedelta(seconds=0.01))
  154. future = c.wait()
  155. self.assertEqual(102, len(c._waiters))
  156. # Let first 101 waiters time out, triggering a collection.
  157. yield gen.sleep(0.02)
  158. self.assertEqual(1, len(c._waiters))
  159. # Final waiter is still active.
  160. self.assertFalse(future.done())
  161. c.notify()
  162. self.assertTrue(future.done())
  163. class EventTest(AsyncTestCase):
  164. def test_repr(self):
  165. event = locks.Event()
  166. self.assertTrue('clear' in str(event))
  167. self.assertFalse('set' in str(event))
  168. event.set()
  169. self.assertFalse('clear' in str(event))
  170. self.assertTrue('set' in str(event))
  171. def test_event(self):
  172. e = locks.Event()
  173. future_0 = e.wait()
  174. e.set()
  175. future_1 = e.wait()
  176. e.clear()
  177. future_2 = e.wait()
  178. self.assertTrue(future_0.done())
  179. self.assertTrue(future_1.done())
  180. self.assertFalse(future_2.done())
  181. @gen_test
  182. def test_event_timeout(self):
  183. e = locks.Event()
  184. with self.assertRaises(TimeoutError):
  185. yield e.wait(timedelta(seconds=0.01))
  186. # After a timed-out waiter, normal operation works.
  187. self.io_loop.add_timeout(timedelta(seconds=0.01), e.set)
  188. yield e.wait(timedelta(seconds=1))
  189. def test_event_set_multiple(self):
  190. e = locks.Event()
  191. e.set()
  192. e.set()
  193. self.assertTrue(e.is_set())
  194. def test_event_wait_clear(self):
  195. e = locks.Event()
  196. f0 = e.wait()
  197. e.clear()
  198. f1 = e.wait()
  199. e.set()
  200. self.assertTrue(f0.done())
  201. self.assertTrue(f1.done())
  202. class SemaphoreTest(AsyncTestCase):
  203. def test_negative_value(self):
  204. self.assertRaises(ValueError, locks.Semaphore, value=-1)
  205. def test_repr(self):
  206. sem = locks.Semaphore()
  207. self.assertIn('Semaphore', repr(sem))
  208. self.assertIn('unlocked,value:1', repr(sem))
  209. sem.acquire()
  210. self.assertIn('locked', repr(sem))
  211. self.assertNotIn('waiters', repr(sem))
  212. sem.acquire()
  213. self.assertIn('waiters', repr(sem))
  214. def test_acquire(self):
  215. sem = locks.Semaphore()
  216. f0 = sem.acquire()
  217. self.assertTrue(f0.done())
  218. # Wait for release().
  219. f1 = sem.acquire()
  220. self.assertFalse(f1.done())
  221. f2 = sem.acquire()
  222. sem.release()
  223. self.assertTrue(f1.done())
  224. self.assertFalse(f2.done())
  225. sem.release()
  226. self.assertTrue(f2.done())
  227. sem.release()
  228. # Now acquire() is instant.
  229. self.assertTrue(sem.acquire().done())
  230. self.assertEqual(0, len(sem._waiters))
  231. @gen_test
  232. def test_acquire_timeout(self):
  233. sem = locks.Semaphore(2)
  234. yield sem.acquire()
  235. yield sem.acquire()
  236. acquire = sem.acquire(timedelta(seconds=0.01))
  237. self.io_loop.call_later(0.02, sem.release) # Too late.
  238. yield gen.sleep(0.3)
  239. with self.assertRaises(gen.TimeoutError):
  240. yield acquire
  241. sem.acquire()
  242. f = sem.acquire()
  243. self.assertFalse(f.done())
  244. sem.release()
  245. self.assertTrue(f.done())
  246. @gen_test
  247. def test_acquire_timeout_preempted(self):
  248. sem = locks.Semaphore(1)
  249. yield sem.acquire()
  250. # This fires before the wait times out.
  251. self.io_loop.call_later(0.01, sem.release)
  252. acquire = sem.acquire(timedelta(seconds=0.02))
  253. yield gen.sleep(0.03)
  254. yield acquire # No TimeoutError.
  255. def test_release_unacquired(self):
  256. # Unbounded releases are allowed, and increment the semaphore's value.
  257. sem = locks.Semaphore()
  258. sem.release()
  259. sem.release()
  260. # Now the counter is 3. We can acquire three times before blocking.
  261. self.assertTrue(sem.acquire().done())
  262. self.assertTrue(sem.acquire().done())
  263. self.assertTrue(sem.acquire().done())
  264. self.assertFalse(sem.acquire().done())
  265. @gen_test
  266. def test_garbage_collection(self):
  267. # Test that timed-out waiters are occasionally cleaned from the queue.
  268. sem = locks.Semaphore(value=0)
  269. futures = [sem.acquire(timedelta(seconds=0.01)) for _ in range(101)]
  270. future = sem.acquire()
  271. self.assertEqual(102, len(sem._waiters))
  272. # Let first 101 waiters time out, triggering a collection.
  273. yield gen.sleep(0.02)
  274. self.assertEqual(1, len(sem._waiters))
  275. # Final waiter is still active.
  276. self.assertFalse(future.done())
  277. sem.release()
  278. self.assertTrue(future.done())
  279. # Prevent "Future exception was never retrieved" messages.
  280. for future in futures:
  281. self.assertRaises(TimeoutError, future.result)
  282. class SemaphoreContextManagerTest(AsyncTestCase):
  283. @gen_test
  284. def test_context_manager(self):
  285. sem = locks.Semaphore()
  286. with (yield sem.acquire()) as yielded:
  287. self.assertTrue(yielded is None)
  288. # Semaphore was released and can be acquired again.
  289. self.assertTrue(sem.acquire().done())
  290. @skipBefore35
  291. @gen_test
  292. def test_context_manager_async_await(self):
  293. # Repeat the above test using 'async with'.
  294. sem = locks.Semaphore()
  295. namespace = exec_test(globals(), locals(), """
  296. async def f():
  297. async with sem as yielded:
  298. self.assertTrue(yielded is None)
  299. """)
  300. yield namespace['f']()
  301. # Semaphore was released and can be acquired again.
  302. self.assertTrue(sem.acquire().done())
  303. @gen_test
  304. def test_context_manager_exception(self):
  305. sem = locks.Semaphore()
  306. with self.assertRaises(ZeroDivisionError):
  307. with (yield sem.acquire()):
  308. 1 / 0
  309. # Semaphore was released and can be acquired again.
  310. self.assertTrue(sem.acquire().done())
  311. @gen_test
  312. def test_context_manager_timeout(self):
  313. sem = locks.Semaphore()
  314. with (yield sem.acquire(timedelta(seconds=0.01))):
  315. pass
  316. # Semaphore was released and can be acquired again.
  317. self.assertTrue(sem.acquire().done())
  318. @gen_test
  319. def test_context_manager_timeout_error(self):
  320. sem = locks.Semaphore(value=0)
  321. with self.assertRaises(gen.TimeoutError):
  322. with (yield sem.acquire(timedelta(seconds=0.01))):
  323. pass
  324. # Counter is still 0.
  325. self.assertFalse(sem.acquire().done())
  326. @gen_test
  327. def test_context_manager_contended(self):
  328. sem = locks.Semaphore()
  329. history = []
  330. @gen.coroutine
  331. def f(index):
  332. with (yield sem.acquire()):
  333. history.append('acquired %d' % index)
  334. yield gen.sleep(0.01)
  335. history.append('release %d' % index)
  336. yield [f(i) for i in range(2)]
  337. expected_history = []
  338. for i in range(2):
  339. expected_history.extend(['acquired %d' % i, 'release %d' % i])
  340. self.assertEqual(expected_history, history)
  341. @gen_test
  342. def test_yield_sem(self):
  343. # Ensure we catch a "with (yield sem)", which should be
  344. # "with (yield sem.acquire())".
  345. with self.assertRaises(gen.BadYieldError):
  346. with (yield locks.Semaphore()):
  347. pass
  348. def test_context_manager_misuse(self):
  349. # Ensure we catch a "with sem", which should be
  350. # "with (yield sem.acquire())".
  351. with self.assertRaises(RuntimeError):
  352. with locks.Semaphore():
  353. pass
  354. class BoundedSemaphoreTest(AsyncTestCase):
  355. def test_release_unacquired(self):
  356. sem = locks.BoundedSemaphore()
  357. self.assertRaises(ValueError, sem.release)
  358. # Value is 0.
  359. sem.acquire()
  360. # Block on acquire().
  361. future = sem.acquire()
  362. self.assertFalse(future.done())
  363. sem.release()
  364. self.assertTrue(future.done())
  365. # Value is 1.
  366. sem.release()
  367. self.assertRaises(ValueError, sem.release)
  368. class LockTests(AsyncTestCase):
  369. def test_repr(self):
  370. lock = locks.Lock()
  371. # No errors.
  372. repr(lock)
  373. lock.acquire()
  374. repr(lock)
  375. def test_acquire_release(self):
  376. lock = locks.Lock()
  377. self.assertTrue(lock.acquire().done())
  378. future = lock.acquire()
  379. self.assertFalse(future.done())
  380. lock.release()
  381. self.assertTrue(future.done())
  382. @gen_test
  383. def test_acquire_fifo(self):
  384. lock = locks.Lock()
  385. self.assertTrue(lock.acquire().done())
  386. N = 5
  387. history = []
  388. @gen.coroutine
  389. def f(idx):
  390. with (yield lock.acquire()):
  391. history.append(idx)
  392. futures = [f(i) for i in range(N)]
  393. self.assertFalse(any(future.done() for future in futures))
  394. lock.release()
  395. yield futures
  396. self.assertEqual(list(range(N)), history)
  397. @skipBefore35
  398. @gen_test
  399. def test_acquire_fifo_async_with(self):
  400. # Repeat the above test using `async with lock:`
  401. # instead of `with (yield lock.acquire()):`.
  402. lock = locks.Lock()
  403. self.assertTrue(lock.acquire().done())
  404. N = 5
  405. history = []
  406. namespace = exec_test(globals(), locals(), """
  407. async def f(idx):
  408. async with lock:
  409. history.append(idx)
  410. """)
  411. futures = [namespace['f'](i) for i in range(N)]
  412. lock.release()
  413. yield futures
  414. self.assertEqual(list(range(N)), history)
  415. @gen_test
  416. def test_acquire_timeout(self):
  417. lock = locks.Lock()
  418. lock.acquire()
  419. with self.assertRaises(gen.TimeoutError):
  420. yield lock.acquire(timeout=timedelta(seconds=0.01))
  421. # Still locked.
  422. self.assertFalse(lock.acquire().done())
  423. def test_multi_release(self):
  424. lock = locks.Lock()
  425. self.assertRaises(RuntimeError, lock.release)
  426. lock.acquire()
  427. lock.release()
  428. self.assertRaises(RuntimeError, lock.release)
  429. @gen_test
  430. def test_yield_lock(self):
  431. # Ensure we catch a "with (yield lock)", which should be
  432. # "with (yield lock.acquire())".
  433. with self.assertRaises(gen.BadYieldError):
  434. with (yield locks.Lock()):
  435. pass
  436. def test_context_manager_misuse(self):
  437. # Ensure we catch a "with lock", which should be
  438. # "with (yield lock.acquire())".
  439. with self.assertRaises(RuntimeError):
  440. with locks.Lock():
  441. pass
  442. if __name__ == '__main__':
  443. unittest.main()