I have a httpx.AsyncClient
that I need to use across a lot of different functions. I understood that it’s good to reuse these objects. But I’m running into a problem with reusing it that only occurs in my tests. And of course, because it occurs only in testing, I’m worried I’m missing something big that’ll explode my prod code.
Minimal example:
#in scrap.py
import asyncio, httpx
client = httpx.AsyncClient()
async def foo() -> None:
response = await client.get("https://www.example.com")
print(response.status_code)
async def main() -> None:
await foo()
await foo()
if __name__ == "__main__":
asyncio.run(main())
#in test
import pytest
from scrap import foo
pytestmark = pytest.mark.anyio
async def test_foo_1() -> None:
await foo()
async def test_foo_2() -> None:
await foo()
When I run one test, or when I run scrap.py, it’s fine. But when running more than one test, the first works and the second hits this:
self = <ProactorEventLoop running=False closed=True debug=False>
def _check_closed(self):
if self._closed:
> raise RuntimeError('Event loop is closed')
E RuntimeError: Event loop is closed
What’s the right way to reuse the client? I tried:
with client:
response = await client.get("https://www.example.com")
But that just closes it instantly.