Reputation: 1699
I'm making a wrapper for an api. I wanted the function to return a custom exception message upon invalid input.
def scrape(date, x, y):
response = requests.post(api_url, json={'date': date, 'x': x, 'y': y})
if response.status_code == 200:
output = loads(response.content.decode('utf-8'))
return output
else:
raise Exception('Invalid input')
This is the test for it:
from scrape import scrape
def test_scrape():
with pytest.raises(Exception) as e:
assert scrape(date='test', x=0, y=0)
assert str(e.value) == 'Invalid input'
But the coverage tests skips the last line for some reason. Does anyone know why? I tried changing the code to with pytest.raises(Exception, match = 'Invalid input') as e
, but i get an error:
AssertionError: Pattern 'Invalid input' not found in "date data 'test' does not match format '%Y-%m-%d %H:%M:%S'"
Does it mean it's actually referencing the exception message from the api instead of my wrapper?
Upvotes: 0
Views: 1470
Reputation: 375574
Your scrape function raises an exception, so the line after the function call won't execute. You can put that last assert outside the pytest.raises clause, like this:
from scrape import scrape
def test_scrape():
with pytest.raises(Exception) as e:
assert scrape(date='test', x=0, y=0)
assert str(e.value) == 'Invalid input'
Upvotes: 0
Reputation: 96
It does not get to your second assertion because of the raised exception. What you can do is assert it's value this way:
def test_scrape():
with pytest.raises(Exception, match='Invalid input') as e:
assert scrape(date='test', x=0, y=0)
I would say you get an error "AssertionError: Pattern 'Invalid input' not found in "date data 'test' does not match format '%Y-%m-%d %H:%M:%S'" when the response code is 200 - so there is no exception raised.
Upvotes: 1