2

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!

2
  • cases.values()? it is a list of dict Commented Sep 25, 2019 at 2:06
  • pytest iterates over each case Commented Sep 25, 2019 at 17:06

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.