Quantcast
Channel: Python Mock object with method called multiple times - Stack Overflow
Viewing all articles
Browse latest Browse all 6

Answer by Douglas Morais for Python Mock object with method called multiple times

$
0
0

You can use Side Effect + Dict Dispatch Pattern for a more clean code:

For example (using async, ignore future objects for non async cases)

@pytest.fixture()def mock_fixture(mocker):    # dict to switch results from diferent results    target_function_args_x_results = {'foo': 'result_1','bar': 'result_2','xyz': 'result_3',    }    def function_mock_side_effect(*args, **kwargs):        future = asyncio.Future()        argument_received = args[0] # ex: ... my_function('foo')        mock_result = target_function_args_x_results.get(argument_received, {}) # Dict Dispatch Pattern        future.set_result(mock_result)        return future    mocker.patch("src.app.my_module.my_target_function",                 side_effect=function_mock_side_effect)

Viewing all articles
Browse latest Browse all 6

Trending Articles