diff --git a/nonebot/drivers/aiohttp.py b/nonebot/drivers/aiohttp.py index b12d204b..6b437e22 100644 --- a/nonebot/drivers/aiohttp.py +++ b/nonebot/drivers/aiohttp.py @@ -124,6 +124,8 @@ class Session(HTTPClientSession): @override async def setup(self) -> None: + if self._client is not None: + raise RuntimeError("Session has already been initialized") self._client = aiohttp.ClientSession( cookies=self._cookies, headers=self._headers, diff --git a/nonebot/drivers/httpx.py b/nonebot/drivers/httpx.py index 8300323b..68eed464 100644 --- a/nonebot/drivers/httpx.py +++ b/nonebot/drivers/httpx.py @@ -93,6 +93,8 @@ class Session(HTTPClientSession): @override async def setup(self) -> None: + if self._client is not None: + raise RuntimeError("Session has already been initialized") self._client = httpx.AsyncClient( params=self._params, headers=self._headers, diff --git a/tests/test_driver.py b/tests/test_driver.py index 546cfeec..636e02c3 100644 --- a/tests/test_driver.py +++ b/tests/test_driver.py @@ -328,6 +328,11 @@ async def test_http_client_session(driver: Driver, server_url: URL): with pytest.raises(RuntimeError): await session.request(request) + with pytest.raises(RuntimeError): # noqa: PT012 + async with session: + async with session: + ... + async with session as session: # simple post with query, headers, cookies and content request = Request(