Reputation: 652
I'm trying to test a http call that is supposed to fail but I want to return a value. However the test I do doesn't pass in the coverage :
def callAPI(self, tokenURL:str):
requestBuilder: RequestBuilder = RequestBuilder()
try:
response = requestBuilder.get(tokenURL)
return response.json()
# return "content"
except Exception as err:
Logger.error("An error occured while trying to call API "+ err)
return None
This is my test function :
@responses.activate
def testCallDemFails():
responses.add(
responses.GET, 'http://calldem.com/api', json="{'err'}", status=500)
with pytest.raises(Exception):
demConfig = DemConfig()
resp = demConfig.callAPI('http://callAPI.com/api/1/foobar')
print("testCallAPIFail", resp)
assert resp == None
The requestBuilder.get method just return a request.get function. When I execute the function, I don't even have the testAPI fail. Do you have any ideas ?
Upvotes: 0
Views: 1076
Reputation: 608
It looks like the test function is not wiring up the request URL you are using to the response URL you are expecting. http://callAPI.com/api/1/foobar
does not match http://calldem.com/api
, nor is the test response configured as a regex match which would enable the sub-path matching that is implied by the example code. I am guessing that the response being returned by the misconfigured URL mapping is JSON parseable (or None), therefore the exception is never being raised.
If you try the following test code, does it work?:
import re
@responses.activate
def testCallDemFails():
responses.add(
responses.GET, re.compile('http://callAPI.com/api/.*'), json="{'err'}", status=500)
with pytest.raises(Exception):
demConfig = DemConfig()
resp = demConfig.callAPI('http://callAPI.com/api/1/foobar')
print("testCallAPIFail", resp)
assert resp == None
Upvotes: 1