Reputation: 186
I'm trying to mock out my requests.get to have a status code of 200
and make history[0].status_code
trigger an IndexError
(since there were no redirects). I'm able to get status_code
to return 200
, but when I mock out history with the desired side effect, the IndexError
is not triggered.
@patch('requests.get')
def test_no_redirect(self, mock_requests):
mock_requests.return_value.status_code = 200
mock_requests.history[0].status_code.side_effect = IndexError()
response = requests.get('example.com')
self.assertRaises(IndexError, response.history[0].status_code)
self.assertTrue(200, response.status_code)
Upvotes: 2
Views: 3307
Reputation: 2862
Ok, I checked the code and I'd like to mention a few things.
First of all assertRises
method receives callable as the second parameter ;)
Its definition looks like this
def assertRaises(self, excClass, callableObj=None, *args, **kwargs):
The second thing, if you are mocking status_code
using
mock_requests.return_value.status_code = 200
why not to try the same with history:
mock_requests.return_value.history = []
We are using the real list instead of some kind of mock, so I think that it's even better. The test method could look like this:
@patch('requests.get')
def test_no_redirect(self, mock_requests):
mock_requests.return_value.status_code = 200
mock_requests.return_value.history = []
mock_requests.history[0].status_code.side_effect = IndexError
response = requests.get('example.com')
self.assertRaises(IndexError, lambda: response.history[0])
self.assertTrue(200, response.status_code)
Upvotes: 3