0

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
1

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.