2016-11-05 21:12:12 +08:00
|
|
|
from django.db import IntegrityError, models
|
|
|
|
from django.test import TestCase, skipUnlessDBFeature
|
|
|
|
|
|
|
|
from .models import Product
|
|
|
|
|
|
|
|
|
|
|
|
class CheckConstraintTests(TestCase):
|
|
|
|
def test_repr(self):
|
2018-08-06 10:15:10 +08:00
|
|
|
check = models.Q(price__gt=models.F('discounted_price'))
|
2016-11-05 21:12:12 +08:00
|
|
|
name = 'price_gt_discounted_price'
|
2018-08-06 10:15:10 +08:00
|
|
|
constraint = models.CheckConstraint(check=check, name=name)
|
2016-11-05 21:12:12 +08:00
|
|
|
self.assertEqual(
|
2018-08-06 10:15:10 +08:00
|
|
|
repr(constraint),
|
|
|
|
"<CheckConstraint: check='{}' name='{}'>".format(check, name),
|
2016-11-05 21:12:12 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
def test_deconstruction(self):
|
2018-08-06 10:15:10 +08:00
|
|
|
check = models.Q(price__gt=models.F('discounted_price'))
|
2016-11-05 21:12:12 +08:00
|
|
|
name = 'price_gt_discounted_price'
|
2018-08-06 10:15:10 +08:00
|
|
|
constraint = models.CheckConstraint(check=check, name=name)
|
|
|
|
path, args, kwargs = constraint.deconstruct()
|
2016-11-05 21:12:12 +08:00
|
|
|
self.assertEqual(path, 'django.db.models.CheckConstraint')
|
|
|
|
self.assertEqual(args, ())
|
2018-08-06 10:15:10 +08:00
|
|
|
self.assertEqual(kwargs, {'check': check, 'name': name})
|
2016-11-05 21:12:12 +08:00
|
|
|
|
|
|
|
@skipUnlessDBFeature('supports_table_check_constraints')
|
2018-09-25 23:14:45 +08:00
|
|
|
def test_database_constraint(self):
|
2016-11-05 21:12:12 +08:00
|
|
|
Product.objects.create(name='Valid', price=10, discounted_price=5)
|
|
|
|
with self.assertRaises(IntegrityError):
|
|
|
|
Product.objects.create(name='Invalid', price=10, discounted_price=20)
|