V
V
Valery Ryaboshapko2015-10-11 04:54:06
Python
Valery Ryaboshapko, 2015-10-11 04:54:06

How to check in the test that there was a call to the property of the object?

There is a method that takes an object as an argument and accesses some properties (@property) of this object.

class Event:
    @property
    def number(self):
        return 123

def myFunction(event):
    return event.number * 10

How to write a test that will check if there was a call?
If it were just a method, everything would be elementary. It is enough to create a class like this:
class MockEvent:
    def __init__(self):
        self.number = Mock(return_value=10)

Pass an instance of this class as a parameter and check if the number method has been called. But I do not have a method, but a property, that is, it is not called, they are trying to read it. Accordingly, the mock magic does not work. I also tried to replace the __getattr__ and __getattribute__ methods with a mock, but this did not work, accessing an arbitrary attribute throws an AttributeError.
You can, of course, just check the result that the method returns, but I want to be sure that the result will be extracted from these properties of this particular object. Or should I not want it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
neol, 2015-10-11
@valerium

For python2:

def test_myFunction(self):
  mock_my = mock.MagicMock()
  mock_property = mock.PropertyMock(return_value=123)
  type(mock_my).number = mock_property
  myFunction(mock_my)
  mock_property.assert_called_with()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question