Pytest @patch return different values like @parametrize

Question:

I’m currently writing some tests for my python program and I have a scenario where I need to patch a method but want to run the test multiple times with different return values.

For example. Below is the basic use case. There is a method that is called in the class_to_patch class that makes a call to an external API and for this test case I want to mock the return value (below I have mocked the return value as "x").

@patch(
    "class_to_patch.method_to_patch",
    return_value="x"
    autospec=True,
)
def test_method(mock_method_to_patch):
    val = class_to_patch()
    assert val == 1

Is it possible to be able to run the test multiple times with different return values for method_to_patch, ie if I want to run the test with it returning "x" and then one where it returns "y"?

@pytest.mark.parametrize("param", ["x", "y"])

Something like parametrize but for the return value.

Any help would be greatly appreciated and if I need to provide any further details please let me know.

Asked By: rick_grimes

||

Answers:

You can assign the return_value (unittest.mock.Mock.return_value) in the test (while using parametrize). Something like:

@pytest.mark.parametrize("param", ["x", "y"])
@patch(
    "class_to_patch.method_to_patch",
    autospec=True,
)
def test_method(mock_method_to_patch, param):
    mock_method_to_patch.return_value = param
    val = class_to_patch()
    assert val == 1
Answered By: Ed Kloczko
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.