1
0
mirror of https://github.com/django/django.git synced 2025-04-05 05:56:42 +00:00

contribute to constraints test - minimal

This commit is contained in:
Olivier Dalang 2023-08-11 16:06:07 +02:00
parent 9946f0b0d9
commit 1d4cbee39a
6 changed files with 78 additions and 0 deletions

View File

View File

@ -0,0 +1,14 @@
from django.db import models
class ConstraintField(models.CharField):
"""A field that contributes a DB contraint to the model's Meta"""
def contribute_to_class(self, cls, name, private_only=False):
super().contribute_to_class(cls, name, private_only)
cls._meta.constraints.append(
models.CheckConstraint(
check=models.Q(**{name: "valid"}),
name=f"test_constraint_{cls.__name__.lower()}",
)
)

View File

@ -0,0 +1 @@
0001_initial.py

View File

@ -0,0 +1,14 @@
from django.db import models
from .fields import ConstraintField
class ModelA(models.Model):
field = ConstraintField(max_length=10)
class ModelC(models.Model):
class Meta:
constraints = []
field = ConstraintField(max_length=10)

View File

@ -0,0 +1,49 @@
from pathlib import Path
from django.core.management import call_command
from django.db import IntegrityError
from django.test import TestCase, skipUnlessDBFeature
from .models import ModelA, ModelC
@skipUnlessDBFeature("supports_table_check_constraints")
class ConstraintsTests(TestCase):
"""Check that the constraints allow valid values and reject invalid ones"""
def test_ModelA_constraint(self):
ModelA.objects.create(field="valid")
with self.assertRaises(IntegrityError):
ModelA.objects.create(field="invalid")
def test_ModelC_constraint(self):
ModelC.objects.create(field="valid")
with self.assertRaises(IntegrityError):
ModelC.objects.create(field="invalid")
class ConstraintsMigrationsTests(TestCase):
"""Check that migrations correctly generate the constraints"""
@classmethod
def setUpClass(cls):
super().setUpClass()
# Clean and recreate migration files for further inspection
init_file = Path(__file__).parent / "migrations" / "0001_initial.py"
init_file.unlink(missing_ok=True)
call_command("makemigrations", verbosity=0)
cls.migration_content = init_file.read_text()
def test_ModelA(self):
# check migration contents
self.assertTrue(
"test_constraint_modela" in self.migration_content,
"Could not find constraint `test_constraint_modela` in migration",
)
def test_ModelC(self):
# check migration contents
self.assertTrue(
"test_constraint_modelc" in self.migration_content,
"Could not find constraint `test_constraint_modelc` in migration",
)