gotgenes gotgenes - 2 months ago 6
Python Question

Assert attribute on mock instance was accessed

How can I assert that an attribute on a

and/or a
MagicMock
was accessed?

For example,

from unittest.mock import MagicMock

def foo(x):
a = x.value

m = MagicMock()
foo(m)
m.attr_accessed('value') # method that does not exist but I wish did; should return True


What is an actual way to check that
foo
attempted to access
m.value
?

Answer

You can use PropertyMock as described here.

e.g.,

from unittest.mock import MagicMock, PropertyMock

def foo(x):
    a = x.value

m = MagicMock()
p = PropertyMock()
type(m).value = p
foo(m)
p.assert_called_once_with()
Comments