diff -r c8adc2c13c8b Lib/asyncio/locks.py --- a/Lib/asyncio/locks.py Wed May 13 10:58:35 2015 -0500 +++ b/Lib/asyncio/locks.py Wed May 13 12:27:25 2015 -0400 @@ -3,12 +3,16 @@ __all__ = ['Lock', 'Event', 'Condition', 'Semaphore', 'BoundedSemaphore'] import collections +import sys from . import events from . import futures from .coroutines import coroutine +_PY35 = sys.version_info >= (3, 5) + + class _ContextManager: """Context manager. @@ -179,6 +183,16 @@ yield from self.acquire() return _ContextManager(self) + if _PY35: + @coroutine + def __aenter__(self): + yield from self.acquire() + return self + + @coroutine + def __aexit__(self, exc_type, exc, tb): + self.release() + class Event: """Asynchronous equivalent to threading.Event. @@ -369,6 +383,16 @@ yield from self.acquire() return _ContextManager(self) + if _PY35: + @coroutine + def __aenter__(self): + yield from self.acquire() + return self + + @coroutine + def __aexit__(self, exc_type, exc, tb): + self.release() + class Semaphore: """A Semaphore implementation. @@ -454,6 +478,16 @@ yield from self.acquire() return _ContextManager(self) + if _PY35: + @coroutine + def __aenter__(self): + yield from self.acquire() + return self + + @coroutine + def __aexit__(self, exc_type, exc, tb): + self.release() + class BoundedSemaphore(Semaphore): """A bounded semaphore implementation. diff -r c8adc2c13c8b Lib/test/test_asyncio/test_pep492.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Lib/test/test_asyncio/test_pep492.py Wed May 13 12:27:25 2015 -0400 @@ -0,0 +1,46 @@ +"""Tests support for new syntax introduced by PEP 492.""" + +import unittest +from unittest import mock + +import asyncio +from asyncio import test_utils + + +class BaseTest(test_utils.TestCase): + + def setUp(self): + self.loop = asyncio.BaseEventLoop() + self.loop._process_events = mock.Mock() + self.loop._selector = mock.Mock() + self.loop._selector.select.return_value = () + self.set_event_loop(self.loop) + + +class LockTests(BaseTest): + + def test_context_manager(self): + primitives = [ + asyncio.Lock(loop=self.loop), + asyncio.Condition(loop=self.loop), + asyncio.Semaphore(loop=self.loop), + asyncio.BoundedSemaphore(loop=self.loop), + ] + + async def test(lock): + await asyncio.sleep(0.01, loop=self.loop) + self.assertFalse(lock.locked()) + async with lock as _lock: + self.assertIs(lock, _lock) + self.assertTrue(lock.locked()) + await asyncio.sleep(0.01, loop=self.loop) + self.assertTrue(lock.locked()) + self.assertFalse(lock.locked()) + + for primitive in primitives: + self.loop.run_until_complete(test(primitive)) + self.assertFalse(primitive.locked()) + + +if __name__ == '__main__': + unittest.main()