Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Mock side_effect on object attribute

Tags:

python

Is it possible to have a side_effect on a property? If I look at the Mock documentation it seems it's only possible on object methods.

I am trying to test the following:

def get_object(self):      try:         return self.request.user.shop     except Shop.DoesNotExist:         return None 

I want Shop to raise a DoesNotExist exception.

Guess maybe I wasn't clear enough but I am talking about the voidspace mock library.

http://www.voidspace.org.uk/python/mock/index.html

like image 883
Pickels Avatar asked Apr 24 '11 08:04

Pickels


People also ask

What is Side_effect in mock Python?

side_effect: A function to be called whenever the Mock is called. See the side_effect attribute. Useful for raising exceptions or dynamically changing return values. The function is called with the same arguments as the mock, and unless it returns DEFAULT , the return value of this function is used as the return value.

What is the difference between mock and MagicMock?

Mock vs. So what is the difference between them? MagicMock is a subclass of Mock . It contains all magic methods pre-created and ready to use (e.g. __str__ , __len__ , etc.). Therefore, you should use MagicMock when you need magic methods, and Mock if you don't need them.


1 Answers

It's worth noting that there is now the PropertyMock class:

>>> m = MagicMock() >>> p = PropertyMock(side_effect=ValueError) >>> type(m).foo = p >>> m.foo Traceback (most recent call last): .... ValueError 

That example was taken from the official site.

like image 130
Dan Passaro Avatar answered Sep 30 '22 20:09

Dan Passaro