0

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

  • It's hard to answer this question without knowing what params are available to your test. i.e. What are the values in your env file. I think your test might be passing the incorrect values to the url. – theundeadmonk Dec 28 '22 at 21:24
  • OK your comment made me realize how to solve this. The environment variables weren't passed correctly when testing. I moved the api_key and client_key variables out of the function and defined them at the start of the test with ```load_dotenv() TENOR_API = os.getenv('TENOR_API_KEY') TENOR_CLIENT = os.getenv('TENOR_API_CLIENT') gif = await get_gif(TENOR_API, TENOR_CLIENT)``` and now the function seems to be working and passing my test. I don't understand why the environment variables weren't defined when calling the function in the test, but it now works regardless. thank you! – Ethan Ansel-Kelly Dec 28 '22 at 22:57

1 Answers1

0

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

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 29 '22 at 07:54