| 1 |
from datetime import datetime, timedelta |
| 2 |
from unittest import mock |
| 3 |
|
| 4 |
from django.core.exceptions import ValidationError |
| 5 |
from django.db import IntegrityError, connection, models |
| 6 |
from django.db.models import Case, F, When |
| 7 |
from django.db.models.constraints import BaseConstraint, UniqueConstraint |
| 8 |
from django.db.models.functions import Abs, Lower, Sqrt, Upper |
| 9 |
from django.db.transaction import atomic |
| 10 |
from django.test import SimpleTestCase, TestCase, skipIfDBFeature, skipUnlessDBFeature |
| 11 |
from django.test.utils import ignore_warnings |
| 12 |
from django.utils.deprecation import RemovedInDjango60Warning |
| 13 |
|
| 14 |
from .models import ( |
| 15 |
ChildModel, |
| 16 |
ChildUniqueConstraintProduct, |
| 17 |
GeneratedFieldStoredProduct, |
| 18 |
GeneratedFieldVirtualProduct, |
| 19 |
JSONFieldModel, |
| 20 |
ModelWithDatabaseDefault, |
| 21 |
Product, |
| 22 |
UniqueConstraintConditionProduct, |
| 23 |
UniqueConstraintDeferrable, |
| 24 |
UniqueConstraintInclude, |
| 25 |
UniqueConstraintProduct, |
| 26 |
) |
| 27 |
|
| 28 |
|
| 29 |
def get_constraints(table): |
| 30 |
with connection.cursor() as cursor: |
| 31 |
return connection.introspection.get_constraints(cursor, table) |
| 32 |
|
| 33 |
|
| 34 |
class BaseConstraintTests(SimpleTestCase): |
| 35 |
def test_constraint_sql(self): |
| 36 |
c = BaseConstraint(name="name") |
| 37 |
msg = "This method must be implemented by a subclass." |
| 38 |
with self.assertRaisesMessage(NotImplementedError, msg): |
| 39 |
c.constraint_sql(None, None) |
| 40 |
|
| 41 |
def test_contains_expressions(self): |
| 42 |
c = BaseConstraint(name="name") |
| 43 |
self.assertIs(c.contains_expressions, False) |
| 44 |
|
| 45 |
def test_create_sql(self): |
| 46 |
c = BaseConstraint(name="name") |
| 47 |
msg = "This method must be implemented by a subclass." |
| 48 |
with self.assertRaisesMessage(NotImplementedError, msg): |
| 49 |
c.create_sql(None, None) |
| 50 |
|
| 51 |
def test_remove_sql(self): |
| 52 |
c = BaseConstraint(name="name") |
| 53 |
msg = "This method must be implemented by a subclass." |
| 54 |
with self.assertRaisesMessage(NotImplementedError, msg): |
| 55 |
c.remove_sql(None, None) |
| 56 |
|
| 57 |
def test_validate(self): |
| 58 |
c = BaseConstraint(name="name") |
| 59 |
msg = "This method must be implemented by a subclass." |
| 60 |
with self.assertRaisesMessage(NotImplementedError, msg): |
| 61 |
c.validate(None, None) |
| 62 |
|
| 63 |
def test_default_violation_error_message(self): |
| 64 |
c = BaseConstraint(name="name") |
| 65 |
self.assertEqual( |
| 66 |
c.get_violation_error_message(), "Constraint “name” is violated." |
| 67 |
) |
| 68 |
|
| 69 |
def test_custom_violation_error_message(self): |
| 70 |
c = BaseConstraint( |
| 71 |
name="base_name", violation_error_message="custom %(name)s message" |
| 72 |
) |
| 73 |
self.assertEqual(c.get_violation_error_message(), "custom base_name message") |
| 74 |
|
| 75 |
def test_custom_violation_error_message_clone(self): |
| 76 |
constraint = BaseConstraint( |
| 77 |
name="base_name", |
| 78 |
violation_error_message="custom %(name)s message", |
| 79 |
).clone() |
| 80 |
self.assertEqual( |
| 81 |
constraint.get_violation_error_message(), |
| 82 |
"custom base_name message", |
| 83 |
) |
| 84 |
|
| 85 |
def test_custom_violation_code_message(self): |
| 86 |
c = BaseConstraint(name="base_name", violation_error_code="custom_code") |
| 87 |
self.assertEqual(c.violation_error_code, "custom_code") |
| 88 |
|
| 89 |
def test_deconstruction(self): |
| 90 |
constraint = BaseConstraint( |
| 91 |
name="base_name", |
| 92 |
violation_error_message="custom %(name)s message", |
| 93 |
violation_error_code="custom_code", |
| 94 |
) |
| 95 |
path, args, kwargs = constraint.deconstruct() |
| 96 |
self.assertEqual(path, "django.db.models.BaseConstraint") |
| 97 |
self.assertEqual(args, ()) |
| 98 |
self.assertEqual( |
| 99 |
kwargs, |
| 100 |
{ |
| 101 |
"name": "base_name", |
| 102 |
"violation_error_message": "custom %(name)s message", |
| 103 |
"violation_error_code": "custom_code", |
| 104 |
}, |
| 105 |
) |
| 106 |
|
| 107 |
def test_deprecation(self): |
| 108 |
msg = "Passing positional arguments to BaseConstraint is deprecated." |
| 109 |
with self.assertRaisesMessage(RemovedInDjango60Warning, msg): |
| 110 |
BaseConstraint("name", "violation error message") |
| 111 |
|
| 112 |
def test_name_required(self): |
| 113 |
msg = ( |
| 114 |
"BaseConstraint.__init__() missing 1 required keyword-only argument: 'name'" |
| 115 |
) |
| 116 |
with self.assertRaisesMessage(TypeError, msg): |
| 117 |
BaseConstraint() |
| 118 |
|
| 119 |
@ignore_warnings(category=RemovedInDjango60Warning) |
| 120 |
def test_positional_arguments(self): |
| 121 |
c = BaseConstraint("name", "custom %(name)s message") |
| 122 |
self.assertEqual(c.get_violation_error_message(), "custom name message") |
| 123 |
|
| 124 |
|
| 125 |
class CheckConstraintTests(TestCase): |
| 126 |
def test_eq(self): |
| 127 |
check1 = models.Q(price__gt=models.F("discounted_price")) |
| 128 |
check2 = models.Q(price__lt=models.F("discounted_price")) |
| 129 |
self.assertEqual( |
| 130 |
models.CheckConstraint(condition=check1, name="price"), |
| 131 |
models.CheckConstraint(condition=check1, name="price"), |
| 132 |
) |
| 133 |
self.assertEqual( |
| 134 |
models.CheckConstraint(condition=check1, name="price"), mock.ANY |
| 135 |
) |
| 136 |
self.assertNotEqual( |
| 137 |
models.CheckConstraint(condition=check1, name="price"), |
| 138 |
models.CheckConstraint(condition=check1, name="price2"), |
| 139 |
) |
| 140 |
self.assertNotEqual( |
| 141 |
models.CheckConstraint(condition=check1, name="price"), |
| 142 |
models.CheckConstraint(condition=check2, name="price"), |
| 143 |
) |
| 144 |
self.assertNotEqual(models.CheckConstraint(condition=check1, name="price"), 1) |
| 145 |
self.assertNotEqual( |
| 146 |
models.CheckConstraint(condition=check1, name="price"), |
| 147 |
models.CheckConstraint( |
| 148 |
condition=check1, name="price", violation_error_message="custom error" |
| 149 |
), |
| 150 |
) |
| 151 |
self.assertNotEqual( |
| 152 |
models.CheckConstraint( |
| 153 |
condition=check1, name="price", violation_error_message="custom error" |
| 154 |
), |
| 155 |
models.CheckConstraint( |
| 156 |
condition=check1, |
| 157 |
name="price", |
| 158 |
violation_error_message="other custom error", |
| 159 |
), |
| 160 |
) |
| 161 |
self.assertEqual( |
| 162 |
models.CheckConstraint( |
| 163 |
condition=check1, name="price", violation_error_message="custom error" |
| 164 |
), |
| 165 |
models.CheckConstraint( |
| 166 |
condition=check1, name="price", violation_error_message="custom error" |
| 167 |
), |
| 168 |
) |
| 169 |
self.assertNotEqual( |
| 170 |
models.CheckConstraint(condition=check1, name="price"), |
| 171 |
models.CheckConstraint( |
| 172 |
condition=check1, name="price", violation_error_code="custom_code" |
| 173 |
), |
| 174 |
) |
| 175 |
self.assertEqual( |
| 176 |
models.CheckConstraint( |
| 177 |
condition=check1, name="price", violation_error_code="custom_code" |
| 178 |
), |
| 179 |
models.CheckConstraint( |
| 180 |
condition=check1, name="price", violation_error_code="custom_code" |
| 181 |
), |
| 182 |
) |
| 183 |
|
| 184 |
def test_repr(self): |
| 185 |
constraint = models.CheckConstraint( |
| 186 |
condition=models.Q(price__gt=models.F("discounted_price")), |
| 187 |
name="price_gt_discounted_price", |
| 188 |
) |
| 189 |
self.assertEqual( |
| 190 |
repr(constraint), |
| 191 |
"<CheckConstraint: condition=(AND: ('price__gt', F(discounted_price))) " |
| 192 |
"name='price_gt_discounted_price'>", |
| 193 |
) |
| 194 |
|
| 195 |
def test_repr_with_violation_error_message(self): |
| 196 |
constraint = models.CheckConstraint( |
| 197 |
condition=models.Q(price__lt=1), |
| 198 |
name="price_lt_one", |
| 199 |
violation_error_message="More than 1", |
| 200 |
) |
| 201 |
self.assertEqual( |
| 202 |
repr(constraint), |
| 203 |
"<CheckConstraint: condition=(AND: ('price__lt', 1)) name='price_lt_one' " |
| 204 |
"violation_error_message='More than 1'>", |
| 205 |
) |
| 206 |
|
| 207 |
def test_repr_with_violation_error_code(self): |
| 208 |
constraint = models.CheckConstraint( |
| 209 |
condition=models.Q(price__lt=1), |
| 210 |
name="price_lt_one", |
| 211 |
violation_error_code="more_than_one", |
| 212 |
) |
| 213 |
self.assertEqual( |
| 214 |
repr(constraint), |
| 215 |
"<CheckConstraint: condition=(AND: ('price__lt', 1)) name='price_lt_one' " |
| 216 |
"violation_error_code='more_than_one'>", |
| 217 |
) |
| 218 |
|
| 219 |
def test_invalid_check_types(self): |
| 220 |
msg = "CheckConstraint.condition must be a Q instance or boolean expression." |
| 221 |
with self.assertRaisesMessage(TypeError, msg): |
| 222 |
models.CheckConstraint(condition=models.F("discounted_price"), name="check") |
| 223 |
|
| 224 |
def test_deconstruction(self): |
| 225 |
check = models.Q(price__gt=models.F("discounted_price")) |
| 226 |
name = "price_gt_discounted_price" |
| 227 |
constraint = models.CheckConstraint(condition=check, name=name) |
| 228 |
path, args, kwargs = constraint.deconstruct() |
| 229 |
self.assertEqual(path, "django.db.models.CheckConstraint") |
| 230 |
self.assertEqual(args, ()) |
| 231 |
self.assertEqual(kwargs, {"condition": check, "name": name}) |
| 232 |
|
| 233 |
@skipUnlessDBFeature("supports_table_check_constraints") |
| 234 |
def test_database_constraint(self): |
| 235 |
Product.objects.create(price=10, discounted_price=5) |
| 236 |
with self.assertRaises(IntegrityError): |
| 237 |
Product.objects.create(price=10, discounted_price=20) |
| 238 |
|
| 239 |
@skipUnlessDBFeature("supports_table_check_constraints") |
| 240 |
def test_database_constraint_unicode(self): |
| 241 |
Product.objects.create(price=10, discounted_price=5, unit="μg/mL") |
| 242 |
with self.assertRaises(IntegrityError): |
| 243 |
Product.objects.create(price=10, discounted_price=7, unit="l") |
| 244 |
|
| 245 |
@skipUnlessDBFeature( |
| 246 |
"supports_table_check_constraints", "can_introspect_check_constraints" |
| 247 |
) |
| 248 |
def test_name(self): |
| 249 |
constraints = get_constraints(Product._meta.db_table) |
| 250 |
for expected_name in ( |
| 251 |
"price_gt_discounted_price", |
| 252 |
"constraints_product_price_gt_0", |
| 253 |
): |
| 254 |
with self.subTest(expected_name): |
| 255 |
self.assertIn(expected_name, constraints) |
| 256 |
|
| 257 |
@skipUnlessDBFeature( |
| 258 |
"supports_table_check_constraints", "can_introspect_check_constraints" |
| 259 |
) |
| 260 |
def test_abstract_name(self): |
| 261 |
constraints = get_constraints(ChildModel._meta.db_table) |
| 262 |
self.assertIn("constraints_childmodel_adult", constraints) |
| 263 |
|
| 264 |
def test_validate(self): |
| 265 |
check = models.Q(price__gt=models.F("discounted_price")) |
| 266 |
constraint = models.CheckConstraint(condition=check, name="price") |
| 267 |
# Invalid product. |
| 268 |
invalid_product = Product(price=10, discounted_price=42) |
| 269 |
with self.assertRaises(ValidationError): |
| 270 |
constraint.validate(Product, invalid_product) |
| 271 |
with self.assertRaises(ValidationError): |
| 272 |
constraint.validate(Product, invalid_product, exclude={"unit"}) |
| 273 |
# Fields used by the check constraint are excluded. |
| 274 |
constraint.validate(Product, invalid_product, exclude={"price"}) |
| 275 |
constraint.validate(Product, invalid_product, exclude={"discounted_price"}) |
| 276 |
constraint.validate( |
| 277 |
Product, |
| 278 |
invalid_product, |
| 279 |
exclude={"discounted_price", "price"}, |
| 280 |
) |
| 281 |
# Valid product. |
| 282 |
constraint.validate(Product, Product(price=10, discounted_price=5)) |
| 283 |
|
| 284 |
def test_validate_custom_error(self): |
| 285 |
check = models.Q(price__gt=models.F("discounted_price")) |
| 286 |
constraint = models.CheckConstraint( |
| 287 |
condition=check, |
| 288 |
name="price", |
| 289 |
violation_error_message="discount is fake", |
| 290 |
violation_error_code="fake_discount", |
| 291 |
) |
| 292 |
# Invalid product. |
| 293 |
invalid_product = Product(price=10, discounted_price=42) |
| 294 |
msg = "discount is fake" |
| 295 |
with self.assertRaisesMessage(ValidationError, msg) as cm: |
| 296 |
constraint.validate(Product, invalid_product) |
| 297 |
self.assertEqual(cm.exception.code, "fake_discount") |
| 298 |
|
| 299 |
def test_validate_boolean_expressions(self): |
| 300 |
constraint = models.CheckConstraint( |
| 301 |
condition=models.expressions.ExpressionWrapper( |
| 302 |
models.Q(price__gt=500) | models.Q(price__lt=500), |
| 303 |
output_field=models.BooleanField(), |
| 304 |
), |
| 305 |
name="price_neq_500_wrap", |
| 306 |
) |
| 307 |
msg = f"Constraint “{constraint.name}” is violated." |
| 308 |
with self.assertRaisesMessage(ValidationError, msg): |
| 309 |
constraint.validate(Product, Product(price=500, discounted_price=5)) |
| 310 |
constraint.validate(Product, Product(price=501, discounted_price=5)) |
| 311 |
constraint.validate(Product, Product(price=499, discounted_price=5)) |
| 312 |
|
| 313 |
def test_validate_rawsql_expressions_noop(self): |
| 314 |
constraint = models.CheckConstraint( |
| 315 |
condition=models.expressions.RawSQL( |
| 316 |
"price < %s OR price > %s", |
| 317 |
(500, 500), |
| 318 |
output_field=models.BooleanField(), |
| 319 |
), |
| 320 |
name="price_neq_500_raw", |
| 321 |
) |
| 322 |
# RawSQL can not be checked and is always considered valid. |
| 323 |
constraint.validate(Product, Product(price=500, discounted_price=5)) |
| 324 |
constraint.validate(Product, Product(price=501, discounted_price=5)) |
| 325 |
constraint.validate(Product, Product(price=499, discounted_price=5)) |
| 326 |
|
| 327 |
@skipUnlessDBFeature("supports_comparing_boolean_expr") |
| 328 |
def test_validate_nullable_field_with_none(self): |
| 329 |
# Nullable fields should be considered valid on None values. |
| 330 |
constraint = models.CheckConstraint( |
| 331 |
condition=models.Q(price__gte=0), |
| 332 |
name="positive_price", |
| 333 |
) |
| 334 |
constraint.validate(Product, Product()) |
| 335 |
|
| 336 |
@skipIfDBFeature("supports_comparing_boolean_expr") |
| 337 |
def test_validate_nullable_field_with_isnull(self): |
| 338 |
constraint = models.CheckConstraint( |
| 339 |
condition=models.Q(price__gte=0) | models.Q(price__isnull=True), |
| 340 |
name="positive_price", |
| 341 |
) |
| 342 |
constraint.validate(Product, Product()) |
| 343 |
|
| 344 |
@skipUnlessDBFeature("supports_json_field") |
| 345 |
def test_validate_nullable_jsonfield(self): |
| 346 |
is_null_constraint = models.CheckConstraint( |
| 347 |
condition=models.Q(data__isnull=True), |
| 348 |
name="nullable_data", |
| 349 |
) |
| 350 |
is_not_null_constraint = models.CheckConstraint( |
| 351 |
condition=models.Q(data__isnull=False), |
| 352 |
name="nullable_data", |
| 353 |
) |
| 354 |
is_null_constraint.validate(JSONFieldModel, JSONFieldModel(data=None)) |
| 355 |
msg = f"Constraint “{is_null_constraint.name}” is violated." |
| 356 |
with self.assertRaisesMessage(ValidationError, msg): |
| 357 |
is_null_constraint.validate(JSONFieldModel, JSONFieldModel(data={})) |
| 358 |
msg = f"Constraint “{is_not_null_constraint.name}” is violated." |
| 359 |
with self.assertRaisesMessage(ValidationError, msg): |
| 360 |
is_not_null_constraint.validate(JSONFieldModel, JSONFieldModel(data=None)) |
| 361 |
is_not_null_constraint.validate(JSONFieldModel, JSONFieldModel(data={})) |
| 362 |
|
| 363 |
def test_validate_pk_field(self): |
| 364 |
constraint_with_pk = models.CheckConstraint( |
| 365 |
condition=~models.Q(pk=models.F("age")), |
| 366 |
name="pk_not_age_check", |
| 367 |
) |
| 368 |
constraint_with_pk.validate(ChildModel, ChildModel(pk=1, age=2)) |
| 369 |
msg = f"Constraint “{constraint_with_pk.name}” is violated." |
| 370 |
with self.assertRaisesMessage(ValidationError, msg): |
| 371 |
constraint_with_pk.validate(ChildModel, ChildModel(pk=1, age=1)) |
| 372 |
with self.assertRaisesMessage(ValidationError, msg): |
| 373 |
constraint_with_pk.validate(ChildModel, ChildModel(id=1, age=1)) |
| 374 |
constraint_with_pk.validate(ChildModel, ChildModel(pk=1, age=1), exclude={"pk"}) |
| 375 |
|
| 376 |
@skipUnlessDBFeature("supports_json_field") |
| 377 |
def test_validate_jsonfield_exact(self): |
| 378 |
data = {"release": "5.0.2", "version": "stable"} |
| 379 |
json_exact_constraint = models.CheckConstraint( |
| 380 |
condition=models.Q(data__version="stable"), |
| 381 |
name="only_stable_version", |
| 382 |
) |
| 383 |
json_exact_constraint.validate(JSONFieldModel, JSONFieldModel(data=data)) |
| 384 |
|
| 385 |
data = {"release": "5.0.2", "version": "not stable"} |
| 386 |
msg = f"Constraint “{json_exact_constraint.name}” is violated." |
| 387 |
with self.assertRaisesMessage(ValidationError, msg): |
| 388 |
json_exact_constraint.validate(JSONFieldModel, JSONFieldModel(data=data)) |
| 389 |
|
| 390 |
@skipUnlessDBFeature("supports_stored_generated_columns") |
| 391 |
def test_validate_generated_field_stored(self): |
| 392 |
self.assertGeneratedFieldIsValidated(model=GeneratedFieldStoredProduct) |
| 393 |
|
| 394 |
@skipUnlessDBFeature("supports_virtual_generated_columns") |
| 395 |
def test_validate_generated_field_virtual(self): |
| 396 |
self.assertGeneratedFieldIsValidated(model=GeneratedFieldVirtualProduct) |
| 397 |
|
| 398 |
def assertGeneratedFieldIsValidated(self, model): |
| 399 |
constraint = models.CheckConstraint( |
| 400 |
condition=models.Q(rebate__range=(0, 100)), name="bounded_rebate" |
| 401 |
) |
| 402 |
constraint.validate(model, model(price=50, discounted_price=20)) |
| 403 |
|
| 404 |
invalid_product = model(price=1200, discounted_price=500) |
| 405 |
msg = f"Constraint “{constraint.name}” is violated." |
| 406 |
with self.assertRaisesMessage(ValidationError, msg): |
| 407 |
constraint.validate(model, invalid_product) |
| 408 |
|
| 409 |
# Excluding referenced or generated fields should skip validation. |
| 410 |
constraint.validate(model, invalid_product, exclude={"price"}) |
| 411 |
constraint.validate(model, invalid_product, exclude={"rebate"}) |
| 412 |
|
| 413 |
def test_check_deprecation(self): |
| 414 |
msg = "CheckConstraint.check is deprecated in favor of `.condition`." |
| 415 |
condition = models.Q(foo="bar") |
| 416 |
with self.assertWarnsMessage(RemovedInDjango60Warning, msg) as ctx: |
| 417 |
constraint = models.CheckConstraint(name="constraint", check=condition) |
| 418 |
self.assertEqual(ctx.filename, __file__) |
| 419 |
with self.assertWarnsMessage(RemovedInDjango60Warning, msg) as ctx: |
| 420 |
self.assertIs(constraint.check, condition) |
| 421 |
self.assertEqual(ctx.filename, __file__) |
| 422 |
other_condition = models.Q(something="else") |
| 423 |
with self.assertWarnsMessage(RemovedInDjango60Warning, msg) as ctx: |
| 424 |
constraint.check = other_condition |
| 425 |
self.assertEqual(ctx.filename, __file__) |
| 426 |
with self.assertWarnsMessage(RemovedInDjango60Warning, msg) as ctx: |
| 427 |
self.assertIs(constraint.check, other_condition) |
| 428 |
self.assertEqual(ctx.filename, __file__) |
| 429 |
|
| 430 |
def test_database_default(self): |
| 431 |
models.CheckConstraint( |
| 432 |
condition=models.Q(field_with_db_default="field_with_db_default"), |
| 433 |
name="check_field_with_db_default", |
| 434 |
).validate(ModelWithDatabaseDefault, ModelWithDatabaseDefault()) |
| 435 |
|
| 436 |
# Ensure that a check also does not silently pass with either |
| 437 |
# FieldError or DatabaseError when checking with a db_default. |
| 438 |
with self.assertRaises(ValidationError): |
| 439 |
models.CheckConstraint( |
| 440 |
condition=models.Q( |
| 441 |
field_with_db_default="field_with_db_default", field="field" |
| 442 |
), |
| 443 |
name="check_field_with_db_default_2", |
| 444 |
).validate( |
| 445 |
ModelWithDatabaseDefault, ModelWithDatabaseDefault(field="not-field") |
| 446 |
) |
| 447 |
|
| 448 |
with self.assertRaises(ValidationError): |
| 449 |
models.CheckConstraint( |
| 450 |
condition=models.Q(field_with_db_default="field_with_db_default"), |
| 451 |
name="check_field_with_db_default", |
| 452 |
).validate( |
| 453 |
ModelWithDatabaseDefault, |
| 454 |
ModelWithDatabaseDefault(field_with_db_default="other value"), |
| 455 |
) |
| 456 |
|
| 457 |
|
| 458 |
class UniqueConstraintTests(TestCase): |
| 459 |
@classmethod |
| 460 |
def setUpTestData(cls): |
| 461 |
cls.p1 = UniqueConstraintProduct.objects.create(name="p1", color="red") |
| 462 |
cls.p2 = UniqueConstraintProduct.objects.create(name="p2") |
| 463 |
|
| 464 |
def test_eq(self): |
| 465 |
self.assertEqual( |
| 466 |
models.UniqueConstraint(fields=["foo", "bar"], name="unique"), |
| 467 |
models.UniqueConstraint(fields=["foo", "bar"], name="unique"), |
| 468 |
) |
| 469 |
self.assertEqual( |
| 470 |
models.UniqueConstraint(fields=["foo", "bar"], name="unique"), |
| 471 |
mock.ANY, |
| 472 |
) |
| 473 |
self.assertNotEqual( |
| 474 |
models.UniqueConstraint(fields=["foo", "bar"], name="unique"), |
| 475 |
models.UniqueConstraint(fields=["foo", "bar"], name="unique2"), |
| 476 |
) |
| 477 |
self.assertNotEqual( |
| 478 |
models.UniqueConstraint(fields=["foo", "bar"], name="unique"), |
| 479 |
models.UniqueConstraint(fields=["foo", "baz"], name="unique"), |
| 480 |
) |
| 481 |
self.assertNotEqual( |
| 482 |
models.UniqueConstraint(fields=["foo", "bar"], name="unique"), 1 |
| 483 |
) |
| 484 |
self.assertNotEqual( |
| 485 |
models.UniqueConstraint(fields=["foo", "bar"], name="unique"), |
| 486 |
models.UniqueConstraint( |
| 487 |
fields=["foo", "bar"], |
| 488 |
name="unique", |
| 489 |
violation_error_message="custom error", |
| 490 |
), |
| 491 |
) |
| 492 |
self.assertNotEqual( |
| 493 |
models.UniqueConstraint( |
| 494 |
fields=["foo", "bar"], |
| 495 |
name="unique", |
| 496 |
violation_error_message="custom error", |
| 497 |
), |
| 498 |
models.UniqueConstraint( |
| 499 |
fields=["foo", "bar"], |
| 500 |
name="unique", |
| 501 |
violation_error_message="other custom error", |
| 502 |
), |
| 503 |
) |
| 504 |
self.assertEqual( |
| 505 |
models.UniqueConstraint( |
| 506 |
fields=["foo", "bar"], |
| 507 |
name="unique", |
| 508 |
violation_error_message="custom error", |
| 509 |
), |
| 510 |
models.UniqueConstraint( |
| 511 |
fields=["foo", "bar"], |
| 512 |
name="unique", |
| 513 |
violation_error_message="custom error", |
| 514 |
), |
| 515 |
) |
| 516 |
self.assertNotEqual( |
| 517 |
models.UniqueConstraint( |
| 518 |
fields=["foo", "bar"], |
| 519 |
name="unique", |
| 520 |
violation_error_code="custom_error", |
| 521 |
), |
| 522 |
models.UniqueConstraint( |
| 523 |
fields=["foo", "bar"], |
| 524 |
name="unique", |
| 525 |
violation_error_code="other_custom_error", |
| 526 |
), |
| 527 |
) |
| 528 |
self.assertEqual( |
| 529 |
models.UniqueConstraint( |
| 530 |
fields=["foo", "bar"], |
| 531 |
name="unique", |
| 532 |
violation_error_code="custom_error", |
| 533 |
), |
| 534 |
models.UniqueConstraint( |
| 535 |
fields=["foo", "bar"], |
| 536 |
name="unique", |
| 537 |
violation_error_code="custom_error", |
| 538 |
), |
| 539 |
) |
| 540 |
|
| 541 |
def test_eq_with_condition(self): |
| 542 |
self.assertEqual( |
| 543 |
models.UniqueConstraint( |
| 544 |
fields=["foo", "bar"], |
| 545 |
name="unique", |
| 546 |
condition=models.Q(foo=models.F("bar")), |
| 547 |
), |
| 548 |
models.UniqueConstraint( |
| 549 |
fields=["foo", "bar"], |
| 550 |
name="unique", |
| 551 |
condition=models.Q(foo=models.F("bar")), |
| 552 |
), |
| 553 |
) |
| 554 |
self.assertNotEqual( |
| 555 |
models.UniqueConstraint( |
| 556 |
fields=["foo", "bar"], |
| 557 |
name="unique", |
| 558 |
condition=models.Q(foo=models.F("bar")), |
| 559 |
), |
| 560 |
models.UniqueConstraint( |
| 561 |
fields=["foo", "bar"], |
| 562 |
name="unique", |
| 563 |
condition=models.Q(foo=models.F("baz")), |
| 564 |
), |
| 565 |
) |
| 566 |
|
| 567 |
def test_eq_with_deferrable(self): |
| 568 |
constraint_1 = models.UniqueConstraint( |
| 569 |
fields=["foo", "bar"], |
| 570 |
name="unique", |
| 571 |
deferrable=models.Deferrable.DEFERRED, |
| 572 |
) |
| 573 |
constraint_2 = models.UniqueConstraint( |
| 574 |
fields=["foo", "bar"], |
| 575 |
name="unique", |
| 576 |
deferrable=models.Deferrable.IMMEDIATE, |
| 577 |
) |
| 578 |
self.assertEqual(constraint_1, constraint_1) |
| 579 |
self.assertNotEqual(constraint_1, constraint_2) |
| 580 |
|
| 581 |
def test_eq_with_include(self): |
| 582 |
constraint_1 = models.UniqueConstraint( |
| 583 |
fields=["foo", "bar"], |
| 584 |
name="include", |
| 585 |
include=["baz_1"], |
| 586 |
) |
| 587 |
constraint_2 = models.UniqueConstraint( |
| 588 |
fields=["foo", "bar"], |
| 589 |
name="include", |
| 590 |
include=["baz_2"], |
| 591 |
) |
| 592 |
self.assertEqual(constraint_1, constraint_1) |
| 593 |
self.assertNotEqual(constraint_1, constraint_2) |
| 594 |
|
| 595 |
def test_eq_with_opclasses(self): |
| 596 |
constraint_1 = models.UniqueConstraint( |
| 597 |
fields=["foo", "bar"], |
| 598 |
name="opclasses", |
| 599 |
opclasses=["text_pattern_ops", "varchar_pattern_ops"], |
| 600 |
) |
| 601 |
constraint_2 = models.UniqueConstraint( |
| 602 |
fields=["foo", "bar"], |
| 603 |
name="opclasses", |
| 604 |
opclasses=["varchar_pattern_ops", "text_pattern_ops"], |
| 605 |
) |
| 606 |
self.assertEqual(constraint_1, constraint_1) |
| 607 |
self.assertNotEqual(constraint_1, constraint_2) |
| 608 |
|
| 609 |
def test_eq_with_expressions(self): |
| 610 |
constraint = models.UniqueConstraint( |
| 611 |
Lower("title"), |
| 612 |
F("author"), |
| 613 |
name="book_func_uq", |
| 614 |
) |
| 615 |
same_constraint = models.UniqueConstraint( |
| 616 |
Lower("title"), |
| 617 |
"author", |
| 618 |
name="book_func_uq", |
| 619 |
) |
| 620 |
another_constraint = models.UniqueConstraint( |
| 621 |
Lower("title"), |
| 622 |
name="book_func_uq", |
| 623 |
) |
| 624 |
self.assertEqual(constraint, same_constraint) |
| 625 |
self.assertEqual(constraint, mock.ANY) |
| 626 |
self.assertNotEqual(constraint, another_constraint) |
| 627 |
|
| 628 |
def test_eq_with_nulls_distinct(self): |
| 629 |
constraint_1 = models.UniqueConstraint( |
| 630 |
Lower("title"), |
| 631 |
nulls_distinct=False, |
| 632 |
name="book_func_nulls_distinct_uq", |
| 633 |
) |
| 634 |
constraint_2 = models.UniqueConstraint( |
| 635 |
Lower("title"), |
| 636 |
nulls_distinct=True, |
| 637 |
name="book_func_nulls_distinct_uq", |
| 638 |
) |
| 639 |
constraint_3 = models.UniqueConstraint( |
| 640 |
Lower("title"), |
| 641 |
name="book_func_nulls_distinct_uq", |
| 642 |
) |
| 643 |
self.assertEqual(constraint_1, constraint_1) |
| 644 |
self.assertEqual(constraint_1, mock.ANY) |
| 645 |
self.assertNotEqual(constraint_1, constraint_2) |
| 646 |
self.assertNotEqual(constraint_1, constraint_3) |
| 647 |
self.assertNotEqual(constraint_2, constraint_3) |
| 648 |
|
| 649 |
def test_repr(self): |
| 650 |
fields = ["foo", "bar"] |
| 651 |
name = "unique_fields" |
| 652 |
constraint = models.UniqueConstraint(fields=fields, name=name) |
| 653 |
self.assertEqual( |
| 654 |
repr(constraint), |
| 655 |
"<UniqueConstraint: fields=('foo', 'bar') name='unique_fields'>", |
| 656 |
) |
| 657 |
|
| 658 |
def test_repr_with_condition(self): |
| 659 |
constraint = models.UniqueConstraint( |
| 660 |
fields=["foo", "bar"], |
| 661 |
name="unique_fields", |
| 662 |
condition=models.Q(foo=models.F("bar")), |
| 663 |
) |
| 664 |
self.assertEqual( |
| 665 |
repr(constraint), |
| 666 |
"<UniqueConstraint: fields=('foo', 'bar') name='unique_fields' " |
| 667 |
"condition=(AND: ('foo', F(bar)))>", |
| 668 |
) |
| 669 |
|
| 670 |
def test_repr_with_deferrable(self): |
| 671 |
constraint = models.UniqueConstraint( |
| 672 |
fields=["foo", "bar"], |
| 673 |
name="unique_fields", |
| 674 |
deferrable=models.Deferrable.IMMEDIATE, |
| 675 |
) |
| 676 |
self.assertEqual( |
| 677 |
repr(constraint), |
| 678 |
"<UniqueConstraint: fields=('foo', 'bar') name='unique_fields' " |
| 679 |
"deferrable=Deferrable.IMMEDIATE>", |
| 680 |
) |
| 681 |
|
| 682 |
def test_repr_with_include(self): |
| 683 |
constraint = models.UniqueConstraint( |
| 684 |
fields=["foo", "bar"], |
| 685 |
name="include_fields", |
| 686 |
include=["baz_1", "baz_2"], |
| 687 |
) |
| 688 |
self.assertEqual( |
| 689 |
repr(constraint), |
| 690 |
"<UniqueConstraint: fields=('foo', 'bar') name='include_fields' " |
| 691 |
"include=('baz_1', 'baz_2')>", |
| 692 |
) |
| 693 |
|
| 694 |
def test_repr_with_opclasses(self): |
| 695 |
constraint = models.UniqueConstraint( |
| 696 |
fields=["foo", "bar"], |
| 697 |
name="opclasses_fields", |
| 698 |
opclasses=["text_pattern_ops", "varchar_pattern_ops"], |
| 699 |
) |
| 700 |
self.assertEqual( |
| 701 |
repr(constraint), |
| 702 |
"<UniqueConstraint: fields=('foo', 'bar') name='opclasses_fields' " |
| 703 |
"opclasses=['text_pattern_ops', 'varchar_pattern_ops']>", |
| 704 |
) |
| 705 |
|
| 706 |
def test_repr_with_nulls_distinct(self): |
| 707 |
constraint = models.UniqueConstraint( |
| 708 |
fields=["foo", "bar"], |
| 709 |
name="nulls_distinct_fields", |
| 710 |
nulls_distinct=False, |
| 711 |
) |
| 712 |
self.assertEqual( |
| 713 |
repr(constraint), |
| 714 |
"<UniqueConstraint: fields=('foo', 'bar') name='nulls_distinct_fields' " |
| 715 |
"nulls_distinct=False>", |
| 716 |
) |
| 717 |
|
| 718 |
def test_repr_with_expressions(self): |
| 719 |
constraint = models.UniqueConstraint( |
| 720 |
Lower("title"), |
| 721 |
F("author"), |
| 722 |
name="book_func_uq", |
| 723 |
) |
| 724 |
self.assertEqual( |
| 725 |
repr(constraint), |
| 726 |
"<UniqueConstraint: expressions=(Lower(F(title)), F(author)) " |
| 727 |
"name='book_func_uq'>", |
| 728 |
) |
| 729 |
|
| 730 |
def test_repr_with_violation_error_message(self): |
| 731 |
constraint = models.UniqueConstraint( |
| 732 |
models.F("baz__lower"), |
| 733 |
name="unique_lower_baz", |
| 734 |
violation_error_message="BAZ", |
| 735 |
) |
| 736 |
self.assertEqual( |
| 737 |
repr(constraint), |
| 738 |
( |
| 739 |
"<UniqueConstraint: expressions=(F(baz__lower),) " |
| 740 |
"name='unique_lower_baz' violation_error_message='BAZ'>" |
| 741 |
), |
| 742 |
) |
| 743 |
|
| 744 |
def test_repr_with_violation_error_code(self): |
| 745 |
constraint = models.UniqueConstraint( |
| 746 |
models.F("baz__lower"), |
| 747 |
name="unique_lower_baz", |
| 748 |
violation_error_code="baz", |
| 749 |
) |
| 750 |
self.assertEqual( |
| 751 |
repr(constraint), |
| 752 |
( |
| 753 |
"<UniqueConstraint: expressions=(F(baz__lower),) " |
| 754 |
"name='unique_lower_baz' violation_error_code='baz'>" |
| 755 |
), |
| 756 |
) |
| 757 |
|
| 758 |
def test_deconstruction(self): |
| 759 |
fields = ["foo", "bar"] |
| 760 |
name = "unique_fields" |
| 761 |
constraint = models.UniqueConstraint(fields=fields, name=name) |
| 762 |
path, args, kwargs = constraint.deconstruct() |
| 763 |
self.assertEqual(path, "django.db.models.UniqueConstraint") |
| 764 |
self.assertEqual(args, ()) |
| 765 |
self.assertEqual(kwargs, {"fields": tuple(fields), "name": name}) |
| 766 |
|
| 767 |
def test_deconstruction_with_condition(self): |
| 768 |
fields = ["foo", "bar"] |
| 769 |
name = "unique_fields" |
| 770 |
condition = models.Q(foo=models.F("bar")) |
| 771 |
constraint = models.UniqueConstraint( |
| 772 |
fields=fields, name=name, condition=condition |
| 773 |
) |
| 774 |
path, args, kwargs = constraint.deconstruct() |
| 775 |
self.assertEqual(path, "django.db.models.UniqueConstraint") |
| 776 |
self.assertEqual(args, ()) |
| 777 |
self.assertEqual( |
| 778 |
kwargs, {"fields": tuple(fields), "name": name, "condition": condition} |
| 779 |
) |
| 780 |
|
| 781 |
def test_deconstruction_with_deferrable(self): |
| 782 |
fields = ["foo"] |
| 783 |
name = "unique_fields" |
| 784 |
constraint = models.UniqueConstraint( |
| 785 |
fields=fields, |
| 786 |
name=name, |
| 787 |
deferrable=models.Deferrable.DEFERRED, |
| 788 |
) |
| 789 |
path, args, kwargs = constraint.deconstruct() |
| 790 |
self.assertEqual(path, "django.db.models.UniqueConstraint") |
| 791 |
self.assertEqual(args, ()) |
| 792 |
self.assertEqual( |
| 793 |
kwargs, |
| 794 |
{ |
| 795 |
"fields": tuple(fields), |
| 796 |
"name": name, |
| 797 |
"deferrable": models.Deferrable.DEFERRED, |
| 798 |
}, |
| 799 |
) |
| 800 |
|
| 801 |
def test_deconstruction_with_include(self): |
| 802 |
fields = ["foo", "bar"] |
| 803 |
name = "unique_fields" |
| 804 |
include = ["baz_1", "baz_2"] |
| 805 |
constraint = models.UniqueConstraint(fields=fields, name=name, include=include) |
| 806 |
path, args, kwargs = constraint.deconstruct() |
| 807 |
self.assertEqual(path, "django.db.models.UniqueConstraint") |
| 808 |
self.assertEqual(args, ()) |
| 809 |
self.assertEqual( |
| 810 |
kwargs, |
| 811 |
{ |
| 812 |
"fields": tuple(fields), |
| 813 |
"name": name, |
| 814 |
"include": tuple(include), |
| 815 |
}, |
| 816 |
) |
| 817 |
|
| 818 |
def test_deconstruction_with_opclasses(self): |
| 819 |
fields = ["foo", "bar"] |
| 820 |
name = "unique_fields" |
| 821 |
opclasses = ["varchar_pattern_ops", "text_pattern_ops"] |
| 822 |
constraint = models.UniqueConstraint( |
| 823 |
fields=fields, name=name, opclasses=opclasses |
| 824 |
) |
| 825 |
path, args, kwargs = constraint.deconstruct() |
| 826 |
self.assertEqual(path, "django.db.models.UniqueConstraint") |
| 827 |
self.assertEqual(args, ()) |
| 828 |
self.assertEqual( |
| 829 |
kwargs, |
| 830 |
{ |
| 831 |
"fields": tuple(fields), |
| 832 |
"name": name, |
| 833 |
"opclasses": opclasses, |
| 834 |
}, |
| 835 |
) |
| 836 |
|
| 837 |
def test_deconstruction_with_nulls_distinct(self): |
| 838 |
fields = ["foo", "bar"] |
| 839 |
name = "unique_fields" |
| 840 |
constraint = models.UniqueConstraint( |
| 841 |
fields=fields, name=name, nulls_distinct=True |
| 842 |
) |
| 843 |
path, args, kwargs = constraint.deconstruct() |
| 844 |
self.assertEqual(path, "django.db.models.UniqueConstraint") |
| 845 |
self.assertEqual(args, ()) |
| 846 |
self.assertEqual( |
| 847 |
kwargs, |
| 848 |
{ |
| 849 |
"fields": tuple(fields), |
| 850 |
"name": name, |
| 851 |
"nulls_distinct": True, |
| 852 |
}, |
| 853 |
) |
| 854 |
|
| 855 |
def test_deconstruction_with_expressions(self): |
| 856 |
name = "unique_fields" |
| 857 |
constraint = models.UniqueConstraint(Lower("title"), name=name) |
| 858 |
path, args, kwargs = constraint.deconstruct() |
| 859 |
self.assertEqual(path, "django.db.models.UniqueConstraint") |
| 860 |
self.assertEqual(args, (Lower("title"),)) |
| 861 |
self.assertEqual(kwargs, {"name": name}) |
| 862 |
|
| 863 |
def test_database_constraint(self): |
| 864 |
with self.assertRaises(IntegrityError): |
| 865 |
UniqueConstraintProduct.objects.create( |
| 866 |
name=self.p1.name, color=self.p1.color |
| 867 |
) |
| 868 |
|
| 869 |
@skipUnlessDBFeature("supports_partial_indexes") |
| 870 |
def test_database_constraint_with_condition(self): |
| 871 |
UniqueConstraintConditionProduct.objects.create(name="p1") |
| 872 |
UniqueConstraintConditionProduct.objects.create(name="p2") |
| 873 |
with self.assertRaises(IntegrityError): |
| 874 |
UniqueConstraintConditionProduct.objects.create(name="p1") |
| 875 |
|
| 876 |
def test_model_validation(self): |
| 877 |
msg = "Unique constraint product with this Name and Color already exists." |
| 878 |
with self.assertRaisesMessage(ValidationError, msg): |
| 879 |
UniqueConstraintProduct( |
| 880 |
name=self.p1.name, color=self.p1.color |
| 881 |
).validate_constraints() |
| 882 |
|
| 883 |
@skipUnlessDBFeature("supports_partial_indexes") |
| 884 |
def test_model_validation_with_condition(self): |
| 885 |
""" |
| 886 |
Partial unique constraints are not ignored by |
| 887 |
Model.validate_constraints(). |
| 888 |
""" |
| 889 |
obj1 = UniqueConstraintConditionProduct.objects.create(name="p1", color="red") |
| 890 |
obj2 = UniqueConstraintConditionProduct.objects.create(name="p2") |
| 891 |
UniqueConstraintConditionProduct( |
| 892 |
name=obj1.name, color="blue" |
| 893 |
).validate_constraints() |
| 894 |
msg = "Constraint “name_without_color_uniq” is violated." |
| 895 |
with self.assertRaisesMessage(ValidationError, msg): |
| 896 |
UniqueConstraintConditionProduct(name=obj2.name).validate_constraints() |
| 897 |
|
| 898 |
def test_model_validation_constraint_no_code_error(self): |
| 899 |
class ValidateNoCodeErrorConstraint(UniqueConstraint): |
| 900 |
def validate(self, model, instance, **kwargs): |
| 901 |
raise ValidationError({"name": ValidationError("Already exists.")}) |
| 902 |
|
| 903 |
class NoCodeErrorConstraintModel(models.Model): |
| 904 |
name = models.CharField(max_length=255) |
| 905 |
|
| 906 |
class Meta: |
| 907 |
constraints = [ |
| 908 |
ValidateNoCodeErrorConstraint( |
| 909 |
Lower("name"), |
| 910 |
name="custom_validate_no_code_error", |
| 911 |
) |
| 912 |
] |
| 913 |
|
| 914 |
msg = "{'name': ['Already exists.']}" |
| 915 |
with self.assertRaisesMessage(ValidationError, msg): |
| 916 |
NoCodeErrorConstraintModel(name="test").validate_constraints() |
| 917 |
|
| 918 |
def test_validate(self): |
| 919 |
constraint = UniqueConstraintProduct._meta.constraints[0] |
| 920 |
msg = "Unique constraint product with this Name and Color already exists." |
| 921 |
non_unique_product = UniqueConstraintProduct( |
| 922 |
name=self.p1.name, color=self.p1.color |
| 923 |
) |
| 924 |
with self.assertRaisesMessage(ValidationError, msg) as cm: |
| 925 |
constraint.validate(UniqueConstraintProduct, non_unique_product) |
| 926 |
self.assertEqual(cm.exception.code, "unique_together") |
| 927 |
# Null values are ignored. |
| 928 |
constraint.validate( |
| 929 |
UniqueConstraintProduct, |
| 930 |
UniqueConstraintProduct(name=self.p2.name, color=None), |
| 931 |
) |
| 932 |
# Existing instances have their existing row excluded. |
| 933 |
constraint.validate(UniqueConstraintProduct, self.p1) |
| 934 |
# Unique fields are excluded. |
| 935 |
constraint.validate( |
| 936 |
UniqueConstraintProduct, |
| 937 |
non_unique_product, |
| 938 |
exclude={"name"}, |
| 939 |
) |
| 940 |
constraint.validate( |
| 941 |
UniqueConstraintProduct, |
| 942 |
non_unique_product, |
| 943 |
exclude={"color"}, |
| 944 |
) |
| 945 |
constraint.validate( |
| 946 |
UniqueConstraintProduct, |
| 947 |
non_unique_product, |
| 948 |
exclude={"name", "color"}, |
| 949 |
) |
| 950 |
# Validation on a child instance. |
| 951 |
with self.assertRaisesMessage(ValidationError, msg): |
| 952 |
constraint.validate( |
| 953 |
UniqueConstraintProduct, |
| 954 |
ChildUniqueConstraintProduct(name=self.p1.name, color=self.p1.color), |
| 955 |
) |
| 956 |
|
| 957 |
def test_validate_unique_custom_code_and_message(self): |
| 958 |
product = UniqueConstraintProduct.objects.create( |
| 959 |
name="test", color="red", age=42 |
| 960 |
) |
| 961 |
code = "custom_code" |
| 962 |
message = "Custom message" |
| 963 |
multiple_fields_constraint = models.UniqueConstraint( |
| 964 |
fields=["color", "age"], |
| 965 |
name="color_age_uniq", |
| 966 |
violation_error_code=code, |
| 967 |
violation_error_message=message, |
| 968 |
) |
| 969 |
single_field_constraint = models.UniqueConstraint( |
| 970 |
fields=["color"], |
| 971 |
name="color_uniq", |
| 972 |
violation_error_code=code, |
| 973 |
violation_error_message=message, |
| 974 |
) |
| 975 |
|
| 976 |
with self.assertRaisesMessage(ValidationError, message) as cm: |
| 977 |
multiple_fields_constraint.validate( |
| 978 |
UniqueConstraintProduct, |
| 979 |
UniqueConstraintProduct( |
| 980 |
name="new-test", color=product.color, age=product.age |
| 981 |
), |
| 982 |
) |
| 983 |
self.assertEqual(cm.exception.code, code) |
| 984 |
|
| 985 |
with self.assertRaisesMessage(ValidationError, message) as cm: |
| 986 |
single_field_constraint.validate( |
| 987 |
UniqueConstraintProduct, |
| 988 |
UniqueConstraintProduct(name="new-test", color=product.color), |
| 989 |
) |
| 990 |
self.assertEqual(cm.exception.code, code) |
| 991 |
|
| 992 |
@skipUnlessDBFeature("supports_table_check_constraints") |
| 993 |
def test_validate_fields_unattached(self): |
| 994 |
Product.objects.create(price=42) |
| 995 |
constraint = models.UniqueConstraint(fields=["price"], name="uniq_prices") |
| 996 |
msg = "Product with this Price already exists." |
| 997 |
with self.assertRaisesMessage(ValidationError, msg): |
| 998 |
constraint.validate(Product, Product(price=42)) |
| 999 |
|
| 1000 |
@skipUnlessDBFeature("supports_partial_indexes") |
| 1001 |
def test_validate_condition(self): |
| 1002 |
p1 = UniqueConstraintConditionProduct.objects.create(name="p1") |
| 1003 |
constraint = UniqueConstraintConditionProduct._meta.constraints[0] |
| 1004 |
msg = "Constraint “name_without_color_uniq” is violated." |
| 1005 |
with self.assertRaisesMessage(ValidationError, msg): |
| 1006 |
constraint.validate( |
| 1007 |
UniqueConstraintConditionProduct, |
| 1008 |
UniqueConstraintConditionProduct(name=p1.name, color=None), |
| 1009 |
) |
| 1010 |
# Values not matching condition are ignored. |
| 1011 |
constraint.validate( |
| 1012 |
UniqueConstraintConditionProduct, |
| 1013 |
UniqueConstraintConditionProduct(name=p1.name, color="anything-but-none"), |
| 1014 |
) |
| 1015 |
# Existing instances have their existing row excluded. |
| 1016 |
constraint.validate(UniqueConstraintConditionProduct, p1) |
| 1017 |
# Unique field is excluded. |
| 1018 |
constraint.validate( |
| 1019 |
UniqueConstraintConditionProduct, |
| 1020 |
UniqueConstraintConditionProduct(name=p1.name, color=None), |
| 1021 |
exclude={"name"}, |
| 1022 |
) |
| 1023 |
|
| 1024 |
@skipUnlessDBFeature("supports_partial_indexes") |
| 1025 |
def test_validate_condition_custom_error(self): |
| 1026 |
p1 = UniqueConstraintConditionProduct.objects.create(name="p1") |
| 1027 |
constraint = models.UniqueConstraint( |
| 1028 |
fields=["name"], |
| 1029 |
name="name_without_color_uniq", |
| 1030 |
condition=models.Q(color__isnull=True), |
| 1031 |
violation_error_code="custom_code", |
| 1032 |
violation_error_message="Custom message", |
| 1033 |
) |
| 1034 |
msg = "Custom message" |
| 1035 |
with self.assertRaisesMessage(ValidationError, msg) as cm: |
| 1036 |
constraint.validate( |
| 1037 |
UniqueConstraintConditionProduct, |
| 1038 |
UniqueConstraintConditionProduct(name=p1.name, color=None), |
| 1039 |
) |
| 1040 |
self.assertEqual(cm.exception.code, "custom_code") |
| 1041 |
|
| 1042 |
def test_validate_expression(self): |
| 1043 |
constraint = models.UniqueConstraint(Lower("name"), name="name_lower_uniq") |
| 1044 |
msg = "Constraint “name_lower_uniq” is violated." |
| 1045 |
with self.assertRaisesMessage(ValidationError, msg): |
| 1046 |
constraint.validate( |
| 1047 |
UniqueConstraintProduct, |
| 1048 |
UniqueConstraintProduct(name=self.p1.name.upper()), |
| 1049 |
) |
| 1050 |
constraint.validate( |
| 1051 |
UniqueConstraintProduct, |
| 1052 |
UniqueConstraintProduct(name="another-name"), |
| 1053 |
) |
| 1054 |
# Existing instances have their existing row excluded. |
| 1055 |
constraint.validate(UniqueConstraintProduct, self.p1) |
| 1056 |
# Unique field is excluded. |
| 1057 |
constraint.validate( |
| 1058 |
UniqueConstraintProduct, |
| 1059 |
UniqueConstraintProduct(name=self.p1.name.upper()), |
| 1060 |
exclude={"name"}, |
| 1061 |
) |
| 1062 |
|
| 1063 |
def test_validate_field_transform(self): |
| 1064 |
updated_date = datetime(2005, 7, 26) |
| 1065 |
UniqueConstraintProduct.objects.create(name="p1", updated=updated_date) |
| 1066 |
constraint = models.UniqueConstraint( |
| 1067 |
models.F("updated__date"), name="date_created_unique" |
| 1068 |
) |
| 1069 |
msg = "Constraint “date_created_unique” is violated." |
| 1070 |
with self.assertRaisesMessage(ValidationError, msg): |
| 1071 |
constraint.validate( |
| 1072 |
UniqueConstraintProduct, |
| 1073 |
UniqueConstraintProduct(updated=updated_date), |
| 1074 |
) |
| 1075 |
constraint.validate( |
| 1076 |
UniqueConstraintProduct, |
| 1077 |
UniqueConstraintProduct(updated=updated_date + timedelta(days=1)), |
| 1078 |
) |
| 1079 |
|
| 1080 |
def test_validate_case_when(self): |
| 1081 |
UniqueConstraintProduct.objects.create(name="p1") |
| 1082 |
constraint = models.UniqueConstraint( |
| 1083 |
Case(When(color__isnull=True, then=F("name"))), |
| 1084 |
name="name_without_color_uniq", |
| 1085 |
) |
| 1086 |
msg = "Constraint “name_without_color_uniq” is violated." |
| 1087 |
with self.assertRaisesMessage(ValidationError, msg): |
| 1088 |
constraint.validate( |
| 1089 |
UniqueConstraintProduct, |
| 1090 |
UniqueConstraintProduct(name="p1"), |
| 1091 |
) |
| 1092 |
constraint.validate( |
| 1093 |
UniqueConstraintProduct, |
| 1094 |
UniqueConstraintProduct(name="p1", color="green"), |
| 1095 |
) |
| 1096 |
|
| 1097 |
def test_validate_ordered_expression(self): |
| 1098 |
constraint = models.UniqueConstraint( |
| 1099 |
Lower("name").desc(), name="name_lower_uniq_desc" |
| 1100 |
) |
| 1101 |
msg = "Constraint “name_lower_uniq_desc” is violated." |
| 1102 |
with self.assertRaisesMessage(ValidationError, msg): |
| 1103 |
constraint.validate( |
| 1104 |
UniqueConstraintProduct, |
| 1105 |
UniqueConstraintProduct(name=self.p1.name.upper()), |
| 1106 |
) |
| 1107 |
constraint.validate( |
| 1108 |
UniqueConstraintProduct, |
| 1109 |
UniqueConstraintProduct(name="another-name"), |
| 1110 |
) |
| 1111 |
# Existing instances have their existing row excluded. |
| 1112 |
constraint.validate(UniqueConstraintProduct, self.p1) |
| 1113 |
# Unique field is excluded. |
| 1114 |
constraint.validate( |
| 1115 |
UniqueConstraintProduct, |
| 1116 |
UniqueConstraintProduct(name=self.p1.name.upper()), |
| 1117 |
exclude={"name"}, |
| 1118 |
) |
| 1119 |
|
| 1120 |
def test_validate_expression_condition(self): |
| 1121 |
constraint = models.UniqueConstraint( |
| 1122 |
Lower("name"), |
| 1123 |
name="name_lower_without_color_uniq", |
| 1124 |
condition=models.Q(color__isnull=True), |
| 1125 |
) |
| 1126 |
non_unique_product = UniqueConstraintProduct(name=self.p2.name.upper()) |
| 1127 |
msg = "Constraint “name_lower_without_color_uniq” is violated." |
| 1128 |
with self.assertRaisesMessage(ValidationError, msg): |
| 1129 |
constraint.validate(UniqueConstraintProduct, non_unique_product) |
| 1130 |
# Values not matching condition are ignored. |
| 1131 |
constraint.validate( |
| 1132 |
UniqueConstraintProduct, |
| 1133 |
UniqueConstraintProduct(name=self.p1.name, color=self.p1.color), |
| 1134 |
) |
| 1135 |
# Existing instances have their existing row excluded. |
| 1136 |
constraint.validate(UniqueConstraintProduct, self.p2) |
| 1137 |
# Unique field is excluded. |
| 1138 |
constraint.validate( |
| 1139 |
UniqueConstraintProduct, |
| 1140 |
non_unique_product, |
| 1141 |
exclude={"name"}, |
| 1142 |
) |
| 1143 |
# Field from a condition is excluded. |
| 1144 |
constraint.validate( |
| 1145 |
UniqueConstraintProduct, |
| 1146 |
non_unique_product, |
| 1147 |
exclude={"color"}, |
| 1148 |
) |
| 1149 |
|
| 1150 |
def test_validate_expression_str(self): |
| 1151 |
constraint = models.UniqueConstraint("name", name="name_uniq") |
| 1152 |
msg = "Constraint “name_uniq” is violated." |
| 1153 |
with self.assertRaisesMessage(ValidationError, msg): |
| 1154 |
constraint.validate( |
| 1155 |
UniqueConstraintProduct, |
| 1156 |
UniqueConstraintProduct(name=self.p1.name), |
| 1157 |
) |
| 1158 |
constraint.validate( |
| 1159 |
UniqueConstraintProduct, |
| 1160 |
UniqueConstraintProduct(name=self.p1.name), |
| 1161 |
exclude={"name"}, |
| 1162 |
) |
| 1163 |
|
| 1164 |
@skipUnlessDBFeature("supports_stored_generated_columns") |
| 1165 |
def test_validate_expression_generated_field_stored(self): |
| 1166 |
self.assertGeneratedFieldWithExpressionIsValidated( |
| 1167 |
model=GeneratedFieldStoredProduct |
| 1168 |
) |
| 1169 |
|
| 1170 |
@skipUnlessDBFeature("supports_virtual_generated_columns") |
| 1171 |
def test_validate_expression_generated_field_virtual(self): |
| 1172 |
self.assertGeneratedFieldWithExpressionIsValidated( |
| 1173 |
model=GeneratedFieldVirtualProduct |
| 1174 |
) |
| 1175 |
|
| 1176 |
def assertGeneratedFieldWithExpressionIsValidated(self, model): |
| 1177 |
constraint = UniqueConstraint(Sqrt("rebate"), name="unique_rebate_sqrt") |
| 1178 |
model.objects.create(price=100, discounted_price=84) |
| 1179 |
|
| 1180 |
valid_product = model(price=100, discounted_price=75) |
| 1181 |
constraint.validate(model, valid_product) |
| 1182 |
|
| 1183 |
invalid_product = model(price=20, discounted_price=4) |
| 1184 |
with self.assertRaisesMessage( |
| 1185 |
ValidationError, f"Constraint “{constraint.name}” is violated." |
| 1186 |
): |
| 1187 |
constraint.validate(model, invalid_product) |
| 1188 |
|
| 1189 |
# Excluding referenced or generated fields should skip validation. |
| 1190 |
constraint.validate(model, invalid_product, exclude={"rebate"}) |
| 1191 |
constraint.validate(model, invalid_product, exclude={"price"}) |
| 1192 |
|
| 1193 |
@skipUnlessDBFeature("supports_stored_generated_columns") |
| 1194 |
def test_validate_fields_generated_field_stored(self): |
| 1195 |
self.assertGeneratedFieldWithFieldsIsValidated( |
| 1196 |
model=GeneratedFieldStoredProduct |
| 1197 |
) |
| 1198 |
|
| 1199 |
@skipUnlessDBFeature("supports_virtual_generated_columns") |
| 1200 |
def test_validate_fields_generated_field_virtual(self): |
| 1201 |
self.assertGeneratedFieldWithFieldsIsValidated( |
| 1202 |
model=GeneratedFieldVirtualProduct |
| 1203 |
) |
| 1204 |
|
| 1205 |
def assertGeneratedFieldWithFieldsIsValidated(self, model): |
| 1206 |
constraint = models.UniqueConstraint( |
| 1207 |
fields=["lower_name"], name="lower_name_unique" |
| 1208 |
) |
| 1209 |
model.objects.create(name="Box") |
| 1210 |
constraint.validate(model, model(name="Case")) |
| 1211 |
|
| 1212 |
invalid_product = model(name="BOX") |
| 1213 |
msg = str(invalid_product.unique_error_message(model, ["lower_name"])) |
| 1214 |
with self.assertRaisesMessage(ValidationError, msg): |
| 1215 |
constraint.validate(model, invalid_product) |
| 1216 |
|
| 1217 |
# Excluding referenced or generated fields should skip validation. |
| 1218 |
constraint.validate(model, invalid_product, exclude={"lower_name"}) |
| 1219 |
constraint.validate(model, invalid_product, exclude={"name"}) |
| 1220 |
|
| 1221 |
@skipUnlessDBFeature("supports_stored_generated_columns") |
| 1222 |
def test_validate_fields_generated_field_stored_nulls_distinct(self): |
| 1223 |
self.assertGeneratedFieldNullsDistinctIsValidated( |
| 1224 |
model=GeneratedFieldStoredProduct |
| 1225 |
) |
| 1226 |
|
| 1227 |
@skipUnlessDBFeature("supports_virtual_generated_columns") |
| 1228 |
def test_validate_fields_generated_field_virtual_nulls_distinct(self): |
| 1229 |
self.assertGeneratedFieldNullsDistinctIsValidated( |
| 1230 |
model=GeneratedFieldVirtualProduct |
| 1231 |
) |
| 1232 |
|
| 1233 |
def assertGeneratedFieldNullsDistinctIsValidated(self, model): |
| 1234 |
constraint = models.UniqueConstraint( |
| 1235 |
fields=["lower_name"], |
| 1236 |
name="lower_name_unique_nulls_distinct", |
| 1237 |
nulls_distinct=False, |
| 1238 |
) |
| 1239 |
model.objects.create(name=None) |
| 1240 |
valid_product = model(name="Box") |
| 1241 |
constraint.validate(model, valid_product) |
| 1242 |
|
| 1243 |
invalid_product = model(name=None) |
| 1244 |
msg = str(invalid_product.unique_error_message(model, ["lower_name"])) |
| 1245 |
with self.assertRaisesMessage(ValidationError, msg): |
| 1246 |
constraint.validate(model, invalid_product) |
| 1247 |
|
| 1248 |
@skipUnlessDBFeature("supports_table_check_constraints") |
| 1249 |
def test_validate_nullable_textfield_with_isnull_true(self): |
| 1250 |
is_null_constraint = models.UniqueConstraint( |
| 1251 |
"price", |
| 1252 |
"discounted_price", |
| 1253 |
condition=models.Q(unit__isnull=True), |
| 1254 |
name="uniq_prices_no_unit", |
| 1255 |
) |
| 1256 |
is_not_null_constraint = models.UniqueConstraint( |
| 1257 |
"price", |
| 1258 |
"discounted_price", |
| 1259 |
condition=models.Q(unit__isnull=False), |
| 1260 |
name="uniq_prices_unit", |
| 1261 |
) |
| 1262 |
|
| 1263 |
Product.objects.create(price=2, discounted_price=1) |
| 1264 |
Product.objects.create(price=4, discounted_price=3, unit="ng/mL") |
| 1265 |
|
| 1266 |
msg = "Constraint “uniq_prices_no_unit” is violated." |
| 1267 |
with self.assertRaisesMessage(ValidationError, msg): |
| 1268 |
is_null_constraint.validate( |
| 1269 |
Product, Product(price=2, discounted_price=1, unit=None) |
| 1270 |
) |
| 1271 |
is_null_constraint.validate( |
| 1272 |
Product, Product(price=2, discounted_price=1, unit="ng/mL") |
| 1273 |
) |
| 1274 |
is_null_constraint.validate(Product, Product(price=4, discounted_price=3)) |
| 1275 |
|
| 1276 |
msg = "Constraint “uniq_prices_unit” is violated." |
| 1277 |
with self.assertRaisesMessage(ValidationError, msg): |
| 1278 |
is_not_null_constraint.validate( |
| 1279 |
Product, |
| 1280 |
Product(price=4, discounted_price=3, unit="μg/mL"), |
| 1281 |
) |
| 1282 |
is_not_null_constraint.validate(Product, Product(price=4, discounted_price=3)) |
| 1283 |
is_not_null_constraint.validate(Product, Product(price=2, discounted_price=1)) |
| 1284 |
|
| 1285 |
@skipUnlessDBFeature("supports_table_check_constraints") |
| 1286 |
def test_validate_nulls_distinct_fields(self): |
| 1287 |
Product.objects.create(price=42) |
| 1288 |
constraint = models.UniqueConstraint( |
| 1289 |
fields=["price"], |
| 1290 |
nulls_distinct=False, |
| 1291 |
name="uniq_prices_nulls_distinct", |
| 1292 |
) |
| 1293 |
constraint.validate(Product, Product(price=None)) |
| 1294 |
Product.objects.create(price=None) |
| 1295 |
msg = "Product with this Price already exists." |
| 1296 |
with self.assertRaisesMessage(ValidationError, msg): |
| 1297 |
constraint.validate(Product, Product(price=None)) |
| 1298 |
|
| 1299 |
@skipUnlessDBFeature("supports_table_check_constraints") |
| 1300 |
def test_validate_nulls_distinct_expressions(self): |
| 1301 |
Product.objects.create(price=42) |
| 1302 |
constraint = models.UniqueConstraint( |
| 1303 |
Abs("price"), |
| 1304 |
nulls_distinct=False, |
| 1305 |
name="uniq_prices_nulls_distinct", |
| 1306 |
) |
| 1307 |
constraint.validate(Product, Product(price=None)) |
| 1308 |
Product.objects.create(price=None) |
| 1309 |
msg = f"Constraint “{constraint.name}” is violated." |
| 1310 |
with self.assertRaisesMessage(ValidationError, msg): |
| 1311 |
constraint.validate(Product, Product(price=None)) |
| 1312 |
|
| 1313 |
def test_name(self): |
| 1314 |
constraints = get_constraints(UniqueConstraintProduct._meta.db_table) |
| 1315 |
expected_name = "name_color_uniq" |
| 1316 |
self.assertIn(expected_name, constraints) |
| 1317 |
|
| 1318 |
def test_condition_must_be_q(self): |
| 1319 |
with self.assertRaisesMessage( |
| 1320 |
ValueError, "UniqueConstraint.condition must be a Q instance." |
| 1321 |
): |
| 1322 |
models.UniqueConstraint(name="uniq", fields=["name"], condition="invalid") |
| 1323 |
|
| 1324 |
@skipUnlessDBFeature("supports_deferrable_unique_constraints") |
| 1325 |
def test_initially_deferred_database_constraint(self): |
| 1326 |
obj_1 = UniqueConstraintDeferrable.objects.create(name="p1", shelf="front") |
| 1327 |
obj_2 = UniqueConstraintDeferrable.objects.create(name="p2", shelf="back") |
| 1328 |
|
| 1329 |
def swap(): |
| 1330 |
obj_1.name, obj_2.name = obj_2.name, obj_1.name |
| 1331 |
obj_1.save() |
| 1332 |
obj_2.save() |
| 1333 |
|
| 1334 |
swap() |
| 1335 |
# Behavior can be changed with SET CONSTRAINTS. |
| 1336 |
with self.assertRaises(IntegrityError): |
| 1337 |
with atomic(), connection.cursor() as cursor: |
| 1338 |
constraint_name = connection.ops.quote_name("name_init_deferred_uniq") |
| 1339 |
cursor.execute("SET CONSTRAINTS %s IMMEDIATE" % constraint_name) |
| 1340 |
swap() |
| 1341 |
|
| 1342 |
@skipUnlessDBFeature("supports_deferrable_unique_constraints") |
| 1343 |
def test_initially_immediate_database_constraint(self): |
| 1344 |
obj_1 = UniqueConstraintDeferrable.objects.create(name="p1", shelf="front") |
| 1345 |
obj_2 = UniqueConstraintDeferrable.objects.create(name="p2", shelf="back") |
| 1346 |
obj_1.shelf, obj_2.shelf = obj_2.shelf, obj_1.shelf |
| 1347 |
with self.assertRaises(IntegrityError), atomic(): |
| 1348 |
obj_1.save() |
| 1349 |
# Behavior can be changed with SET CONSTRAINTS. |
| 1350 |
with connection.cursor() as cursor: |
| 1351 |
constraint_name = connection.ops.quote_name("sheld_init_immediate_uniq") |
| 1352 |
cursor.execute("SET CONSTRAINTS %s DEFERRED" % constraint_name) |
| 1353 |
obj_1.save() |
| 1354 |
obj_2.save() |
| 1355 |
|
| 1356 |
def test_deferrable_with_condition(self): |
| 1357 |
message = "UniqueConstraint with conditions cannot be deferred." |
| 1358 |
with self.assertRaisesMessage(ValueError, message): |
| 1359 |
models.UniqueConstraint( |
| 1360 |
fields=["name"], |
| 1361 |
name="name_without_color_unique", |
| 1362 |
condition=models.Q(color__isnull=True), |
| 1363 |
deferrable=models.Deferrable.DEFERRED, |
| 1364 |
) |
| 1365 |
|
| 1366 |
def test_deferrable_with_include(self): |
| 1367 |
message = "UniqueConstraint with include fields cannot be deferred." |
| 1368 |
with self.assertRaisesMessage(ValueError, message): |
| 1369 |
models.UniqueConstraint( |
| 1370 |
fields=["name"], |
| 1371 |
name="name_inc_color_color_unique", |
| 1372 |
include=["color"], |
| 1373 |
deferrable=models.Deferrable.DEFERRED, |
| 1374 |
) |
| 1375 |
|
| 1376 |
def test_deferrable_with_opclasses(self): |
| 1377 |
message = "UniqueConstraint with opclasses cannot be deferred." |
| 1378 |
with self.assertRaisesMessage(ValueError, message): |
| 1379 |
models.UniqueConstraint( |
| 1380 |
fields=["name"], |
| 1381 |
name="name_text_pattern_ops_unique", |
| 1382 |
opclasses=["text_pattern_ops"], |
| 1383 |
deferrable=models.Deferrable.DEFERRED, |
| 1384 |
) |
| 1385 |
|
| 1386 |
def test_deferrable_with_expressions(self): |
| 1387 |
message = "UniqueConstraint with expressions cannot be deferred." |
| 1388 |
with self.assertRaisesMessage(ValueError, message): |
| 1389 |
models.UniqueConstraint( |
| 1390 |
Lower("name"), |
| 1391 |
name="deferred_expression_unique", |
| 1392 |
deferrable=models.Deferrable.DEFERRED, |
| 1393 |
) |
| 1394 |
|
| 1395 |
def test_invalid_defer_argument(self): |
| 1396 |
message = "UniqueConstraint.deferrable must be a Deferrable instance." |
| 1397 |
with self.assertRaisesMessage(TypeError, message): |
| 1398 |
models.UniqueConstraint( |
| 1399 |
fields=["name"], |
| 1400 |
name="name_invalid", |
| 1401 |
deferrable="invalid", |
| 1402 |
) |
| 1403 |
|
| 1404 |
@skipUnlessDBFeature( |
| 1405 |
"supports_table_check_constraints", |
| 1406 |
"supports_covering_indexes", |
| 1407 |
) |
| 1408 |
def test_include_database_constraint(self): |
| 1409 |
UniqueConstraintInclude.objects.create(name="p1", color="red") |
| 1410 |
with self.assertRaises(IntegrityError): |
| 1411 |
UniqueConstraintInclude.objects.create(name="p1", color="blue") |
| 1412 |
|
| 1413 |
def test_invalid_include_argument(self): |
| 1414 |
msg = "UniqueConstraint.include must be a list or tuple." |
| 1415 |
with self.assertRaisesMessage(TypeError, msg): |
| 1416 |
models.UniqueConstraint( |
| 1417 |
name="uniq_include", |
| 1418 |
fields=["field"], |
| 1419 |
include="other", |
| 1420 |
) |
| 1421 |
|
| 1422 |
def test_invalid_opclasses_argument(self): |
| 1423 |
msg = "UniqueConstraint.opclasses must be a list or tuple." |
| 1424 |
with self.assertRaisesMessage(TypeError, msg): |
| 1425 |
models.UniqueConstraint( |
| 1426 |
name="uniq_opclasses", |
| 1427 |
fields=["field"], |
| 1428 |
opclasses="jsonb_path_ops", |
| 1429 |
) |
| 1430 |
|
| 1431 |
def test_invalid_nulls_distinct_argument(self): |
| 1432 |
msg = "UniqueConstraint.nulls_distinct must be a bool." |
| 1433 |
with self.assertRaisesMessage(TypeError, msg): |
| 1434 |
models.UniqueConstraint( |
| 1435 |
name="uniq_opclasses", fields=["field"], nulls_distinct="NULLS DISTINCT" |
| 1436 |
) |
| 1437 |
|
| 1438 |
def test_opclasses_and_fields_same_length(self): |
| 1439 |
msg = ( |
| 1440 |
"UniqueConstraint.fields and UniqueConstraint.opclasses must have " |
| 1441 |
"the same number of elements." |
| 1442 |
) |
| 1443 |
with self.assertRaisesMessage(ValueError, msg): |
| 1444 |
models.UniqueConstraint( |
| 1445 |
name="uniq_opclasses", |
| 1446 |
fields=["field"], |
| 1447 |
opclasses=["foo", "bar"], |
| 1448 |
) |
| 1449 |
|
| 1450 |
def test_requires_field_or_expression(self): |
| 1451 |
msg = ( |
| 1452 |
"At least one field or expression is required to define a unique " |
| 1453 |
"constraint." |
| 1454 |
) |
| 1455 |
with self.assertRaisesMessage(ValueError, msg): |
| 1456 |
models.UniqueConstraint(name="name") |
| 1457 |
|
| 1458 |
def test_expressions_and_fields_mutually_exclusive(self): |
| 1459 |
msg = "UniqueConstraint.fields and expressions are mutually exclusive." |
| 1460 |
with self.assertRaisesMessage(ValueError, msg): |
| 1461 |
models.UniqueConstraint(Lower("field_1"), fields=["field_2"], name="name") |
| 1462 |
|
| 1463 |
def test_expressions_with_opclasses(self): |
| 1464 |
msg = ( |
| 1465 |
"UniqueConstraint.opclasses cannot be used with expressions. Use " |
| 1466 |
"django.contrib.postgres.indexes.OpClass() instead." |
| 1467 |
) |
| 1468 |
with self.assertRaisesMessage(ValueError, msg): |
| 1469 |
models.UniqueConstraint( |
| 1470 |
Lower("field"), |
| 1471 |
name="test_func_opclass", |
| 1472 |
opclasses=["jsonb_path_ops"], |
| 1473 |
) |
| 1474 |
|
| 1475 |
def test_requires_name(self): |
| 1476 |
msg = "A unique constraint must be named." |
| 1477 |
with self.assertRaisesMessage(ValueError, msg): |
| 1478 |
models.UniqueConstraint(fields=["field"]) |
| 1479 |
|
| 1480 |
def test_database_default(self): |
| 1481 |
models.UniqueConstraint( |
| 1482 |
fields=["field_with_db_default"], name="unique_field_with_db_default" |
| 1483 |
).validate(ModelWithDatabaseDefault, ModelWithDatabaseDefault()) |
| 1484 |
models.UniqueConstraint( |
| 1485 |
Upper("field_with_db_default"), |
| 1486 |
name="unique_field_with_db_default_expression", |
| 1487 |
).validate(ModelWithDatabaseDefault, ModelWithDatabaseDefault()) |
| 1488 |
|
| 1489 |
ModelWithDatabaseDefault.objects.create() |
| 1490 |
|
| 1491 |
msg = ( |
| 1492 |
"Model with database default with this Field with db default already " |
| 1493 |
"exists." |
| 1494 |
) |
| 1495 |
with self.assertRaisesMessage(ValidationError, msg): |
| 1496 |
models.UniqueConstraint( |
| 1497 |
fields=["field_with_db_default"], name="unique_field_with_db_default" |
| 1498 |
).validate(ModelWithDatabaseDefault, ModelWithDatabaseDefault()) |
| 1499 |
|
| 1500 |
msg = "Constraint “unique_field_with_db_default_expression” is violated." |
| 1501 |
with self.assertRaisesMessage(ValidationError, msg): |
| 1502 |
models.UniqueConstraint( |
| 1503 |
Upper("field_with_db_default"), |
| 1504 |
name="unique_field_with_db_default_expression", |
| 1505 |
).validate(ModelWithDatabaseDefault, ModelWithDatabaseDefault()) |