1

Based on this blog post https://changhsinlee.com/pytest-mock/, trying to mock the object method call. But its giving the error for me.

tests/pytest_samples/test_load_data.py:5 (test_slow_load)
mocker = <pytest_mock.plugin.MockerFixture object at 0x10536b940>

    def test_slow_load(mocker):
        assert "Data" in slow_load()
    
        expected = 'mock load'
    
        def mock_load():
            return 'mock load'
    
        mocker.patch("python_tools.pytest_samples.load_data.DataSet.load_data", mock_load())
>       actual = slow_load()

test_load_data.py:15: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

    def slow_load():
        dataset = DataSet()
>       return dataset.load_data()
E       TypeError: 'str' object is not callable

../../src/python_tools/pytest_samples/load_data.py:6: TypeError

Here is the file name and test code: module name python_tools folder name pytest_samples. This test needs pytest-mock python module to run the test.

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_load_data.py

from python_tools.pytest_samples.load_data import slow_load


def test_slow_load():
    assert "Data" in slow_load()


def test_slow_load(mocker):
    assert "Data" in slow_load()

    expected = 'mock load'

    def mock_load():
        return 'mock load'

    mocker.patch("python_tools.pytest_samples.load_data.DataSet.load_data", mock_load())
    actual = slow_load()
    assert actual == expected

Can you help me understand why its giving this error message?

Thanks

sfgroups
  • 18,151
  • 28
  • 132
  • 204
  • 3
    You're passing in the result of `mock_load()` to `patch()` and not the object itself. So, it's patching the method with `'mock load'` (a string) and not `mock_load` (a callable function). It should be `mocker.patch("python_tools.pytest_samples.load_data.DataSet.load_data", mock_load)`. – Axe319 Jan 06 '23 at 02:06

1 Answers1

1

As per Axe comment, I have updated my code like this, its working now

def test_slow_load(mocker):
    assert "Data" in slow_load()

    expected = 'mock load'

    def mock_load(self):
        return 'mock load'

    mocker.patch("python_tools.pytest_samples.load_data.DataSet.load_data", mock_load)
    actual = slow_load()
    assert actual == expected
sfgroups
  • 18,151
  • 28
  • 132
  • 204