James
James

Reputation: 1260

Python:How to implement multiple dynamic mock.patch functions?

I am trying to dynamically mock/patch multiple @property methods of a class in python i.e.

class Dog():
     ...

     @property
     def size(self):
        .....

     @property
     def breed(self):
        .....


cases = [{"size":9, "breed":"doberman"}, {"size":2, "breed":"pug"}]

@pytest.mark.parametrize("case", list(cases.values()), ids=list(cases.keys()))
def test_properties(case):

    dog = Dog()
    mocks = ()

    for m, v in case.items():
       mocks += (mock.patch.object(dog, m, return_value=v),)

    with mocks:
        ...

However, I get the following error:

      with mocks:

E AttributeError: enter

Clearly this is not the appropriate method of mocking multiple properties according to a config as shown above? Could someone please advise me on how to best achieve this, thanks!

Upvotes: 2

Views: 1623

Answers (2)

James
James

Reputation: 1260

Apart from the answer from Alex, the following solved it:

if "mock" in case:
        for m,v in case["mock"].items():
            def get_value(self):return v
            monkeypatch.setattr(State, m, property(get_value))

Upvotes: 0

Alex Grönholm
Alex Grönholm

Reputation: 5901

The easiest option for you would be using contextlib.ExitStack: https://docs.python.org/3/library/contextlib.html#supporting-a-variable-number-of-context-managers

Another option would be using pytest's monkeypatch fixture: https://docs.pytest.org/en/latest/monkeypatch.html

Upvotes: 1

Related Questions