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
As shown in the documentation, you can specify an exception as the response body for the request to trigger an exception:
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 thecapsys
fixture to capture the standard output.