Reputation: 3042
I am struggling to understand how to stub a class / mock all the methods from a class dependency in Python & pytest. The listing below shows the class that I am testing. It has two internal dependencies: OWMProxy
and PyOwmDeserializer
.
Class Under Test
class OWM:
def __init__(self, api_key: str, units: WeatherUnits) -> None:
self._api_key = api_key
self._units = units
self._pyorm = OWMProxy.from_api_key(api_key)
self._deserializer = PyOwmDeserializer()
def at(self, city: str, iso_datetime: str) -> ForecastModel:
weather = self._pyorm.for_time(city, iso_datetime)
return self._deserializer.deserialize(weather, self._units)
def day(self, city: str, day: str) -> ForecastModel:
weather = self._pyorm.for_day(city, day)
return self._deserializer.deserialize(weather, self._units)
def now(self, city: str) -> ForecastModel:
weather = self._pyorm.now(city)
return self._deserializer.deserialize(weather, self._units)
My question is, is it possible to mock an entire class dependency when unit test with PyTest?
Currently, the unit test that I have uses mocker to mock each class method, including init method.
I could use a dependency injection approach, i.e. create an interface for the internal deserializer and proxy interface and add these interfaces to the constructor of the class under test.
Alternatively I could test using unittest.mock
module, as suggested here. Is there an equivalent functionality in pytest-mock
???
Unit Test So Far...
@pytest.mark.skip(reason="not implemented")
def test_owm_initialises_deserializer(
default_weather_units: WeatherUnits, mocker: MockFixture
) -> None:
api_key = "test_api_key"
proxy = OWMProxy(py_OWM(api_key))
patch_proxy = mocker.patch(
"wayhome_weather_api.openweathermap.client.OWMProxy.from_api_key",
return_value=proxy,
)
patch_val = mocker.patch(
"wayhome_weather_api.openweathermap.deserializers.PyOwmDeserializer",
"__init__",
return_value=None,
)
owm = OWM(api_key, default_weather_units)
assert owm is not None
Upvotes: 1
Views: 8866
Reputation: 10709
You can just mock the whole class and control the return values and/or side effects of its methods as how its done in the docs.
>>> def some_function(): ... instance = module.Foo() ... return instance.method() ... >>> with patch('module.Foo') as mock: ... instance = mock.return_value ... instance.method.return_value = 'the result' ... result = some_function() ... assert result == 'the result'
Assuming the class under test is located in src.py.
test_owm.py
import pytest
from pytest_mock.plugin import MockerFixture
from src import OWM, WeatherUnits
@pytest.fixture
def default_weather_units():
return 40
def test_owm_mock(
default_weather_units: WeatherUnits, mocker: MockerFixture
) -> None:
api_key = "test_api_key"
# Note that you have to mock the version of the class that is defined/imported in the target source code to run. So here, if the OWM class is located in src.py, then mock its definition/import of src.OWMProxy and src.PyOwmDeserializer
patch_proxy = mocker.patch("src.OWMProxy.from_api_key")
patch_val = mocker.patch("src.PyOwmDeserializer")
owm = OWM(api_key, default_weather_units)
assert owm is not None
# Default patch
print("Default patch:", owm.day("Manila", "Today"))
# Customizing the return value
patch_proxy.return_value.for_day.return_value = "Sunny"
patch_val.return_value.deserialize.return_value = "Really Sunny"
print("Custom return value:", owm.day("Manila", "Today"))
patch_proxy.return_value.for_day.assert_called_with("Manila", "Today")
patch_val.return_value.deserialize.assert_called_with("Sunny", default_weather_units)
# Customizing the side effect
patch_proxy.return_value.for_day.side_effect = lambda city, day: f"{day} in hot {city}"
patch_val.return_value.deserialize.side_effect = lambda weather, units: f"{weather} is {units} deg celsius"
print("Custom side effect:", owm.day("Manila", "Today"))
patch_proxy.return_value.for_day.assert_called_with("Manila", "Today")
patch_val.return_value.deserialize.assert_called_with("Today in hot Manila", default_weather_units)
def test_owm_stub(
default_weather_units: WeatherUnits, mocker: MockerFixture
) -> None:
api_key = "test_api_key"
class OWMProxyStub:
@staticmethod
def from_api_key(api_key):
return OWMProxyStub()
def for_day(self, city, day):
return f"{day} in hot {city}"
class PyOwmDeserializerStub:
def deserialize(self, weather, units):
return f"{weather} is {units} deg celsius"
patch_proxy = mocker.patch("src.OWMProxy", OWMProxyStub)
patch_val = mocker.patch("src.PyOwmDeserializer", PyOwmDeserializerStub)
owm = OWM(api_key, default_weather_units)
assert owm is not None
# Default patch
print("Default patch:", owm.day("Manila", "Today"))
# If you want to assert the calls made as did in the first test above, you can use the mocker.spy() functionality
Output
$ pytest -q -rP
================================================================================================= PASSES ==================================================================================================
______________________________________________________________________________________________ test_owm_mock ______________________________________________________________________________________________
------------------------------------------------------------------------------------------ Captured stdout call -------------------------------------------------------------------------------------------
Default patch: <MagicMock name='PyOwmDeserializer().deserialize()' id='139838844832256'>
Custom return value: Really Sunny
Custom side effect: Today in hot Manila is 40 deg celsius
______________________________________________________________________________________________ test_owm_stub ______________________________________________________________________________________________
------------------------------------------------------------------------------------------ Captured stdout call -------------------------------------------------------------------------------------------
Default patch: Today in hot Manila is 40 deg celsius
2 passed in 0.06s
As you can see, we are able to control the return values of the methods of the mocked dependencies.
Upvotes: 3