17

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!!!

2
  • 2
    Why not removing it with delattr? Commented Jul 19, 2013 at 19:38
  • 1
    I used: del mock_class.a.c in the end. Thanks! Commented Jul 20, 2013 at 6:23

2 Answers 2

11

Actually mock_class.a will create another MagicMock, which don't have a spec. The only way I can think of is to assign the attribute a of the mock_class with another MagicMock with spec, like this:

mock_class = MagicMock(spec=[u'a']) mock_class.a = MagicMock(spec=[u'a']) hasattr(mock_class.a, u'c') # returns False 

Also if you have some real objects you want to mock, there is a possibility to do some recursive autospecing.

Sign up to request clarification or add additional context in comments.

1 Comment

I could have sworn I tried this but it didn't work, but trying your example worked!
8

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.