9
votes

My code is as following:

import pytest
import requests
from unittest import mock

@mock.patch('requests.get')
def test_verify(mock_request):
    mock_resp = mock.Mock()
    mock_resp.status_code = 404

    mock_request.return_value = mock_resp
    r = requests.get()

    with pytest.raises(requests.exceptions.HTTPError) as err_msg:
        r.raise_for_status()
    print(err_msg)

Since the status code of response is set to 404, I expect that a HTTPError will be raised. However, there is an error stating

Failed: DID NOT RAISE <class 'requests.exceptions.HTTPError'>

The output is as following:

======================================== test session starts ======================================== platform darwin -- Python 3.6.4, pytest-3.7.0, py-1.5.2, pluggy-0.7.1 rootdir: /Users/michael/Code/youtube-data-api, inifile: plugins: requests-mock-1.5.2 collected 1 item

temp_test.py F
[100%]

============================================= FAILURES ============================================== ____________________________________________ test_verify ____________________________________________

mock_request =

@mock.patch('requests.get')
def test_verify(mock_request):
    mock_resp = mock.Mock()
    mock_resp.status_code = 404

    mock_request.return_value = mock_resp
    r = requests.get()
    #print(r.status_code)

    with pytest.raises(requests.exceptions.HTTPError) as err_msg:
       r.raise_for_status() E           Failed: DID NOT RAISE <class 'requests.exceptions.HTTPError'>

temp_test.py:15: Failed ===================================== 1 failed in 0.12 seconds ======================================

terminal output: terminal output

1
Please copy and paste the output instead of giving a screenshot. - Spinor8

1 Answers

9
votes

mock_resp is a mock.Mock() object. Calling raise_for_status() is just going to return another Mock().

You'll need to use a response that preserves the original raise_for_status(). Try this:

import pytest
import requests
from unittest import mock

@mock.patch('requests.get')
def test_verify(mock_request):
    mock_resp = requests.models.Response()
    mock_resp.status_code = 404
    mock_request.return_value = mock_resp
    res = requests.get()
    with pytest.raises(requests.exceptions.HTTPError) as err_msg:
        res.raise_for_status()
    print(err_msg)