How to test try/except block with pytest and cover all exceptions

1.2k Views Asked by At

I have a function call an api to get an access token :

def get_token():
    try:
        url = 'https://call-api/accesstoken'
        token = 'authentication-token'
        headers = {"Authorization": "Bearer %s" % token}
        session = requests.Session()
        response = session.get(url, headers=headers)
        return response.json()
    except HTTPError as http_err:
        print(f'HTTP error occurred: {http_err}')
    except Exception as err:
        print(f'Other error occurred: {err}')

I want to test this function with pytest and verify the try/except block. Here is my test function :

import responses
import functions as m_functions

@responses.activate
def test_get_token():

    url = 'https://call-api/accesstoken'
    
    responses.add(responses.GET, url, 
        json = {
                "accessToken": "tmp-token1"
                })
    
    response = m_functions.get_token()
    assert response['accessToken'] == 'tmp-token1'

The part inside the block try is tested, but how to test the exceptions part ? For the moment, only part inside try block is covered by tests. I would like my code to be fully covered.

Any idea? Thanks

1

There are 1 best solutions below

0
On

As shown in the documentation, you can specify an exception as the response body for the request to trigger an exception:

responses.add(responses.GET, url, body=SomeExceptionObject(...))

Therefore, you can make two tests: one where you specify HTTPError as the exception and another tests with a different exception. You can then use the capsys fixture to capture the standard output.