我正在使用MagicMock和Python 2.7来模拟对象。我正在嘲笑的其中一个类具有属性,其中一个可以在某些情况下引发TypeError
。
我想嘲笑这种行为,但我无法弄清楚如何:
del my_mock.my_property
,AttributeError
将导致my_property
,但我需要TypeError
。my_mock.my_property = MagicMock(side_effect=TypeError)
会在TypeError
被称为时导致my_property
,但仅在访问时才会导致class SingleTextInputFilter(admin.FieldListFilter):
"""
renders filter form with text input and submit button
"""
parameter_name = None
template = "admin/textinput_filter.html"
def __init__(self, field, request, params, model, model_admin, field_path):
super().__init__(field, request, params, model, model_admin, field_path)
if self.parameter_name is None:
self.parameter_name = self.field.name
if self.parameter_name in params:
value = params.pop(self.parameter_name)
self.used_parameters[self.parameter_name] = value
def queryset(self, request, queryset):
if self.value():
return queryset.filter(imei__icontains=self.value())
def value(self):
"""
Returns the value (in string format) provided in the request's
query string for this filter, if any. If the value wasn't provided then
returns None.
"""
return self.used_parameters.get(self.parameter_name, None)
def has_output(self):
return True
def expected_parameters(self):
"""
Returns the list of parameter names that are expected from the
request's query string and that will be used by this filter.
"""
return [self.parameter_name]
def choices(self, cl):
all_choice = {
'selected': self.value() is None,
'query_string': cl.get_query_string({}, [self.parameter_name]),
'display': _('All'),
}
return ({
'get_query': cl.params,
'current_value': self.value(),
'all_choice': all_choice,
'parameter_name': self.parameter_name
}, )
。我该怎么做?
答案 0 :(得分:2)
您可以将PropertyMock
用于此目的:
import mock
class A(object):
@property
def prop(self):
pass
a = A()
type(a).prop = mock.PropertyMock(side_effect=TypeError)
如果您现在访问a.prop
,则会提出TypeError
。