How to handle AioHttpClient in Pytest?

76 Views Asked by At

I am writing my first test (unit test with Pytest), that contains AioHttpClient with BasicAuth (with username and poassword). My function's structure:

async def example_function(some parameters):
    (...)
    try:
        synth_url = os.getenv("SYNTH_URL", 'https://...')
        async with AioHttpClient.session().post(synth_url, data=data_in, auth=aiohttp.BasicAuth(
                'username', os.getenv("MY_PASSWORD"))) as resp:
            if resp.ok:
                return await resp.read()
            else:
                (...)

What is the best practice when testing such function? I have tried to use monkeypatch or mock the AioHttpClient but without any success so far. Thank you.

1

There are 1 best solutions below

0
On

You should use aioresponses which is meant for this.

A basic test example could be:

from aioresponses import aioresponses


async def test_example_function():
    with aioresponses() as m:
        m.post(os.getenv("SYNTH_URL", 'https://...'), body='your desired response')
        response = example_function(some parameters)
        assert response == 'your desired response'

You can read more in the official documentation.