I am testing the generating mock exception using side_effect
. based on this page https://changhsinlee.com/pytest-mock/ I am trying to generate the exception when calling load_data
method, but its not working for me.
test_load_data.py::test_slow_load_02 FAILED [100%]
tests/pytest_samples/test_load_data.py:31 (test_slow_load_02)
ds_mock = <MagicMock name='DataSet' id='4473855648'>
@patch("python_tools.pytest_samples.load_data.DataSet")
def test_slow_load_02(ds_mock):
with patch.object(ds_mock, 'load_data', side_effect=Exception('URLError')):
> with pytest.raises(Exception) as excinfo:
E Failed: DID NOT RAISE <class 'Exception'>
test_load_data.py:35: Failed
Here is the code.
slow.py
class DataSet:
def load_data(self):
return 'Loading Data'
load_data.py
from python_tools.pytest_samples.slow import DataSet
def slow_load():
dataset = DataSet()
return dataset.load_data()
test_data.py
@patch("python_tools.pytest_samples.load_data.DataSet")
def test_slow_load_02(ds_mock):
with patch.object(ds_mock, 'load_data', side_effect=Exception('URLError')):
with pytest.raises(Exception) as excinfo:
actual = slow_load()
assert str(excinfo.value) == 'URLError'
This test code worked for me:
def test_slow_load_01(mocker):
with mocker.patch("python_tools.pytest_samples.load_data.DataSet.load_data", side_effect=Exception('URLError')):
with pytest.raises(Exception) as excinfo:
actual = slow_load()
assert str(excinfo.value) == 'URLError'
I like to understand why patch and patch.object is not working.
Thanks