asyncio: Locks refactor: use a separate context manager; remove Semaphore._locked.

This commit is contained in:
Guido van Rossum 2014-01-25 16:51:57 -08:00
parent ab27a9fc4b
commit ab3c88983b
2 changed files with 95 additions and 22 deletions

View file

@ -208,6 +208,24 @@ class LockTests(unittest.TestCase):
self.assertFalse(lock.locked())
def test_context_manager_cant_reuse(self):
lock = asyncio.Lock(loop=self.loop)
@asyncio.coroutine
def acquire_lock():
return (yield from lock)
# This spells "yield from lock" outside a generator.
cm = self.loop.run_until_complete(acquire_lock())
with cm:
self.assertTrue(lock.locked())
self.assertFalse(lock.locked())
with self.assertRaises(AttributeError):
with cm:
pass
def test_context_manager_no_yield(self):
lock = asyncio.Lock(loop=self.loop)
@ -219,6 +237,8 @@ class LockTests(unittest.TestCase):
str(err),
'"yield from" should be used as context manager expression')
self.assertFalse(lock.locked())
class EventTests(unittest.TestCase):
@ -655,6 +675,8 @@ class ConditionTests(unittest.TestCase):
str(err),
'"yield from" should be used as context manager expression')
self.assertFalse(cond.locked())
class SemaphoreTests(unittest.TestCase):
@ -830,6 +852,19 @@ class SemaphoreTests(unittest.TestCase):
self.assertEqual(2, sem._value)
def test_context_manager_no_yield(self):
sem = asyncio.Semaphore(2, loop=self.loop)
try:
with sem:
self.fail('RuntimeError is not raised in with expression')
except RuntimeError as err:
self.assertEqual(
str(err),
'"yield from" should be used as context manager expression')
self.assertEqual(2, sem._value)
if __name__ == '__main__':
unittest.main()