[英]Django model field validator is not raising an Exception as it should
I have the following model in models.py
: 我在
models.py
有以下模型:
@python_2_unicode_compatible
class Session(ModelCommon): # ModelCommon is an abstract Model which extends from models.Model with the fields name(CharField) and enabled(BooleanField).
"""
Model Session with foreign key to Model Event.
"""
event = models.ForeignKey(verbose_name=_('Event'), to=Event, default=None, null=False, blank=False)
start_datetime = models.DateTimeField(verbose_name=_('Session Starts'), default=None, null=False, blank=False)
end_datetime = models.DateTimeField(verbose_name=_('Session Ends'), default=None, null=False, blank=False)
available = models.BooleanField(verbose_name=_('Available'), default=True, null=False, blank=False)
price = models.DecimalField(verbose_name=_('Price'), max_digits=10, decimal_places=2,
validators=[MinValueValidator(0.00)],
default=None, null=False, blank=False)
When I test my Model that it shouldn't be saved in Database if price
is negative, it doesn't raise an Exception as it should. 当我测试我的模型时,如果
price
是负数,它不应该保存在数据库中,它不会引发异常。
test_models.py
: test_models.py
:
class SessionTestCase(TestCase):
"""
Case of tests for Model Session.
"""
def setUpTestData(cls):
"""
This method is used to declare dummy data that could be used by all tests.
"""
cls.test_event = Event(name='Test Event Name for Session', enabled=True)
cls.test_event.save()
def setUp(self):
"""
This method is used to run code before each test.
"""
self.session = Session(event=self.test_event, name='Session No1', enabled=True,
start_datetime=timezone.now() + timedelta(days=1),
end_datetime=timezone.now() + timedelta(days=3), price=0)
def test_session_price_cannot_be_negative(self):
"""
:return: Passed if Session object with negative price raises Exception.
"""
self.session.price = -20.0
self.assertRaises(Exception, lambda: self.session.save())
Finally, as I run my test_models.py
, I get the following message: 最后,当我运行我的
test_models.py
,我收到以下消息:
Failure
Traceback (most recent call last):
self.assertRaises(Exception, lambda: self.session.save())
AssertionError: Exception not raised
Calling save()
does not trigger validation. 调用
save()
不会触发验证。 See the Django docs on validating objects for more info. 有关更多信息,请参阅有关验证对象的Django文档。 You could call
full_clean
instead. 你可以改为调用
full_clean
。
self.session.price = -20.0
self.assertRaises(Exception, lambda: self.session.full_clean())
Note that you can remove the lambda from your code and pass the callable. 请注意,您可以从代码中删除lambda并传递callable。 It would also be better to catch the more specific
ValidationError
rather than Exception
. 捕获更具体的
ValidationError
而不是Exception
也会更好。
self.session.price = -20.0
self.assertRaises(ValidationError, self.session.full_clean)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.