how to unit test an async function in python with pytest-asyncio?

989 Views Asked by At

I have an async function that makes a request to the Tenor API. The function gets called/awaited in another function, r.status_code == 200 is True and the function returns the specified gif as a str, but when trying to test the function it no longer works. I'm pretty new to Python so I think I'm not using async/await or the requests library correctly, but I don't know how to fix this error.

this is the function:

async def get_gif():
    api_key = os.getenv('TENOR_API_KEY')
    client_key = os.getenv('TENOR_API_CLIENT')

    r = requests.get(
        f"https://tenor.googleapis.com/v2/search?q={get_gif_params()}&key={api_key}&client_key={client_key}&limit=1"
    )

    if r.status_code == 200:
        gif = json.loads(r.content)[
            'results'][0]["media_formats"]["mediumgif"]['url']
        return gif

this returns a str ending in '.gif'.

this is the unit test:

@pytest.mark.asyncio
async def test_gif():
    gif = await get_gif()
    assert type(gif) == str

I've tried using pytest-asyncio to write an asynchronous unit test per the documentation, and expected the test to await the function before asserting the return value.

When testing, the request status code is 400 and the return is None. I'm not sure how to change my function or test so that the unit test properly awaits the return str

1

There are 1 best solutions below

1
On BEST ANSWER

The original way I wrote my function meant that the environment variables were not being passed when get_gif() was called in the test function. The solution was to refactor get_gif() so that the environment variables were declared outside of the function and then passed to the function as params