mercredi 30 décembre 2020

Pytest: How to mock a class method inside a for loop?

I have a method class method which is inside a for loop that I would like to mock using pytest. The method has some default named arguments.

Here is something I have tried:

import pytest
import my_module

def test_dummy_method(monkeypatch):
    
    def mockreturn(**kwargs):
        
        dummy_mocked_values = [1, 2, 3]
        
        for val in dummy_mocked_values:
            yield val

    dummy_mock = mockreturn()
    monkeypatch.setattr(my_module, 'dummy_method', lambda x: next(dummy_mock))

    list_return_values = []
    
    for i in range(3):
        result_ = my_module.dummy_method(dummy_arg_1="foo", dummy_arg_2=42) # here, I am expecting result_ to be 1, 2 and 3 successively...
        list_return_values.append(result_)
    
    assert list_return_values == [1, 2, 3]
    

But I am getting the following error:

FAILED dummy_repo/tests/test_dummy_method.py::test_dummy_method- TypeError: <lambda>() got an unexpected keyword argument 'dummy_arg_1'

because the signature of the lambda function does not match the mock dummy_method to be testes

How can I use monkeypatch.setattr to yield different values from a mocked method on each call in a pythonic and clean way?

I know that one can do that with MagickMock but if possible I would like to use only pytest.

Thanks!

Aucun commentaire:

Enregistrer un commentaire