I'm using the pytest-mock wrapper with pytest.
I can't get a PropertyMock to work with the requests package.
Here's an example of a function I'm trying to unit test:
def get():
url = f'http://foo.bar/'
response = requests.get(url)
if response.status_code != 200:
sys.exit(1)
return response.text
And here's my attempt at a unit test:
import pytest
import my_module
import requests
def test_get(mocker, monkeypatch):
response_mock = mocker.MagicMock()
status_code_mock = mocker.PropertyMock(return_value=200)
text_mock = mocker.PropertyMock(return_value='xyz')
type(response_mock).status_code = status_code_mock
type(response_mock).text = text_mock
monkeypatch.setattr(requests, 'get', response_mock)
my_module.get()
The test fails because 200 is not returned by response.status_code
.
I tried putting a PDB breakpoint after the requests.get()
call, and checked the response.status_code attribute myself in PDB. I get a MagicMock object:
(Pdb) response.status_code
<MagicMock name='mock().status_code' id='4487925656'>