diff --git a/tests/test_misuse.py b/tests/test_misuse.py index 597ac9d..d4fe0fc 100644 --- a/tests/test_misuse.py +++ b/tests/test_misuse.py @@ -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 diff --git a/traio/nursery.py b/traio/nursery.py index f73a60b..2582562 100644 --- a/traio/nursery.py +++ b/traio/nursery.py @@ -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())