Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 959
gotgenes Avatar asked Oct 02 '13 21:10

gotgenes


1 Answers

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()
like image 65
space Avatar answered Oct 21 '22 01:10

space