Reputation: 333
I'm trying to mock a function that makes an API call using mocker patch. However, it doesn't work, not even in this simple example. The class_abcd.process_weather() uses the actual get_weather() as opposed to the mocked one.
The directory structure is the following:
-source
-sub
-using_output.py
-weather_api.py
using_output.py
from source.weather_api import get_weather
class abcd():
def process_weather(self):
weather = get_weather()
return "processed " + weather
weather_api.py
def get_weather():
return "weather"
I'm trying to test the process_weather and faking the get_weather from the weather api.
from pytest_mock import mocker
def test_weather_in_batch(mocker):
# Setup
fake_weather = "fake_weather"
# Actual
class_abcd = abcd()
mocker.patch('weather_api.get_weather', return_value=fake_weather)
actual = class_abcd.process_weather()
# Expected
expected = "processed " + "fake_weather"
# Asset
assert expected == actual
Upvotes: 0
Views: 1943
Reputation: 1403
When using mock, you need to specify what import you want to patch, not the underlying module/function.
from pytest_mock import mocker
def test_weather_in_batch(mocker):
# Setup
fake_weather = "fake_weather"
# Actual
class_abcd = abcd()
mocker.patch('source.sub.using_output.get_weather', return_value=fake_weather)
actual = class_abcd.process_weather()
# Expected
expected = "processed " + "fake_weather"
# Asset
assert expected == actual
In your case you are importing get_weather
into using_output.py
.
Because you want the use the mocked version of get_weather
in using_output.py
, this is what you need to patch.
Upvotes: 1