gotgenes
gotgenes

Reputation: 40039

Assert attribute on mock instance was accessed

How can I assert that an attribute on a Mock 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?

Upvotes: 21

Views: 6451

Answers (1)

space
space

Reputation: 417

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

Upvotes: 24

Related Questions