Skip to content

Commit

Permalink
Protect Nursery against calls as sync ctx manager
Browse files Browse the repository at this point in the history
  • Loading branch information
RouquinBlanc committed Nov 6, 2018
1 parent f8c37b2 commit b583754
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
8 changes: 8 additions & 0 deletions tests/test_misuse.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,11 @@ async def test_task_not_awaitable(arg):
with pytest.raises(OSError):
async with Nursery() as n:
n.start_soon(arg)


@pytest.mark.asyncio
async def test_sync_ctx_manager():
"""Calling nursery as a synchronous context manager"""
with pytest.raises(RuntimeError):
with Nursery():
pass
9 changes: 9 additions & 0 deletions traio/nursery.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,15 @@ async def __aexit__(self, exc_type, exc_val, exc_tb):
self.cancel(exc_val)
await self.join()

def __enter__(self):
"""Protect against calling as regular context manager"""
raise RuntimeError(
"asynchronous context manager, use 'async with Nursery(...)'!"
)

def __exit__(self, *_): # pragma: no cover
assert False, 'This should never be called'

async def _timeout_handler(self):
await asyncio.sleep(self.timeout)
self.cancel(TimeoutError())
Expand Down

0 comments on commit b583754

Please sign in to comment.