Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Mock a missing attribute

Tags:

python

mocking

I have a line of code that is:

if not hasattr(class.a, u'c'):
    return

How do I mock out class so that class.a.c returns False for hasattr?

If I do this:

>>> from mock import MagicMock
>>> mock_class = MagicMock(spec=[u'a'])
>>> hasattr(mock_class, u'a')
True
>>> hasattr(mock_class, u'b')
False
>>> hasattr(mock_class.a, u'c')
True

Although I dont spec class.a.c, its being mocked!!!

like image 583
Philip Ridout Avatar asked Jul 19 '13 19:07

Philip Ridout


1 Answers

You can delete the attribute, which will cause hasattr to return False.

From the Documentation:

>>> mock = MagicMock()
>>> hasattr(mock, 'm')
True
>>> del mock.m
>>> hasattr(mock, 'm')
False
>>> del mock.f
>>> mock.f
Traceback (most recent call last):
    ...
AttributeError: f

For your specific example, since mock_class.a is another Mock, you can do del mock_class.a.c.

like image 151
Kyle Avatar answered Oct 07 '22 10:10

Kyle