0

How can we capture the print statement within an except when the exception is mocked?

In the example below, I am mocking the make_request_and_get_response using side_effect. Then, using the pytest.raises I assert that this exception was raised. But, when trying to assert that the corresponding print statement is being output by using capsys to capture it, nothing is captured.

Am I correct to expect that since I am mocking the exception the corresponding print statement will be executed?

import pytest
from unittest import mock
from foo.main import get_response_from_external_api

def test_url_error(capsys):
    mock_query = mock.Mock()
    mock_query.make_request_and_get_response.side_effect = Exception('HTTPError')

    with pytest.raises(Exception) as excinfo:
        get_response_from_external_api(mock_query)

    assert str(excinfo.value) == 'HTTPError '

    out, err = capsys.readouterr()
    assert "Got a HTTPError" in out  # AssertionError

query.py

from foo.query import *

def get_response_from_external_api(query):
    response = 0

    try:
        response = query.make_request_and_get_response()
    except urllib.error.HTTPError as e:
        print('Got a HTTPError: ', e)

    return response

if __name__ == "__main__":    
    query = Query('input A', 'input B')
    result = get_response_from_external_api(query)
    return result

main.py

from foo.query import *

def get_response_from_external_api(query):
    response = 0

    try:
        response = query.make_request_and_get_response()
    except urllib.error.HTTPError as e:
        print('Got a HTTPError: ', e)

    return response

if __name__ == "__main__":    
    query = Query('input A', 'input B')
    result = get_response_from_external_api(query)
    return resul
timmy78h
  • 183
  • 1
  • 3
  • 10
  • Your function captures only `HTTPError`s, but your mock is raising an `Exception`. Since it is not captured, the print line is not invoked. – hoefling Nov 18 '19 at 09:23
  • @hoefling I thought the string within the `Exception` specified the specific exception. Could you please help me on how the syntax would look like so that the mock raises an `HTTPError`? I tried importing `urllib.error.HTTPError` and replaced `Exception('HTTPError')` with `HTTPError()` but now I get a `failed: did not raise` error. – timmy78h Nov 18 '19 at 10:56

0 Answers0