locks_test.py 17 KB

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