| 1 |
import time |
| 2 |
import traceback |
| 3 |
from datetime import date, datetime, timedelta |
| 4 |
from threading import Event, Thread, Timer |
| 5 |
from unittest.mock import patch |
| 6 |
|
| 7 |
from django.core.exceptions import FieldError |
| 8 |
from django.db import DatabaseError, IntegrityError, connection |
| 9 |
from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature |
| 10 |
from django.test.utils import CaptureQueriesContext |
| 11 |
from django.utils.functional import lazy |
| 12 |
|
| 13 |
from .models import ( |
| 14 |
Author, |
| 15 |
Book, |
| 16 |
DefaultPerson, |
| 17 |
Journalist, |
| 18 |
ManualPrimaryKeyTest, |
| 19 |
Person, |
| 20 |
Profile, |
| 21 |
Publisher, |
| 22 |
Tag, |
| 23 |
Thing, |
| 24 |
) |
| 25 |
|
| 26 |
|
| 27 |
class GetOrCreateTests(TestCase): |
| 28 |
@classmethod |
| 29 |
def setUpTestData(cls): |
| 30 |
Person.objects.create( |
| 31 |
first_name="John", last_name="Lennon", birthday=date(1940, 10, 9) |
| 32 |
) |
| 33 |
|
| 34 |
def test_get_or_create_method_with_get(self): |
| 35 |
created = Person.objects.get_or_create( |
| 36 |
first_name="John", |
| 37 |
last_name="Lennon", |
| 38 |
defaults={"birthday": date(1940, 10, 9)}, |
| 39 |
)[1] |
| 40 |
self.assertFalse(created) |
| 41 |
self.assertEqual(Person.objects.count(), 1) |
| 42 |
|
| 43 |
def test_get_or_create_method_with_create(self): |
| 44 |
created = Person.objects.get_or_create( |
| 45 |
first_name="George", |
| 46 |
last_name="Harrison", |
| 47 |
defaults={"birthday": date(1943, 2, 25)}, |
| 48 |
)[1] |
| 49 |
self.assertTrue(created) |
| 50 |
self.assertEqual(Person.objects.count(), 2) |
| 51 |
|
| 52 |
def test_get_or_create_redundant_instance(self): |
| 53 |
""" |
| 54 |
If we execute the exact same statement twice, the second time, |
| 55 |
it won't create a Person. |
| 56 |
""" |
| 57 |
Person.objects.get_or_create( |
| 58 |
first_name="George", |
| 59 |
last_name="Harrison", |
| 60 |
defaults={"birthday": date(1943, 2, 25)}, |
| 61 |
) |
| 62 |
created = Person.objects.get_or_create( |
| 63 |
first_name="George", |
| 64 |
last_name="Harrison", |
| 65 |
defaults={"birthday": date(1943, 2, 25)}, |
| 66 |
)[1] |
| 67 |
|
| 68 |
self.assertFalse(created) |
| 69 |
self.assertEqual(Person.objects.count(), 2) |
| 70 |
|
| 71 |
def test_get_or_create_invalid_params(self): |
| 72 |
""" |
| 73 |
If you don't specify a value or default value for all required |
| 74 |
fields, you will get an error. |
| 75 |
""" |
| 76 |
with self.assertRaises(IntegrityError): |
| 77 |
Person.objects.get_or_create(first_name="Tom", last_name="Smith") |
| 78 |
|
| 79 |
def test_get_or_create_with_pk_property(self): |
| 80 |
""" |
| 81 |
Using the pk property of a model is allowed. |
| 82 |
""" |
| 83 |
Thing.objects.get_or_create(pk=1) |
| 84 |
|
| 85 |
def test_get_or_create_with_model_property_defaults(self): |
| 86 |
"""Using a property with a setter implemented is allowed.""" |
| 87 |
t, _ = Thing.objects.get_or_create( |
| 88 |
defaults={"capitalized_name_property": "annie"}, pk=1 |
| 89 |
) |
| 90 |
self.assertEqual(t.name, "Annie") |
| 91 |
|
| 92 |
def test_get_or_create_on_related_manager(self): |
| 93 |
p = Publisher.objects.create(name="Acme Publishing") |
| 94 |
# Create a book through the publisher. |
| 95 |
book, created = p.books.get_or_create(name="The Book of Ed & Fred") |
| 96 |
self.assertTrue(created) |
| 97 |
# The publisher should have one book. |
| 98 |
self.assertEqual(p.books.count(), 1) |
| 99 |
|
| 100 |
# Try get_or_create again, this time nothing should be created. |
| 101 |
book, created = p.books.get_or_create(name="The Book of Ed & Fred") |
| 102 |
self.assertFalse(created) |
| 103 |
# And the publisher should still have one book. |
| 104 |
self.assertEqual(p.books.count(), 1) |
| 105 |
|
| 106 |
# Add an author to the book. |
| 107 |
ed, created = book.authors.get_or_create(name="Ed") |
| 108 |
self.assertTrue(created) |
| 109 |
# The book should have one author. |
| 110 |
self.assertEqual(book.authors.count(), 1) |
| 111 |
|
| 112 |
# Try get_or_create again, this time nothing should be created. |
| 113 |
ed, created = book.authors.get_or_create(name="Ed") |
| 114 |
self.assertFalse(created) |
| 115 |
# And the book should still have one author. |
| 116 |
self.assertEqual(book.authors.count(), 1) |
| 117 |
|
| 118 |
# Add a second author to the book. |
| 119 |
fred, created = book.authors.get_or_create(name="Fred") |
| 120 |
self.assertTrue(created) |
| 121 |
|
| 122 |
# The book should have two authors now. |
| 123 |
self.assertEqual(book.authors.count(), 2) |
| 124 |
|
| 125 |
# Create an Author not tied to any books. |
| 126 |
Author.objects.create(name="Ted") |
| 127 |
|
| 128 |
# There should be three Authors in total. The book object should have two. |
| 129 |
self.assertEqual(Author.objects.count(), 3) |
| 130 |
self.assertEqual(book.authors.count(), 2) |
| 131 |
|
| 132 |
# Try creating a book through an author. |
| 133 |
_, created = ed.books.get_or_create(name="Ed's Recipes", publisher=p) |
| 134 |
self.assertTrue(created) |
| 135 |
|
| 136 |
# Now Ed has two Books, Fred just one. |
| 137 |
self.assertEqual(ed.books.count(), 2) |
| 138 |
self.assertEqual(fred.books.count(), 1) |
| 139 |
|
| 140 |
# Use the publisher's primary key value instead of a model instance. |
| 141 |
_, created = ed.books.get_or_create( |
| 142 |
name="The Great Book of Ed", publisher_id=p.id |
| 143 |
) |
| 144 |
self.assertTrue(created) |
| 145 |
|
| 146 |
# Try get_or_create again, this time nothing should be created. |
| 147 |
_, created = ed.books.get_or_create( |
| 148 |
name="The Great Book of Ed", publisher_id=p.id |
| 149 |
) |
| 150 |
self.assertFalse(created) |
| 151 |
|
| 152 |
# The publisher should have three books. |
| 153 |
self.assertEqual(p.books.count(), 3) |
| 154 |
|
| 155 |
def test_defaults_exact(self): |
| 156 |
""" |
| 157 |
If you have a field named defaults and want to use it as an exact |
| 158 |
lookup, you need to use 'defaults__exact'. |
| 159 |
""" |
| 160 |
obj, created = Person.objects.get_or_create( |
| 161 |
first_name="George", |
| 162 |
last_name="Harrison", |
| 163 |
defaults__exact="testing", |
| 164 |
defaults={ |
| 165 |
"birthday": date(1943, 2, 25), |
| 166 |
"defaults": "testing", |
| 167 |
}, |
| 168 |
) |
| 169 |
self.assertTrue(created) |
| 170 |
self.assertEqual(obj.defaults, "testing") |
| 171 |
obj2, created = Person.objects.get_or_create( |
| 172 |
first_name="George", |
| 173 |
last_name="Harrison", |
| 174 |
defaults__exact="testing", |
| 175 |
defaults={ |
| 176 |
"birthday": date(1943, 2, 25), |
| 177 |
"defaults": "testing", |
| 178 |
}, |
| 179 |
) |
| 180 |
self.assertFalse(created) |
| 181 |
self.assertEqual(obj, obj2) |
| 182 |
|
| 183 |
def test_callable_defaults(self): |
| 184 |
""" |
| 185 |
Callables in `defaults` are evaluated if the instance is created. |
| 186 |
""" |
| 187 |
obj, created = Person.objects.get_or_create( |
| 188 |
first_name="George", |
| 189 |
defaults={"last_name": "Harrison", "birthday": lambda: date(1943, 2, 25)}, |
| 190 |
) |
| 191 |
self.assertTrue(created) |
| 192 |
self.assertEqual(date(1943, 2, 25), obj.birthday) |
| 193 |
|
| 194 |
def test_callable_defaults_not_called(self): |
| 195 |
def raise_exception(): |
| 196 |
raise AssertionError |
| 197 |
|
| 198 |
obj, created = Person.objects.get_or_create( |
| 199 |
first_name="John", |
| 200 |
last_name="Lennon", |
| 201 |
defaults={"birthday": lambda: raise_exception()}, |
| 202 |
) |
| 203 |
|
| 204 |
def test_defaults_not_evaluated_unless_needed(self): |
| 205 |
"""`defaults` aren't evaluated if the instance isn't created.""" |
| 206 |
|
| 207 |
def raise_exception(): |
| 208 |
raise AssertionError |
| 209 |
|
| 210 |
obj, created = Person.objects.get_or_create( |
| 211 |
first_name="John", |
| 212 |
defaults=lazy(raise_exception, object)(), |
| 213 |
) |
| 214 |
self.assertFalse(created) |
| 215 |
|
| 216 |
|
| 217 |
class GetOrCreateTestsWithManualPKs(TestCase): |
| 218 |
@classmethod |
| 219 |
def setUpTestData(cls): |
| 220 |
ManualPrimaryKeyTest.objects.create(id=1, data="Original") |
| 221 |
|
| 222 |
def test_create_with_duplicate_primary_key(self): |
| 223 |
""" |
| 224 |
If you specify an existing primary key, but different other fields, |
| 225 |
then you will get an error and data will not be updated. |
| 226 |
""" |
| 227 |
with self.assertRaises(IntegrityError): |
| 228 |
ManualPrimaryKeyTest.objects.get_or_create(id=1, data="Different") |
| 229 |
self.assertEqual(ManualPrimaryKeyTest.objects.get(id=1).data, "Original") |
| 230 |
|
| 231 |
def test_savepoint_rollback(self): |
| 232 |
""" |
| 233 |
The database connection is still usable after a DatabaseError in |
| 234 |
get_or_create() (#20463). |
| 235 |
""" |
| 236 |
Tag.objects.create(text="foo") |
| 237 |
with self.assertRaises(DatabaseError): |
| 238 |
# pk 123456789 doesn't exist, so the tag object will be created. |
| 239 |
# Saving triggers a unique constraint violation on 'text'. |
| 240 |
Tag.objects.get_or_create(pk=123456789, defaults={"text": "foo"}) |
| 241 |
# Tag objects can be created after the error. |
| 242 |
Tag.objects.create(text="bar") |
| 243 |
|
| 244 |
def test_get_or_create_empty(self): |
| 245 |
""" |
| 246 |
If all the attributes on a model have defaults, get_or_create() doesn't |
| 247 |
require any arguments. |
| 248 |
""" |
| 249 |
DefaultPerson.objects.get_or_create() |
| 250 |
|
| 251 |
|
| 252 |
class GetOrCreateTransactionTests(TransactionTestCase): |
| 253 |
available_apps = ["get_or_create"] |
| 254 |
|
| 255 |
def test_get_or_create_integrityerror(self): |
| 256 |
""" |
| 257 |
Regression test for #15117. Requires a TransactionTestCase on |
| 258 |
databases that delay integrity checks until the end of transactions, |
| 259 |
otherwise the exception is never raised. |
| 260 |
""" |
| 261 |
try: |
| 262 |
Profile.objects.get_or_create(person=Person(id=1)) |
| 263 |
except IntegrityError: |
| 264 |
pass |
| 265 |
else: |
| 266 |
self.skipTest("This backend does not support integrity checks.") |
| 267 |
|
| 268 |
|
| 269 |
class GetOrCreateThroughManyToMany(TestCase): |
| 270 |
def test_get_get_or_create(self): |
| 271 |
tag = Tag.objects.create(text="foo") |
| 272 |
a_thing = Thing.objects.create(name="a") |
| 273 |
a_thing.tags.add(tag) |
| 274 |
obj, created = a_thing.tags.get_or_create(text="foo") |
| 275 |
|
| 276 |
self.assertFalse(created) |
| 277 |
self.assertEqual(obj.pk, tag.pk) |
| 278 |
|
| 279 |
def test_create_get_or_create(self): |
| 280 |
a_thing = Thing.objects.create(name="a") |
| 281 |
obj, created = a_thing.tags.get_or_create(text="foo") |
| 282 |
|
| 283 |
self.assertTrue(created) |
| 284 |
self.assertEqual(obj.text, "foo") |
| 285 |
self.assertIn(obj, a_thing.tags.all()) |
| 286 |
|
| 287 |
def test_something(self): |
| 288 |
Tag.objects.create(text="foo") |
| 289 |
a_thing = Thing.objects.create(name="a") |
| 290 |
with self.assertRaises(IntegrityError): |
| 291 |
a_thing.tags.get_or_create(text="foo") |
| 292 |
|
| 293 |
|
| 294 |
class UpdateOrCreateTests(TestCase): |
| 295 |
def test_update(self): |
| 296 |
Person.objects.create( |
| 297 |
first_name="John", last_name="Lennon", birthday=date(1940, 10, 9) |
| 298 |
) |
| 299 |
p, created = Person.objects.update_or_create( |
| 300 |
first_name="John", |
| 301 |
last_name="Lennon", |
| 302 |
defaults={"birthday": date(1940, 10, 10)}, |
| 303 |
) |
| 304 |
self.assertFalse(created) |
| 305 |
self.assertEqual(p.first_name, "John") |
| 306 |
self.assertEqual(p.last_name, "Lennon") |
| 307 |
self.assertEqual(p.birthday, date(1940, 10, 10)) |
| 308 |
|
| 309 |
def test_create(self): |
| 310 |
p, created = Person.objects.update_or_create( |
| 311 |
first_name="John", |
| 312 |
last_name="Lennon", |
| 313 |
defaults={"birthday": date(1940, 10, 10)}, |
| 314 |
) |
| 315 |
self.assertTrue(created) |
| 316 |
self.assertEqual(p.first_name, "John") |
| 317 |
self.assertEqual(p.last_name, "Lennon") |
| 318 |
self.assertEqual(p.birthday, date(1940, 10, 10)) |
| 319 |
|
| 320 |
def test_create_twice(self): |
| 321 |
p, created = Person.objects.update_or_create( |
| 322 |
first_name="John", |
| 323 |
last_name="Lennon", |
| 324 |
create_defaults={"birthday": date(1940, 10, 10)}, |
| 325 |
defaults={"birthday": date(1950, 2, 2)}, |
| 326 |
) |
| 327 |
self.assertIs(created, True) |
| 328 |
self.assertEqual(p.birthday, date(1940, 10, 10)) |
| 329 |
# If we execute the exact same statement, it won't create a Person, but |
| 330 |
# will update the birthday. |
| 331 |
p, created = Person.objects.update_or_create( |
| 332 |
first_name="John", |
| 333 |
last_name="Lennon", |
| 334 |
create_defaults={"birthday": date(1940, 10, 10)}, |
| 335 |
defaults={"birthday": date(1950, 2, 2)}, |
| 336 |
) |
| 337 |
self.assertIs(created, False) |
| 338 |
self.assertEqual(p.birthday, date(1950, 2, 2)) |
| 339 |
|
| 340 |
def test_integrity(self): |
| 341 |
""" |
| 342 |
If you don't specify a value or default value for all required |
| 343 |
fields, you will get an error. |
| 344 |
""" |
| 345 |
with self.assertRaises(IntegrityError): |
| 346 |
Person.objects.update_or_create(first_name="Tom", last_name="Smith") |
| 347 |
|
| 348 |
def test_manual_primary_key_test(self): |
| 349 |
""" |
| 350 |
If you specify an existing primary key, but different other fields, |
| 351 |
then you will get an error and data will not be updated. |
| 352 |
""" |
| 353 |
ManualPrimaryKeyTest.objects.create(id=1, data="Original") |
| 354 |
with self.assertRaises(IntegrityError): |
| 355 |
ManualPrimaryKeyTest.objects.update_or_create(id=1, data="Different") |
| 356 |
self.assertEqual(ManualPrimaryKeyTest.objects.get(id=1).data, "Original") |
| 357 |
|
| 358 |
def test_with_pk_property(self): |
| 359 |
""" |
| 360 |
Using the pk property of a model is allowed. |
| 361 |
""" |
| 362 |
Thing.objects.update_or_create(pk=1) |
| 363 |
|
| 364 |
def test_update_or_create_with_model_property_defaults(self): |
| 365 |
"""Using a property with a setter implemented is allowed.""" |
| 366 |
t, _ = Thing.objects.update_or_create( |
| 367 |
defaults={"capitalized_name_property": "annie"}, pk=1 |
| 368 |
) |
| 369 |
self.assertEqual(t.name, "Annie") |
| 370 |
|
| 371 |
def test_error_contains_full_traceback(self): |
| 372 |
""" |
| 373 |
update_or_create should raise IntegrityErrors with the full traceback. |
| 374 |
This is tested by checking that a known method call is in the traceback. |
| 375 |
We cannot use assertRaises/assertRaises here because we need to inspect |
| 376 |
the actual traceback. Refs #16340. |
| 377 |
""" |
| 378 |
try: |
| 379 |
ManualPrimaryKeyTest.objects.update_or_create(id=1, data="Different") |
| 380 |
except IntegrityError: |
| 381 |
formatted_traceback = traceback.format_exc() |
| 382 |
self.assertIn("obj.save", formatted_traceback) |
| 383 |
|
| 384 |
def test_create_with_related_manager(self): |
| 385 |
""" |
| 386 |
Should be able to use update_or_create from the related manager to |
| 387 |
create a book. Refs #23611. |
| 388 |
""" |
| 389 |
p = Publisher.objects.create(name="Acme Publishing") |
| 390 |
book, created = p.books.update_or_create(name="The Book of Ed & Fred") |
| 391 |
self.assertIs(created, True) |
| 392 |
self.assertEqual(p.books.count(), 1) |
| 393 |
book, created = p.books.update_or_create( |
| 394 |
name="Basics of Django", create_defaults={"name": "Advanced Django"} |
| 395 |
) |
| 396 |
self.assertIs(created, True) |
| 397 |
self.assertEqual(book.name, "Advanced Django") |
| 398 |
self.assertEqual(p.books.count(), 2) |
| 399 |
|
| 400 |
def test_update_with_related_manager(self): |
| 401 |
""" |
| 402 |
Should be able to use update_or_create from the related manager to |
| 403 |
update a book. Refs #23611. |
| 404 |
""" |
| 405 |
p = Publisher.objects.create(name="Acme Publishing") |
| 406 |
book = Book.objects.create(name="The Book of Ed & Fred", publisher=p) |
| 407 |
self.assertEqual(p.books.count(), 1) |
| 408 |
name = "The Book of Django" |
| 409 |
book, created = p.books.update_or_create(defaults={"name": name}, id=book.id) |
| 410 |
self.assertFalse(created) |
| 411 |
self.assertEqual(book.name, name) |
| 412 |
# create_defaults should be ignored. |
| 413 |
book, created = p.books.update_or_create( |
| 414 |
create_defaults={"name": "Basics of Django"}, |
| 415 |
defaults={"name": name}, |
| 416 |
id=book.id, |
| 417 |
) |
| 418 |
self.assertIs(created, False) |
| 419 |
self.assertEqual(book.name, name) |
| 420 |
self.assertEqual(p.books.count(), 1) |
| 421 |
|
| 422 |
def test_create_with_many(self): |
| 423 |
""" |
| 424 |
Should be able to use update_or_create from the m2m related manager to |
| 425 |
create a book. Refs #23611. |
| 426 |
""" |
| 427 |
p = Publisher.objects.create(name="Acme Publishing") |
| 428 |
author = Author.objects.create(name="Ted") |
| 429 |
book, created = author.books.update_or_create( |
| 430 |
name="The Book of Ed & Fred", publisher=p |
| 431 |
) |
| 432 |
self.assertIs(created, True) |
| 433 |
self.assertEqual(author.books.count(), 1) |
| 434 |
book, created = author.books.update_or_create( |
| 435 |
name="Basics of Django", |
| 436 |
publisher=p, |
| 437 |
create_defaults={"name": "Advanced Django"}, |
| 438 |
) |
| 439 |
self.assertIs(created, True) |
| 440 |
self.assertEqual(book.name, "Advanced Django") |
| 441 |
self.assertEqual(author.books.count(), 2) |
| 442 |
|
| 443 |
def test_update_with_many(self): |
| 444 |
""" |
| 445 |
Should be able to use update_or_create from the m2m related manager to |
| 446 |
update a book. Refs #23611. |
| 447 |
""" |
| 448 |
p = Publisher.objects.create(name="Acme Publishing") |
| 449 |
author = Author.objects.create(name="Ted") |
| 450 |
book = Book.objects.create(name="The Book of Ed & Fred", publisher=p) |
| 451 |
book.authors.add(author) |
| 452 |
self.assertEqual(author.books.count(), 1) |
| 453 |
name = "The Book of Django" |
| 454 |
book, created = author.books.update_or_create( |
| 455 |
defaults={"name": name}, id=book.id |
| 456 |
) |
| 457 |
self.assertFalse(created) |
| 458 |
self.assertEqual(book.name, name) |
| 459 |
# create_defaults should be ignored. |
| 460 |
book, created = author.books.update_or_create( |
| 461 |
create_defaults={"name": "Basics of Django"}, |
| 462 |
defaults={"name": name}, |
| 463 |
id=book.id, |
| 464 |
) |
| 465 |
self.assertIs(created, False) |
| 466 |
self.assertEqual(book.name, name) |
| 467 |
self.assertEqual(author.books.count(), 1) |
| 468 |
|
| 469 |
def test_defaults_exact(self): |
| 470 |
""" |
| 471 |
If you have a field named defaults and want to use it as an exact |
| 472 |
lookup, you need to use 'defaults__exact'. |
| 473 |
""" |
| 474 |
obj, created = Person.objects.update_or_create( |
| 475 |
first_name="George", |
| 476 |
last_name="Harrison", |
| 477 |
defaults__exact="testing", |
| 478 |
defaults={ |
| 479 |
"birthday": date(1943, 2, 25), |
| 480 |
"defaults": "testing", |
| 481 |
}, |
| 482 |
) |
| 483 |
self.assertTrue(created) |
| 484 |
self.assertEqual(obj.defaults, "testing") |
| 485 |
obj, created = Person.objects.update_or_create( |
| 486 |
first_name="George", |
| 487 |
last_name="Harrison", |
| 488 |
defaults__exact="testing", |
| 489 |
defaults={ |
| 490 |
"birthday": date(1943, 2, 25), |
| 491 |
"defaults": "another testing", |
| 492 |
}, |
| 493 |
) |
| 494 |
self.assertFalse(created) |
| 495 |
self.assertEqual(obj.defaults, "another testing") |
| 496 |
|
| 497 |
def test_create_defaults_exact(self): |
| 498 |
""" |
| 499 |
If you have a field named create_defaults and want to use it as an |
| 500 |
exact lookup, you need to use 'create_defaults__exact'. |
| 501 |
""" |
| 502 |
obj, created = Person.objects.update_or_create( |
| 503 |
first_name="George", |
| 504 |
last_name="Harrison", |
| 505 |
create_defaults__exact="testing", |
| 506 |
create_defaults={ |
| 507 |
"birthday": date(1943, 2, 25), |
| 508 |
"create_defaults": "testing", |
| 509 |
}, |
| 510 |
) |
| 511 |
self.assertIs(created, True) |
| 512 |
self.assertEqual(obj.create_defaults, "testing") |
| 513 |
obj, created = Person.objects.update_or_create( |
| 514 |
first_name="George", |
| 515 |
last_name="Harrison", |
| 516 |
create_defaults__exact="testing", |
| 517 |
create_defaults={ |
| 518 |
"birthday": date(1943, 2, 25), |
| 519 |
"create_defaults": "another testing", |
| 520 |
}, |
| 521 |
) |
| 522 |
self.assertIs(created, False) |
| 523 |
self.assertEqual(obj.create_defaults, "testing") |
| 524 |
|
| 525 |
def test_create_callable_default(self): |
| 526 |
obj, created = Person.objects.update_or_create( |
| 527 |
first_name="George", |
| 528 |
last_name="Harrison", |
| 529 |
defaults={"birthday": lambda: date(1943, 2, 25)}, |
| 530 |
) |
| 531 |
self.assertIs(created, True) |
| 532 |
self.assertEqual(obj.birthday, date(1943, 2, 25)) |
| 533 |
|
| 534 |
def test_create_callable_create_defaults(self): |
| 535 |
obj, created = Person.objects.update_or_create( |
| 536 |
first_name="George", |
| 537 |
last_name="Harrison", |
| 538 |
defaults={}, |
| 539 |
create_defaults={"birthday": lambda: date(1943, 2, 25)}, |
| 540 |
) |
| 541 |
self.assertIs(created, True) |
| 542 |
self.assertEqual(obj.birthday, date(1943, 2, 25)) |
| 543 |
|
| 544 |
def test_update_callable_default(self): |
| 545 |
Person.objects.update_or_create( |
| 546 |
first_name="George", |
| 547 |
last_name="Harrison", |
| 548 |
birthday=date(1942, 2, 25), |
| 549 |
) |
| 550 |
obj, created = Person.objects.update_or_create( |
| 551 |
first_name="George", |
| 552 |
defaults={"last_name": lambda: "NotHarrison"}, |
| 553 |
) |
| 554 |
self.assertIs(created, False) |
| 555 |
self.assertEqual(obj.last_name, "NotHarrison") |
| 556 |
|
| 557 |
def test_defaults_not_evaluated_unless_needed(self): |
| 558 |
"""`defaults` aren't evaluated if the instance isn't created.""" |
| 559 |
Person.objects.create( |
| 560 |
first_name="John", last_name="Lennon", birthday=date(1940, 10, 9) |
| 561 |
) |
| 562 |
|
| 563 |
def raise_exception(): |
| 564 |
raise AssertionError |
| 565 |
|
| 566 |
obj, created = Person.objects.get_or_create( |
| 567 |
first_name="John", |
| 568 |
defaults=lazy(raise_exception, object)(), |
| 569 |
) |
| 570 |
self.assertFalse(created) |
| 571 |
|
| 572 |
def test_mti_update_non_local_concrete_fields(self): |
| 573 |
journalist = Journalist.objects.create(name="Jane", specialty="Politics") |
| 574 |
journalist, created = Journalist.objects.update_or_create( |
| 575 |
pk=journalist.pk, |
| 576 |
defaults={"name": "John"}, |
| 577 |
) |
| 578 |
self.assertIs(created, False) |
| 579 |
self.assertEqual(journalist.name, "John") |
| 580 |
|
| 581 |
def test_update_only_defaults_and_pre_save_fields_when_local_fields(self): |
| 582 |
publisher = Publisher.objects.create(name="Acme Publishing") |
| 583 |
book = Book.objects.create(publisher=publisher, name="The Book of Ed & Fred") |
| 584 |
|
| 585 |
for defaults in [{"publisher": publisher}, {"publisher_id": publisher}]: |
| 586 |
with self.subTest(defaults=defaults): |
| 587 |
with CaptureQueriesContext(connection) as captured_queries: |
| 588 |
book, created = Book.objects.update_or_create( |
| 589 |
pk=book.pk, |
| 590 |
defaults=defaults, |
| 591 |
) |
| 592 |
self.assertIs(created, False) |
| 593 |
update_sqls = [ |
| 594 |
q["sql"] for q in captured_queries if q["sql"].startswith("UPDATE") |
| 595 |
] |
| 596 |
self.assertEqual(len(update_sqls), 1) |
| 597 |
update_sql = update_sqls[0] |
| 598 |
self.assertIsNotNone(update_sql) |
| 599 |
self.assertIn( |
| 600 |
connection.ops.quote_name("publisher_id_column"), update_sql |
| 601 |
) |
| 602 |
self.assertIn(connection.ops.quote_name("updated"), update_sql) |
| 603 |
# Name should not be updated. |
| 604 |
self.assertNotIn(connection.ops.quote_name("name"), update_sql) |
| 605 |
|
| 606 |
|
| 607 |
class UpdateOrCreateTestsWithManualPKs(TestCase): |
| 608 |
def test_create_with_duplicate_primary_key(self): |
| 609 |
""" |
| 610 |
If an existing primary key is specified with different values for other |
| 611 |
fields, then IntegrityError is raised and data isn't updated. |
| 612 |
""" |
| 613 |
ManualPrimaryKeyTest.objects.create(id=1, data="Original") |
| 614 |
with self.assertRaises(IntegrityError): |
| 615 |
ManualPrimaryKeyTest.objects.update_or_create(id=1, data="Different") |
| 616 |
self.assertEqual(ManualPrimaryKeyTest.objects.get(id=1).data, "Original") |
| 617 |
|
| 618 |
|
| 619 |
class UpdateOrCreateTransactionTests(TransactionTestCase): |
| 620 |
available_apps = ["get_or_create"] |
| 621 |
|
| 622 |
@skipUnlessDBFeature("has_select_for_update") |
| 623 |
@skipUnlessDBFeature("supports_transactions") |
| 624 |
def test_updates_in_transaction(self): |
| 625 |
""" |
| 626 |
Objects are selected and updated in a transaction to avoid race |
| 627 |
conditions. This test forces update_or_create() to hold the lock |
| 628 |
in another thread for a relatively long time so that it can update |
| 629 |
while it holds the lock. The updated field isn't a field in 'defaults', |
| 630 |
so update_or_create() shouldn't have an effect on it. |
| 631 |
""" |
| 632 |
lock_status = {"has_grabbed_lock": False} |
| 633 |
|
| 634 |
def birthday_sleep(): |
| 635 |
lock_status["has_grabbed_lock"] = True |
| 636 |
time.sleep(0.5) |
| 637 |
return date(1940, 10, 10) |
| 638 |
|
| 639 |
def update_birthday_slowly(): |
| 640 |
Person.objects.update_or_create( |
| 641 |
first_name="John", defaults={"birthday": birthday_sleep} |
| 642 |
) |
| 643 |
# Avoid leaking connection for Oracle |
| 644 |
connection.close() |
| 645 |
|
| 646 |
def lock_wait(): |
| 647 |
# timeout after ~0.5 seconds |
| 648 |
for i in range(20): |
| 649 |
time.sleep(0.025) |
| 650 |
if lock_status["has_grabbed_lock"]: |
| 651 |
return True |
| 652 |
return False |
| 653 |
|
| 654 |
Person.objects.create( |
| 655 |
first_name="John", last_name="Lennon", birthday=date(1940, 10, 9) |
| 656 |
) |
| 657 |
|
| 658 |
# update_or_create in a separate thread |
| 659 |
t = Thread(target=update_birthday_slowly) |
| 660 |
before_start = datetime.now() |
| 661 |
t.start() |
| 662 |
|
| 663 |
if not lock_wait(): |
| 664 |
self.skipTest("Database took too long to lock the row") |
| 665 |
|
| 666 |
# Update during lock |
| 667 |
Person.objects.filter(first_name="John").update(last_name="NotLennon") |
| 668 |
after_update = datetime.now() |
| 669 |
|
| 670 |
# Wait for thread to finish |
| 671 |
t.join() |
| 672 |
|
| 673 |
# The update remains and it blocked. |
| 674 |
updated_person = Person.objects.get(first_name="John") |
| 675 |
self.assertGreater(after_update - before_start, timedelta(seconds=0.5)) |
| 676 |
self.assertEqual(updated_person.last_name, "NotLennon") |
| 677 |
|
| 678 |
@skipUnlessDBFeature("has_select_for_update") |
| 679 |
@skipUnlessDBFeature("supports_transactions") |
| 680 |
def test_creation_in_transaction(self): |
| 681 |
""" |
| 682 |
Objects are selected and updated in a transaction to avoid race |
| 683 |
conditions. This test checks the behavior of update_or_create() when |
| 684 |
the object doesn't already exist, but another thread creates the |
| 685 |
object before update_or_create() does and then attempts to update the |
| 686 |
object, also before update_or_create(). It forces update_or_create() to |
| 687 |
hold the lock in another thread for a relatively long time so that it |
| 688 |
can update while it holds the lock. The updated field isn't a field in |
| 689 |
'defaults', so update_or_create() shouldn't have an effect on it. |
| 690 |
""" |
| 691 |
locked_for_update = Event() |
| 692 |
save_allowed = Event() |
| 693 |
|
| 694 |
def wait_or_fail(event, message): |
| 695 |
if not event.wait(5): |
| 696 |
raise AssertionError(message) |
| 697 |
|
| 698 |
def birthday_yield(): |
| 699 |
# At this point the row should be locked as create or update |
| 700 |
# defaults are only called once the SELECT FOR UPDATE is issued. |
| 701 |
locked_for_update.set() |
| 702 |
# Yield back the execution to the main thread until it allows |
| 703 |
# save() to proceed. |
| 704 |
save_allowed.clear() |
| 705 |
return date(1940, 10, 10) |
| 706 |
|
| 707 |
person_save = Person.save |
| 708 |
|
| 709 |
def wait_for_allowed_save(*args, **kwargs): |
| 710 |
wait_or_fail(save_allowed, "Test took too long to allow save") |
| 711 |
return person_save(*args, **kwargs) |
| 712 |
|
| 713 |
def update_person(): |
| 714 |
try: |
| 715 |
with patch.object(Person, "save", wait_for_allowed_save): |
| 716 |
Person.objects.update_or_create( |
| 717 |
first_name="John", |
| 718 |
defaults={"last_name": "Doe", "birthday": birthday_yield}, |
| 719 |
) |
| 720 |
finally: |
| 721 |
# Avoid leaking connection for Oracle. |
| 722 |
connection.close() |
| 723 |
|
| 724 |
t = Thread(target=update_person) |
| 725 |
t.start() |
| 726 |
wait_or_fail(locked_for_update, "Database took too long to lock row") |
| 727 |
# Create object *after* initial attempt by update_or_create to get obj |
| 728 |
# but before creation attempt. |
| 729 |
person = Person( |
| 730 |
first_name="John", last_name="Lennon", birthday=date(1940, 10, 9) |
| 731 |
) |
| 732 |
# Don't use person.save() as it's gated by the save_allowed event. |
| 733 |
person_save(person, force_insert=True) |
| 734 |
# Now that the row is created allow the update_or_create() logic to |
| 735 |
# attempt a save(force_insert) that will inevitably fail and wait |
| 736 |
# until it yields back execution after performing a subsequent |
| 737 |
# locked select for update with an intent to save(force_update). |
| 738 |
locked_for_update.clear() |
| 739 |
save_allowed.set() |
| 740 |
wait_or_fail(locked_for_update, "Database took too long to lock row") |
| 741 |
allow_save = Timer(0.5, save_allowed.set) |
| 742 |
before_start = datetime.now() |
| 743 |
allow_save.start() |
| 744 |
# The following update() should block until the update_or_create() |
| 745 |
# initiated save() is allowed to proceed by the `allow_save` timer |
| 746 |
# setting `save_allowed` after 0.5 seconds. |
| 747 |
Person.objects.filter(first_name="John").update(last_name="NotLennon") |
| 748 |
after_update = datetime.now() |
| 749 |
# Wait for thread to finish. |
| 750 |
t.join() |
| 751 |
# Check call to update_or_create() succeeded and the subsequent |
| 752 |
# (blocked) call to update(). |
| 753 |
updated_person = Person.objects.get(first_name="John") |
| 754 |
# Confirm update_or_create() performed an update. |
| 755 |
self.assertEqual(updated_person.birthday, date(1940, 10, 10)) |
| 756 |
# Confirm update() was the last statement to run. |
| 757 |
self.assertEqual(updated_person.last_name, "NotLennon") |
| 758 |
# Confirm update() blocked at least the duration of the timer. |
| 759 |
self.assertGreater(after_update - before_start, timedelta(seconds=0.5)) |
| 760 |
|
| 761 |
|
| 762 |
class InvalidCreateArgumentsTests(TransactionTestCase): |
| 763 |
available_apps = ["get_or_create"] |
| 764 |
msg = "Invalid field name(s) for model Thing: 'nonexistent'." |
| 765 |
bad_field_msg = ( |
| 766 |
"Cannot resolve keyword 'nonexistent' into field. Choices are: id, name, tags" |
| 767 |
) |
| 768 |
|
| 769 |
def test_get_or_create_with_invalid_defaults(self): |
| 770 |
with self.assertRaisesMessage(FieldError, self.msg): |
| 771 |
Thing.objects.get_or_create(name="a", defaults={"nonexistent": "b"}) |
| 772 |
|
| 773 |
def test_get_or_create_with_invalid_kwargs(self): |
| 774 |
with self.assertRaisesMessage(FieldError, self.bad_field_msg): |
| 775 |
Thing.objects.get_or_create(name="a", nonexistent="b") |
| 776 |
|
| 777 |
def test_update_or_create_with_invalid_defaults(self): |
| 778 |
with self.assertRaisesMessage(FieldError, self.msg): |
| 779 |
Thing.objects.update_or_create(name="a", defaults={"nonexistent": "b"}) |
| 780 |
|
| 781 |
def test_update_or_create_with_invalid_create_defaults(self): |
| 782 |
with self.assertRaisesMessage(FieldError, self.msg): |
| 783 |
Thing.objects.update_or_create( |
| 784 |
name="a", create_defaults={"nonexistent": "b"} |
| 785 |
) |
| 786 |
|
| 787 |
def test_update_or_create_with_invalid_kwargs(self): |
| 788 |
with self.assertRaisesMessage(FieldError, self.bad_field_msg): |
| 789 |
Thing.objects.update_or_create(name="a", nonexistent="b") |
| 790 |
|
| 791 |
def test_multiple_invalid_fields(self): |
| 792 |
with self.assertRaisesMessage(FieldError, self.bad_field_msg): |
| 793 |
Thing.objects.update_or_create( |
| 794 |
name="a", nonexistent="b", defaults={"invalid": "c"} |
| 795 |
) |
| 796 |
|
| 797 |
def test_property_attribute_without_setter_defaults(self): |
| 798 |
with self.assertRaisesMessage( |
| 799 |
FieldError, "Invalid field name(s) for model Thing: 'name_in_all_caps'" |
| 800 |
): |
| 801 |
Thing.objects.update_or_create( |
| 802 |
name="a", defaults={"name_in_all_caps": "FRANK"} |
| 803 |
) |
| 804 |
|
| 805 |
def test_property_attribute_without_setter_kwargs(self): |
| 806 |
msg = ( |
| 807 |
"Cannot resolve keyword 'name_in_all_caps' into field. Choices are: id, " |
| 808 |
"name, tags" |
| 809 |
) |
| 810 |
with self.assertRaisesMessage(FieldError, msg): |
| 811 |
Thing.objects.update_or_create( |
| 812 |
name_in_all_caps="FRANK", defaults={"name": "Frank"} |
| 813 |
) |