Debian Codegraph @

tests/basic/tests.py

raw
1 import inspect
2 import threading
3 from datetime import datetime, timedelta
4 from unittest import mock
5
6 from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist
7 from django.db import (
8 DEFAULT_DB_ALIAS,
9 DatabaseError,
10 connection,
11 connections,
12 models,
13 transaction,
14 )
15 from django.db.models.manager import BaseManager
16 from django.db.models.query import MAX_GET_RESULTS, EmptyQuerySet
17 from django.test import (
18 SimpleTestCase,
19 TestCase,
20 TransactionTestCase,
21 skipUnlessDBFeature,
22 )
23 from django.test.utils import CaptureQueriesContext, ignore_warnings
24 from django.utils.connection import ConnectionDoesNotExist
25 from django.utils.deprecation import RemovedInDjango60Warning
26 from django.utils.translation import gettext_lazy
27
28 from .models import (
29 Article,
30 ArticleSelectOnSave,
31 ChildPrimaryKeyWithDefault,
32 FeaturedArticle,
33 PrimaryKeyWithDbDefault,
34 PrimaryKeyWithDefault,
35 PrimaryKeyWithFalseyDbDefault,
36 PrimaryKeyWithFalseyDefault,
37 SelfRef,
38 )
39
40
41 class ModelInstanceCreationTests(TestCase):
42 def test_object_is_not_written_to_database_until_save_was_called(self):
43 a = Article(
44 id=None,
45 headline="Parrot programs in Python",
46 pub_date=datetime(2005, 7, 28),
47 )
48 self.assertIsNone(a.id)
49 self.assertEqual(Article.objects.count(), 0)
50
51 # Save it into the database. You have to call save() explicitly.
52 a.save()
53 self.assertIsNotNone(a.id)
54 self.assertEqual(Article.objects.count(), 1)
55
56 def test_can_initialize_model_instance_using_positional_arguments(self):
57 """
58 You can initialize a model instance using positional arguments,
59 which should match the field order as defined in the model.
60 """
61 a = Article(None, "Second article", datetime(2005, 7, 29))
62 a.save()
63
64 self.assertEqual(a.headline, "Second article")
65 self.assertEqual(a.pub_date, datetime(2005, 7, 29, 0, 0))
66
67 def test_can_create_instance_using_kwargs(self):
68 a = Article(
69 id=None,
70 headline="Third article",
71 pub_date=datetime(2005, 7, 30),
72 )
73 a.save()
74 self.assertEqual(a.headline, "Third article")
75 self.assertEqual(a.pub_date, datetime(2005, 7, 30, 0, 0))
76
77 def test_autofields_generate_different_values_for_each_instance(self):
78 a1 = Article.objects.create(
79 headline="First", pub_date=datetime(2005, 7, 30, 0, 0)
80 )
81 a2 = Article.objects.create(
82 headline="First", pub_date=datetime(2005, 7, 30, 0, 0)
83 )
84 a3 = Article.objects.create(
85 headline="First", pub_date=datetime(2005, 7, 30, 0, 0)
86 )
87 self.assertNotEqual(a3.id, a1.id)
88 self.assertNotEqual(a3.id, a2.id)
89
90 def test_can_mix_and_match_position_and_kwargs(self):
91 # You can also mix and match position and keyword arguments, but
92 # be sure not to duplicate field information.
93 a = Article(None, "Fourth article", pub_date=datetime(2005, 7, 31))
94 a.save()
95 self.assertEqual(a.headline, "Fourth article")
96
97 def test_positional_and_keyword_args_for_the_same_field(self):
98 msg = "Article() got both positional and keyword arguments for field '%s'."
99 with self.assertRaisesMessage(TypeError, msg % "headline"):
100 Article(None, "Fifth article", headline="Other headline.")
101 with self.assertRaisesMessage(TypeError, msg % "headline"):
102 Article(None, "Sixth article", headline="")
103 with self.assertRaisesMessage(TypeError, msg % "pub_date"):
104 Article(None, "Seventh article", datetime(2021, 3, 1), pub_date=None)
105
106 def test_cannot_create_instance_with_invalid_kwargs(self):
107 msg = "Article() got unexpected keyword arguments: 'foo'"
108 with self.assertRaisesMessage(TypeError, msg):
109 Article(
110 id=None,
111 headline="Some headline",
112 pub_date=datetime(2005, 7, 31),
113 foo="bar",
114 )
115 msg = "Article() got unexpected keyword arguments: 'foo', 'bar'"
116 with self.assertRaisesMessage(TypeError, msg):
117 Article(
118 id=None,
119 headline="Some headline",
120 pub_date=datetime(2005, 7, 31),
121 foo="bar",
122 bar="baz",
123 )
124
125 def test_can_leave_off_value_for_autofield_and_it_gets_value_on_save(self):
126 """
127 You can leave off the value for an AutoField when creating an
128 object, because it'll get filled in automatically when you save().
129 """
130 a = Article(headline="Article 5", pub_date=datetime(2005, 7, 31))
131 a.save()
132 self.assertEqual(a.headline, "Article 5")
133 self.assertIsNotNone(a.id)
134
135 def test_leaving_off_a_field_with_default_set_the_default_will_be_saved(self):
136 a = Article(pub_date=datetime(2005, 7, 31))
137 a.save()
138 self.assertEqual(a.headline, "Default headline")
139
140 def test_for_datetimefields_saves_as_much_precision_as_was_given(self):
141 """as much precision in *seconds*"""
142 a1 = Article(
143 headline="Article 7",
144 pub_date=datetime(2005, 7, 31, 12, 30),
145 )
146 a1.save()
147 self.assertEqual(
148 Article.objects.get(id__exact=a1.id).pub_date, datetime(2005, 7, 31, 12, 30)
149 )
150
151 a2 = Article(
152 headline="Article 8",
153 pub_date=datetime(2005, 7, 31, 12, 30, 45),
154 )
155 a2.save()
156 self.assertEqual(
157 Article.objects.get(id__exact=a2.id).pub_date,
158 datetime(2005, 7, 31, 12, 30, 45),
159 )
160
161 def test_saving_an_object_again_does_not_create_a_new_object(self):
162 a = Article(headline="original", pub_date=datetime(2014, 5, 16))
163 a.save()
164 current_id = a.id
165
166 a.save()
167 self.assertEqual(a.id, current_id)
168
169 a.headline = "Updated headline"
170 a.save()
171 self.assertEqual(a.id, current_id)
172
173 def test_querysets_checking_for_membership(self):
174 headlines = ["Parrot programs in Python", "Second article", "Third article"]
175 some_pub_date = datetime(2014, 5, 16, 12, 1)
176 for headline in headlines:
177 Article(headline=headline, pub_date=some_pub_date).save()
178 a = Article(headline="Some headline", pub_date=some_pub_date)
179 a.save()
180
181 # You can use 'in' to test for membership...
182 self.assertIn(a, Article.objects.all())
183 # ... but there will often be more efficient ways if that is all you need:
184 self.assertTrue(Article.objects.filter(id=a.id).exists())
185
186 def test_save_primary_with_default(self):
187 # An UPDATE attempt is skipped when a primary key has default.
188 with self.assertNumQueries(1):
189 PrimaryKeyWithDefault().save()
190
191 def test_save_primary_with_default_force_update(self):
192 # An UPDATE attempt is made if explicitly requested.
193 obj = PrimaryKeyWithDefault.objects.create()
194 with self.assertNumQueries(1):
195 PrimaryKeyWithDefault(uuid=obj.pk).save(force_update=True)
196
197 def test_save_primary_with_db_default(self):
198 # An UPDATE attempt is skipped when a primary key has db_default.
199 with self.assertNumQueries(1):
200 PrimaryKeyWithDbDefault().save()
201
202 def test_save_parent_primary_with_default(self):
203 # An UPDATE attempt is skipped when an inherited primary key has
204 # default.
205 with self.assertNumQueries(2):
206 ChildPrimaryKeyWithDefault().save()
207
208 def test_save_primary_with_falsey_default(self):
209 with self.assertNumQueries(1):
210 PrimaryKeyWithFalseyDefault().save()
211
212 def test_save_primary_with_falsey_db_default(self):
213 with self.assertNumQueries(1):
214 PrimaryKeyWithFalseyDbDefault().save()
215
216 def test_save_deprecation(self):
217 a = Article(headline="original", pub_date=datetime(2014, 5, 16))
218 msg = "Passing positional arguments to save() is deprecated"
219 with self.assertWarnsMessage(RemovedInDjango60Warning, msg) as ctx:
220 a.save(False, False, None, None)
221 self.assertEqual(Article.objects.count(), 1)
222 self.assertEqual(ctx.filename, __file__)
223
224 def test_save_deprecation_positional_arguments_used(self):
225 a = Article()
226 fields = ["headline"]
227 with (
228 self.assertWarns(RemovedInDjango60Warning),
229 mock.patch.object(a, "save_base") as mock_save_base,
230 ):
231 a.save(None, 1, 2, fields)
232 self.assertEqual(
233 mock_save_base.mock_calls,
234 [
235 mock.call(
236 using=2,
237 force_insert=None,
238 force_update=1,
239 update_fields=frozenset(fields),
240 )
241 ],
242 )
243
244 def test_save_too_many_positional_arguments(self):
245 a = Article()
246 msg = "Model.save() takes from 1 to 5 positional arguments but 6 were given"
247 with (
248 self.assertWarns(RemovedInDjango60Warning),
249 self.assertRaisesMessage(TypeError, msg),
250 ):
251 a.save(False, False, None, None, None)
252
253 def test_save_conflicting_positional_and_named_arguments(self):
254 a = Article()
255 cases = [
256 ("force_insert", True, [42]),
257 ("force_update", None, [42, 41]),
258 ("using", "some-db", [42, 41, 40]),
259 ("update_fields", ["foo"], [42, 41, 40, 39]),
260 ]
261 for param_name, param_value, args in cases:
262 with self.subTest(param_name=param_name):
263 msg = f"Model.save() got multiple values for argument '{param_name}'"
264 with (
265 self.assertWarns(RemovedInDjango60Warning),
266 self.assertRaisesMessage(TypeError, msg),
267 ):
268 a.save(*args, **{param_name: param_value})
269
270 async def test_asave_deprecation(self):
271 a = Article(headline="original", pub_date=datetime(2014, 5, 16))
272 msg = "Passing positional arguments to asave() is deprecated"
273 with self.assertWarnsMessage(RemovedInDjango60Warning, msg) as ctx:
274 await a.asave(False, False, None, None)
275 self.assertEqual(await Article.objects.acount(), 1)
276 self.assertEqual(ctx.filename, __file__)
277
278 async def test_asave_deprecation_positional_arguments_used(self):
279 a = Article()
280 fields = ["headline"]
281 with (
282 self.assertWarns(RemovedInDjango60Warning),
283 mock.patch.object(a, "save_base") as mock_save_base,
284 ):
285 await a.asave(None, 1, 2, fields)
286 self.assertEqual(
287 mock_save_base.mock_calls,
288 [
289 mock.call(
290 using=2,
291 force_insert=None,
292 force_update=1,
293 update_fields=frozenset(fields),
294 )
295 ],
296 )
297
298 async def test_asave_too_many_positional_arguments(self):
299 a = Article()
300 msg = "Model.asave() takes from 1 to 5 positional arguments but 6 were given"
301 with (
302 self.assertWarns(RemovedInDjango60Warning),
303 self.assertRaisesMessage(TypeError, msg),
304 ):
305 await a.asave(False, False, None, None, None)
306
307 async def test_asave_conflicting_positional_and_named_arguments(self):
308 a = Article()
309 cases = [
310 ("force_insert", True, [42]),
311 ("force_update", None, [42, 41]),
312 ("using", "some-db", [42, 41, 40]),
313 ("update_fields", ["foo"], [42, 41, 40, 39]),
314 ]
315 for param_name, param_value, args in cases:
316 with self.subTest(param_name=param_name):
317 msg = f"Model.asave() got multiple values for argument '{param_name}'"
318 with (
319 self.assertWarns(RemovedInDjango60Warning),
320 self.assertRaisesMessage(TypeError, msg),
321 ):
322 await a.asave(*args, **{param_name: param_value})
323
324 @ignore_warnings(category=RemovedInDjango60Warning)
325 def test_save_positional_arguments(self):
326 a = Article.objects.create(headline="original", pub_date=datetime(2014, 5, 16))
327 a.headline = "changed"
328
329 a.save(False, False, None, ["pub_date"])
330 a.refresh_from_db()
331 self.assertEqual(a.headline, "original")
332
333 a.headline = "changed"
334 a.save(False, False, None, ["pub_date", "headline"])
335 a.refresh_from_db()
336 self.assertEqual(a.headline, "changed")
337
338 @ignore_warnings(category=RemovedInDjango60Warning)
339 async def test_asave_positional_arguments(self):
340 a = await Article.objects.acreate(
341 headline="original", pub_date=datetime(2014, 5, 16)
342 )
343 a.headline = "changed"
344
345 await a.asave(False, False, None, ["pub_date"])
346 await a.arefresh_from_db()
347 self.assertEqual(a.headline, "original")
348
349 a.headline = "changed"
350 await a.asave(False, False, None, ["pub_date", "headline"])
351 await a.arefresh_from_db()
352 self.assertEqual(a.headline, "changed")
353
354
355 class ModelTest(TestCase):
356 def test_objects_attribute_is_only_available_on_the_class_itself(self):
357 with self.assertRaisesMessage(
358 AttributeError, "Manager isn't accessible via Article instances"
359 ):
360 getattr(
361 Article(),
362 "objects",
363 )
364 self.assertFalse(hasattr(Article(), "objects"))
365 self.assertTrue(hasattr(Article, "objects"))
366
367 def test_queryset_delete_removes_all_items_in_that_queryset(self):
368 headlines = ["An article", "Article One", "Amazing article", "Boring article"]
369 some_pub_date = datetime(2014, 5, 16, 12, 1)
370 for headline in headlines:
371 Article(headline=headline, pub_date=some_pub_date).save()
372 self.assertQuerySetEqual(
373 Article.objects.order_by("headline"),
374 sorted(headlines),
375 transform=lambda a: a.headline,
376 )
377 Article.objects.filter(headline__startswith="A").delete()
378 self.assertEqual(Article.objects.get().headline, "Boring article")
379
380 def test_not_equal_and_equal_operators_behave_as_expected_on_instances(self):
381 some_pub_date = datetime(2014, 5, 16, 12, 1)
382 a1 = Article.objects.create(headline="First", pub_date=some_pub_date)
383 a2 = Article.objects.create(headline="Second", pub_date=some_pub_date)
384 self.assertNotEqual(a1, a2)
385 self.assertEqual(a1, Article.objects.get(id__exact=a1.id))
386
387 self.assertNotEqual(
388 Article.objects.get(id__exact=a1.id), Article.objects.get(id__exact=a2.id)
389 )
390
391 def test_microsecond_precision(self):
392 a9 = Article(
393 headline="Article 9",
394 pub_date=datetime(2005, 7, 31, 12, 30, 45, 180),
395 )
396 a9.save()
397 self.assertEqual(
398 Article.objects.get(pk=a9.pk).pub_date,
399 datetime(2005, 7, 31, 12, 30, 45, 180),
400 )
401
402 def test_manually_specify_primary_key(self):
403 # You can manually specify the primary key when creating a new object.
404 a101 = Article(
405 id=101,
406 headline="Article 101",
407 pub_date=datetime(2005, 7, 31, 12, 30, 45),
408 )
409 a101.save()
410 a101 = Article.objects.get(pk=101)
411 self.assertEqual(a101.headline, "Article 101")
412
413 def test_create_method(self):
414 # You can create saved objects in a single step
415 a10 = Article.objects.create(
416 headline="Article 10",
417 pub_date=datetime(2005, 7, 31, 12, 30, 45),
418 )
419 self.assertEqual(Article.objects.get(headline="Article 10"), a10)
420
421 def test_year_lookup_edge_case(self):
422 # Edge-case test: A year lookup should retrieve all objects in
423 # the given year, including Jan. 1 and Dec. 31.
424 a11 = Article.objects.create(
425 headline="Article 11",
426 pub_date=datetime(2008, 1, 1),
427 )
428 a12 = Article.objects.create(
429 headline="Article 12",
430 pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999),
431 )
432 self.assertSequenceEqual(
433 Article.objects.filter(pub_date__year=2008),
434 [a11, a12],
435 )
436
437 def test_unicode_data(self):
438 # Unicode data works, too.
439 a = Article(
440 headline="\u6797\u539f \u3081\u3050\u307f",
441 pub_date=datetime(2005, 7, 28),
442 )
443 a.save()
444 self.assertEqual(
445 Article.objects.get(pk=a.id).headline, "\u6797\u539f \u3081\u3050\u307f"
446 )
447
448 def test_hash_function(self):
449 # Model instances have a hash function, so they can be used in sets
450 # or as dictionary keys. Two models compare as equal if their primary
451 # keys are equal.
452 a10 = Article.objects.create(
453 headline="Article 10",
454 pub_date=datetime(2005, 7, 31, 12, 30, 45),
455 )
456 a11 = Article.objects.create(
457 headline="Article 11",
458 pub_date=datetime(2008, 1, 1),
459 )
460 a12 = Article.objects.create(
461 headline="Article 12",
462 pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999),
463 )
464
465 s = {a10, a11, a12}
466 self.assertIn(Article.objects.get(headline="Article 11"), s)
467
468 def test_extra_method_select_argument_with_dashes_and_values(self):
469 # The 'select' argument to extra() supports names with dashes in
470 # them, as long as you use values().
471 Article.objects.bulk_create(
472 [
473 Article(
474 headline="Article 10", pub_date=datetime(2005, 7, 31, 12, 30, 45)
475 ),
476 Article(headline="Article 11", pub_date=datetime(2008, 1, 1)),
477 Article(
478 headline="Article 12",
479 pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999),
480 ),
481 ]
482 )
483 dicts = (
484 Article.objects.filter(pub_date__year=2008)
485 .extra(select={"dashed-value": "1"})
486 .values("headline", "dashed-value")
487 )
488 self.assertEqual(
489 [sorted(d.items()) for d in dicts],
490 [
491 [("dashed-value", 1), ("headline", "Article 11")],
492 [("dashed-value", 1), ("headline", "Article 12")],
493 ],
494 )
495
496 def test_extra_method_select_argument_with_dashes(self):
497 # If you use 'select' with extra() and names containing dashes on a
498 # query that's *not* a values() query, those extra 'select' values
499 # will silently be ignored.
500 Article.objects.bulk_create(
501 [
502 Article(
503 headline="Article 10", pub_date=datetime(2005, 7, 31, 12, 30, 45)
504 ),
505 Article(headline="Article 11", pub_date=datetime(2008, 1, 1)),
506 Article(
507 headline="Article 12",
508 pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999),
509 ),
510 ]
511 )
512 articles = Article.objects.filter(pub_date__year=2008).extra(
513 select={"dashed-value": "1", "undashedvalue": "2"}
514 )
515 self.assertEqual(articles[0].undashedvalue, 2)
516
517 def test_create_relation_with_gettext_lazy(self):
518 """
519 gettext_lazy objects work when saving model instances
520 through various methods. Refs #10498.
521 """
522 notlazy = "test"
523 lazy = gettext_lazy(notlazy)
524 Article.objects.create(headline=lazy, pub_date=datetime.now())
525 article = Article.objects.get()
526 self.assertEqual(article.headline, notlazy)
527 # test that assign + save works with Promise objects
528 article.headline = lazy
529 article.save()
530 self.assertEqual(article.headline, notlazy)
531 # test .update()
532 Article.objects.update(headline=lazy)
533 article = Article.objects.get()
534 self.assertEqual(article.headline, notlazy)
535 # still test bulk_create()
536 Article.objects.all().delete()
537 Article.objects.bulk_create([Article(headline=lazy, pub_date=datetime.now())])
538 article = Article.objects.get()
539 self.assertEqual(article.headline, notlazy)
540
541 def test_emptyqs(self):
542 msg = "EmptyQuerySet can't be instantiated"
543 with self.assertRaisesMessage(TypeError, msg):
544 EmptyQuerySet()
545 self.assertIsInstance(Article.objects.none(), EmptyQuerySet)
546 self.assertNotIsInstance("", EmptyQuerySet)
547
548 def test_emptyqs_values(self):
549 # test for #15959
550 Article.objects.create(headline="foo", pub_date=datetime.now())
551 with self.assertNumQueries(0):
552 qs = Article.objects.none().values_list("pk")
553 self.assertIsInstance(qs, EmptyQuerySet)
554 self.assertEqual(len(qs), 0)
555
556 def test_emptyqs_customqs(self):
557 # A hacky test for custom QuerySet subclass - refs #17271
558 Article.objects.create(headline="foo", pub_date=datetime.now())
559
560 class CustomQuerySet(models.QuerySet):
561 def do_something(self):
562 return "did something"
563
564 qs = Article.objects.all()
565 qs.__class__ = CustomQuerySet
566 qs = qs.none()
567 with self.assertNumQueries(0):
568 self.assertEqual(len(qs), 0)
569 self.assertIsInstance(qs, EmptyQuerySet)
570 self.assertEqual(qs.do_something(), "did something")
571
572 def test_emptyqs_values_order(self):
573 # Tests for ticket #17712
574 Article.objects.create(headline="foo", pub_date=datetime.now())
575 with self.assertNumQueries(0):
576 self.assertEqual(
577 len(Article.objects.none().values_list("id").order_by("id")), 0
578 )
579 with self.assertNumQueries(0):
580 self.assertEqual(
581 len(
582 Article.objects.none().filter(
583 id__in=Article.objects.values_list("id", flat=True)
584 )
585 ),
586 0,
587 )
588
589 @skipUnlessDBFeature("can_distinct_on_fields")
590 def test_emptyqs_distinct(self):
591 # Tests for #19426
592 Article.objects.create(headline="foo", pub_date=datetime.now())
593 with self.assertNumQueries(0):
594 self.assertEqual(
595 len(Article.objects.none().distinct("headline", "pub_date")), 0
596 )
597
598 def test_ticket_20278(self):
599 sr = SelfRef.objects.create()
600 with self.assertRaises(ObjectDoesNotExist):
601 SelfRef.objects.get(selfref=sr)
602
603 def test_eq(self):
604 self.assertEqual(Article(id=1), Article(id=1))
605 self.assertNotEqual(Article(id=1), object())
606 self.assertNotEqual(object(), Article(id=1))
607 a = Article()
608 self.assertEqual(a, a)
609 self.assertEqual(a, mock.ANY)
610 self.assertNotEqual(Article(), a)
611
612 def test_hash(self):
613 # Value based on PK
614 self.assertEqual(hash(Article(id=1)), hash(1))
615 msg = "Model instances without primary key value are unhashable"
616 with self.assertRaisesMessage(TypeError, msg):
617 # No PK value -> unhashable (because save() would then change
618 # hash)
619 hash(Article())
620
621 def test_missing_hash_not_inherited(self):
622 class NoHash(models.Model):
623 def __eq__(self, other):
624 return super.__eq__(other)
625
626 with self.assertRaisesMessage(TypeError, "unhashable type: 'NoHash'"):
627 hash(NoHash(id=1))
628
629 def test_specified_parent_hash_inherited(self):
630 class ParentHash(models.Model):
631 def __eq__(self, other):
632 return super.__eq__(other)
633
634 __hash__ = models.Model.__hash__
635
636 self.assertEqual(hash(ParentHash(id=1)), 1)
637
638 def test_delete_and_access_field(self):
639 # Accessing a field after it's deleted from a model reloads its value.
640 pub_date = datetime.now()
641 article = Article.objects.create(headline="foo", pub_date=pub_date)
642 new_pub_date = article.pub_date + timedelta(days=10)
643 article.headline = "bar"
644 article.pub_date = new_pub_date
645 del article.headline
646 with self.assertNumQueries(1):
647 self.assertEqual(article.headline, "foo")
648 # Fields that weren't deleted aren't reloaded.
649 self.assertEqual(article.pub_date, new_pub_date)
650
651 def test_multiple_objects_max_num_fetched(self):
652 max_results = MAX_GET_RESULTS - 1
653 Article.objects.bulk_create(
654 Article(headline="Area %s" % i, pub_date=datetime(2005, 7, 28))
655 for i in range(max_results)
656 )
657 self.assertRaisesMessage(
658 MultipleObjectsReturned,
659 "get() returned more than one Article -- it returned %d!" % max_results,
660 Article.objects.get,
661 headline__startswith="Area",
662 )
663 Article.objects.create(
664 headline="Area %s" % max_results, pub_date=datetime(2005, 7, 28)
665 )
666 self.assertRaisesMessage(
667 MultipleObjectsReturned,
668 "get() returned more than one Article -- it returned more than %d!"
669 % max_results,
670 Article.objects.get,
671 headline__startswith="Area",
672 )
673
674 def test_is_pk_unset(self):
675 cases = [
676 Article(),
677 Article(id=None),
678 ]
679 for case in cases:
680 with self.subTest(case=case):
681 self.assertIs(case._is_pk_set(), False)
682
683 def test_is_pk_set(self):
684 def new_instance():
685 a = Article(pub_date=datetime.today())
686 a.save()
687 return a
688
689 cases = [
690 Article(id=1),
691 Article(id=0),
692 Article.objects.create(pub_date=datetime.today()),
693 new_instance(),
694 ]
695 for case in cases:
696 with self.subTest(case=case):
697 self.assertIs(case._is_pk_set(), True)
698
699
700 class ModelLookupTest(TestCase):
701 @classmethod
702 def setUpTestData(cls):
703 # Create an Article.
704 cls.a = Article(
705 id=None,
706 headline="Swallow programs in Python",
707 pub_date=datetime(2005, 7, 28),
708 )
709 # Save it into the database. You have to call save() explicitly.
710 cls.a.save()
711
712 def test_all_lookup(self):
713 # Change values by changing the attributes, then calling save().
714 self.a.headline = "Parrot programs in Python"
715 self.a.save()
716
717 # Article.objects.all() returns all the articles in the database.
718 self.assertSequenceEqual(Article.objects.all(), [self.a])
719
720 def test_rich_lookup(self):
721 # Django provides a rich database lookup API.
722 self.assertEqual(Article.objects.get(id__exact=self.a.id), self.a)
723 self.assertEqual(Article.objects.get(headline__startswith="Swallow"), self.a)
724 self.assertEqual(Article.objects.get(pub_date__year=2005), self.a)
725 self.assertEqual(
726 Article.objects.get(pub_date__year=2005, pub_date__month=7), self.a
727 )
728 self.assertEqual(
729 Article.objects.get(
730 pub_date__year=2005, pub_date__month=7, pub_date__day=28
731 ),
732 self.a,
733 )
734 self.assertEqual(Article.objects.get(pub_date__week_day=5), self.a)
735
736 def test_equal_lookup(self):
737 # The "__exact" lookup type can be omitted, as a shortcut.
738 self.assertEqual(Article.objects.get(id=self.a.id), self.a)
739 self.assertEqual(
740 Article.objects.get(headline="Swallow programs in Python"), self.a
741 )
742
743 self.assertSequenceEqual(
744 Article.objects.filter(pub_date__year=2005),
745 [self.a],
746 )
747 self.assertSequenceEqual(
748 Article.objects.filter(pub_date__year=2004),
749 [],
750 )
751 self.assertSequenceEqual(
752 Article.objects.filter(pub_date__year=2005, pub_date__month=7),
753 [self.a],
754 )
755
756 self.assertSequenceEqual(
757 Article.objects.filter(pub_date__week_day=5),
758 [self.a],
759 )
760 self.assertSequenceEqual(
761 Article.objects.filter(pub_date__week_day=6),
762 [],
763 )
764
765 def test_does_not_exist(self):
766 # Django raises an Article.DoesNotExist exception for get() if the
767 # parameters don't match any object.
768 with self.assertRaisesMessage(
769 ObjectDoesNotExist, "Article matching query does not exist."
770 ):
771 Article.objects.get(
772 id__exact=2000,
773 )
774 # To avoid dict-ordering related errors check only one lookup
775 # in single assert.
776 with self.assertRaises(ObjectDoesNotExist):
777 Article.objects.get(pub_date__year=2005, pub_date__month=8)
778 with self.assertRaisesMessage(
779 ObjectDoesNotExist, "Article matching query does not exist."
780 ):
781 Article.objects.get(
782 pub_date__week_day=6,
783 )
784
785 def test_lookup_by_primary_key(self):
786 # Lookup by a primary key is the most common case, so Django
787 # provides a shortcut for primary-key exact lookups.
788 # The following is identical to articles.get(id=a.id).
789 self.assertEqual(Article.objects.get(pk=self.a.id), self.a)
790
791 # pk can be used as a shortcut for the primary key name in any query.
792 self.assertSequenceEqual(Article.objects.filter(pk__in=[self.a.id]), [self.a])
793
794 # Model instances of the same type and same ID are considered equal.
795 a = Article.objects.get(pk=self.a.id)
796 b = Article.objects.get(pk=self.a.id)
797 self.assertEqual(a, b)
798
799 def test_too_many(self):
800 # Create a very similar object
801 a = Article(
802 id=None,
803 headline="Swallow bites Python",
804 pub_date=datetime(2005, 7, 28),
805 )
806 a.save()
807
808 self.assertEqual(Article.objects.count(), 2)
809
810 # Django raises an Article.MultipleObjectsReturned exception if the
811 # lookup matches more than one object
812 msg = "get() returned more than one Article -- it returned 2!"
813 with self.assertRaisesMessage(MultipleObjectsReturned, msg):
814 Article.objects.get(
815 headline__startswith="Swallow",
816 )
817 with self.assertRaisesMessage(MultipleObjectsReturned, msg):
818 Article.objects.get(
819 pub_date__year=2005,
820 )
821 with self.assertRaisesMessage(MultipleObjectsReturned, msg):
822 Article.objects.get(pub_date__year=2005, pub_date__month=7)
823
824
825 class ConcurrentSaveTests(TransactionTestCase):
826 available_apps = ["basic"]
827
828 @skipUnlessDBFeature("test_db_allows_multiple_connections")
829 def test_concurrent_delete_with_save(self):
830 """
831 Test fetching, deleting and finally saving an object - we should get
832 an insert in this case.
833 """
834 a = Article.objects.create(headline="foo", pub_date=datetime.now())
835 exceptions = []
836
837 def deleter():
838 try:
839 # Do not delete a directly - doing so alters its state.
840 Article.objects.filter(pk=a.pk).delete()
841 except Exception as e:
842 exceptions.append(e)
843 finally:
844 connections[DEFAULT_DB_ALIAS].close()
845
846 self.assertEqual(len(exceptions), 0)
847 t = threading.Thread(target=deleter)
848 t.start()
849 t.join()
850 a.save()
851 self.assertEqual(Article.objects.get(pk=a.pk).headline, "foo")
852
853
854 class ManagerTest(SimpleTestCase):
855 QUERYSET_PROXY_METHODS = [
856 "none",
857 "count",
858 "dates",
859 "datetimes",
860 "distinct",
861 "extra",
862 "get",
863 "get_or_create",
864 "update_or_create",
865 "create",
866 "bulk_create",
867 "bulk_update",
868 "filter",
869 "aggregate",
870 "annotate",
871 "alias",
872 "complex_filter",
873 "exclude",
874 "in_bulk",
875 "iterator",
876 "earliest",
877 "latest",
878 "first",
879 "last",
880 "order_by",
881 "select_for_update",
882 "select_related",
883 "prefetch_related",
884 "values",
885 "values_list",
886 "update",
887 "reverse",
888 "defer",
889 "only",
890 "using",
891 "exists",
892 "contains",
893 "explain",
894 "_insert",
895 "_update",
896 "raw",
897 "union",
898 "intersection",
899 "difference",
900 "aaggregate",
901 "abulk_create",
902 "abulk_update",
903 "acontains",
904 "acount",
905 "acreate",
906 "aearliest",
907 "aexists",
908 "aexplain",
909 "afirst",
910 "aget",
911 "aget_or_create",
912 "ain_bulk",
913 "aiterator",
914 "alast",
915 "alatest",
916 "aupdate",
917 "aupdate_or_create",
918 ]
919
920 def test_manager_methods(self):
921 """
922 This test ensures that the correct set of methods from `QuerySet`
923 are copied onto `Manager`.
924
925 It's particularly useful to prevent accidentally leaking new methods
926 into `Manager`. New `QuerySet` methods that should also be copied onto
927 `Manager` will need to be added to `ManagerTest.QUERYSET_PROXY_METHODS`.
928 """
929 self.assertEqual(
930 sorted(BaseManager._get_queryset_methods(models.QuerySet)),
931 sorted(self.QUERYSET_PROXY_METHODS),
932 )
933
934 def test_manager_method_attributes(self):
935 self.assertEqual(Article.objects.get.__doc__, models.QuerySet.get.__doc__)
936 self.assertEqual(Article.objects.count.__name__, models.QuerySet.count.__name__)
937
938 def test_manager_method_signature(self):
939 self.assertEqual(
940 str(inspect.signature(Article.objects.bulk_create)),
941 "(objs, batch_size=None, ignore_conflicts=False, update_conflicts=False, "
942 "update_fields=None, unique_fields=None)",
943 )
944
945
946 class SelectOnSaveTests(TestCase):
947 def test_select_on_save(self):
948 a1 = Article.objects.create(pub_date=datetime.now())
949 with self.assertNumQueries(1):
950 a1.save()
951 asos = ArticleSelectOnSave.objects.create(pub_date=datetime.now())
952 with self.assertNumQueries(2):
953 asos.save()
954 with self.assertNumQueries(1):
955 asos.save(force_update=True)
956 Article.objects.all().delete()
957 with self.assertRaisesMessage(
958 DatabaseError, "Forced update did not affect any rows."
959 ):
960 with self.assertNumQueries(1):
961 asos.save(force_update=True)
962
963 def test_select_on_save_lying_update(self):
964 """
965 select_on_save works correctly if the database doesn't return correct
966 information about matched rows from UPDATE.
967 """
968 # Change the manager to not return "row matched" for update().
969 # We are going to change the Article's _base_manager class
970 # dynamically. This is a bit of a hack, but it seems hard to
971 # test this properly otherwise. Article's manager, because
972 # proxy models use their parent model's _base_manager.
973
974 orig_class = Article._base_manager._queryset_class
975
976 class FakeQuerySet(models.QuerySet):
977 # Make sure the _update method below is in fact called.
978 called = False
979
980 def _update(self, *args, **kwargs):
981 FakeQuerySet.called = True
982 super()._update(*args, **kwargs)
983 return 0
984
985 try:
986 Article._base_manager._queryset_class = FakeQuerySet
987 asos = ArticleSelectOnSave.objects.create(pub_date=datetime.now())
988 with self.assertNumQueries(3):
989 asos.save()
990 self.assertTrue(FakeQuerySet.called)
991 # This is not wanted behavior, but this is how Django has always
992 # behaved for databases that do not return correct information
993 # about matched rows for UPDATE.
994 with self.assertRaisesMessage(
995 DatabaseError, "Forced update did not affect any rows."
996 ):
997 asos.save(force_update=True)
998 msg = (
999 "An error occurred in the current transaction. You can't "
1000 "execute queries until the end of the 'atomic' block."
1001 )
1002 with self.assertRaisesMessage(DatabaseError, msg) as cm:
1003 asos.save(update_fields=["pub_date"])
1004 self.assertIsInstance(cm.exception.__cause__, DatabaseError)
1005 finally:
1006 Article._base_manager._queryset_class = orig_class
1007
1008
1009 class ModelRefreshTests(TestCase):
1010 def test_refresh(self):
1011 a = Article.objects.create(pub_date=datetime.now())
1012 Article.objects.create(pub_date=datetime.now())
1013 Article.objects.filter(pk=a.pk).update(headline="new headline")
1014 with self.assertNumQueries(1):
1015 a.refresh_from_db()
1016 self.assertEqual(a.headline, "new headline")
1017
1018 orig_pub_date = a.pub_date
1019 new_pub_date = a.pub_date + timedelta(10)
1020 Article.objects.update(headline="new headline 2", pub_date=new_pub_date)
1021 with self.assertNumQueries(1):
1022 a.refresh_from_db(fields=["headline"])
1023 self.assertEqual(a.headline, "new headline 2")
1024 self.assertEqual(a.pub_date, orig_pub_date)
1025 with self.assertNumQueries(1):
1026 a.refresh_from_db()
1027 self.assertEqual(a.pub_date, new_pub_date)
1028
1029 def test_unknown_kwarg(self):
1030 s = SelfRef.objects.create()
1031 msg = "refresh_from_db() got an unexpected keyword argument 'unknown_kwarg'"
1032 with self.assertRaisesMessage(TypeError, msg):
1033 s.refresh_from_db(unknown_kwarg=10)
1034
1035 def test_lookup_in_fields(self):
1036 s = SelfRef.objects.create()
1037 msg = (
1038 'Found "__" in fields argument. Relations and transforms are not allowed '
1039 "in fields."
1040 )
1041 with self.assertRaisesMessage(ValueError, msg):
1042 s.refresh_from_db(fields=["foo__bar"])
1043
1044 def test_refresh_fk(self):
1045 s1 = SelfRef.objects.create()
1046 s2 = SelfRef.objects.create()
1047 s3 = SelfRef.objects.create(selfref=s1)
1048 s3_copy = SelfRef.objects.get(pk=s3.pk)
1049 s3_copy.selfref.touched = True
1050 s3.selfref = s2
1051 s3.save()
1052 with self.assertNumQueries(1):
1053 s3_copy.refresh_from_db()
1054 with self.assertNumQueries(1):
1055 # The old related instance was thrown away (the selfref_id has
1056 # changed). It needs to be reloaded on access, so one query
1057 # executed.
1058 self.assertFalse(hasattr(s3_copy.selfref, "touched"))
1059 self.assertEqual(s3_copy.selfref, s2)
1060
1061 def test_refresh_null_fk(self):
1062 s1 = SelfRef.objects.create()
1063 s2 = SelfRef.objects.create(selfref=s1)
1064 s2.selfref = None
1065 s2.refresh_from_db()
1066 self.assertEqual(s2.selfref, s1)
1067
1068 def test_refresh_unsaved(self):
1069 pub_date = datetime.now()
1070 a = Article.objects.create(pub_date=pub_date)
1071 a2 = Article(id=a.pk)
1072 with self.assertNumQueries(1):
1073 a2.refresh_from_db()
1074 self.assertEqual(a2.pub_date, pub_date)
1075 self.assertEqual(a2._state.db, "default")
1076
1077 def test_refresh_fk_on_delete_set_null(self):
1078 a = Article.objects.create(
1079 headline="Parrot programs in Python",
1080 pub_date=datetime(2005, 7, 28),
1081 )
1082 s1 = SelfRef.objects.create(article=a)
1083 a.delete()
1084 s1.refresh_from_db()
1085 self.assertIsNone(s1.article_id)
1086 self.assertIsNone(s1.article)
1087
1088 def test_refresh_no_fields(self):
1089 a = Article.objects.create(pub_date=datetime.now())
1090 with self.assertNumQueries(0):
1091 a.refresh_from_db(fields=[])
1092
1093 def test_refresh_clears_reverse_related(self):
1094 """refresh_from_db() clear cached reverse relations."""
1095 article = Article.objects.create(
1096 headline="Parrot programs in Python",
1097 pub_date=datetime(2005, 7, 28),
1098 )
1099 self.assertFalse(hasattr(article, "featured"))
1100 FeaturedArticle.objects.create(article_id=article.pk)
1101 article.refresh_from_db()
1102 self.assertTrue(hasattr(article, "featured"))
1103
1104 def test_refresh_clears_reverse_related_explicit_fields(self):
1105 article = Article.objects.create(headline="Test", pub_date=datetime(2024, 2, 4))
1106 self.assertFalse(hasattr(article, "featured"))
1107 FeaturedArticle.objects.create(article_id=article.pk)
1108 article.refresh_from_db(fields=["featured"])
1109 self.assertTrue(hasattr(article, "featured"))
1110
1111 def test_refresh_clears_one_to_one_field(self):
1112 article = Article.objects.create(
1113 headline="Parrot programs in Python",
1114 pub_date=datetime(2005, 7, 28),
1115 )
1116 featured = FeaturedArticle.objects.create(article_id=article.pk)
1117 self.assertEqual(featured.article.headline, "Parrot programs in Python")
1118 article.headline = "Parrot programs in Python 2.0"
1119 article.save()
1120 featured.refresh_from_db()
1121 self.assertEqual(featured.article.headline, "Parrot programs in Python 2.0")
1122
1123 def test_prefetched_cache_cleared(self):
1124 a = Article.objects.create(pub_date=datetime(2005, 7, 28))
1125 s = SelfRef.objects.create(article=a, article_cited=a)
1126 # refresh_from_db() without fields=[...]
1127 a1_prefetched = Article.objects.prefetch_related("selfref_set", "cited").first()
1128 self.assertCountEqual(a1_prefetched.selfref_set.all(), [s])
1129 self.assertCountEqual(a1_prefetched.cited.all(), [s])
1130 s.article = None
1131 s.article_cited = None
1132 s.save()
1133 # Relation is cleared and prefetch cache is stale.
1134 self.assertCountEqual(a1_prefetched.selfref_set.all(), [s])
1135 self.assertCountEqual(a1_prefetched.cited.all(), [s])
1136 a1_prefetched.refresh_from_db()
1137 # Cache was cleared and new results are available.
1138 self.assertCountEqual(a1_prefetched.selfref_set.all(), [])
1139 self.assertCountEqual(a1_prefetched.cited.all(), [])
1140 # refresh_from_db() with fields=[...]
1141 a2_prefetched = Article.objects.prefetch_related("selfref_set", "cited").first()
1142 self.assertCountEqual(a2_prefetched.selfref_set.all(), [])
1143 self.assertCountEqual(a2_prefetched.cited.all(), [])
1144 s.article = a
1145 s.article_cited = a
1146 s.save()
1147 # Relation is added and prefetch cache is stale.
1148 self.assertCountEqual(a2_prefetched.selfref_set.all(), [])
1149 self.assertCountEqual(a2_prefetched.cited.all(), [])
1150 fields = ["selfref_set", "cited"]
1151 a2_prefetched.refresh_from_db(fields=fields)
1152 self.assertEqual(fields, ["selfref_set", "cited"])
1153 # Cache was cleared and new results are available.
1154 self.assertCountEqual(a2_prefetched.selfref_set.all(), [s])
1155 self.assertCountEqual(a2_prefetched.cited.all(), [s])
1156
1157 @skipUnlessDBFeature("has_select_for_update")
1158 def test_refresh_for_update(self):
1159 a = Article.objects.create(pub_date=datetime.now())
1160 for_update_sql = connection.ops.for_update_sql()
1161
1162 with transaction.atomic(), CaptureQueriesContext(connection) as ctx:
1163 a.refresh_from_db(from_queryset=Article.objects.select_for_update())
1164 self.assertTrue(
1165 any(for_update_sql in query["sql"] for query in ctx.captured_queries)
1166 )
1167
1168 def test_refresh_with_related(self):
1169 a = Article.objects.create(pub_date=datetime.now())
1170 fa = FeaturedArticle.objects.create(article=a)
1171
1172 from_queryset = FeaturedArticle.objects.select_related("article")
1173 with self.assertNumQueries(1):
1174 fa.refresh_from_db(from_queryset=from_queryset)
1175 self.assertEqual(fa.article.pub_date, a.pub_date)
1176 with self.assertNumQueries(2):
1177 fa.refresh_from_db()
1178 self.assertEqual(fa.article.pub_date, a.pub_date)
1179
1180 def test_refresh_overwrites_queryset_using(self):
1181 a = Article.objects.create(pub_date=datetime.now())
1182
1183 from_queryset = Article.objects.using("nonexistent")
1184 with self.assertRaises(ConnectionDoesNotExist):
1185 a.refresh_from_db(from_queryset=from_queryset)
1186 a.refresh_from_db(using="default", from_queryset=from_queryset)
1187
1188 def test_refresh_overwrites_queryset_fields(self):
1189 a = Article.objects.create(pub_date=datetime.now())
1190 headline = "headline"
1191 Article.objects.filter(pk=a.pk).update(headline=headline)
1192
1193 from_queryset = Article.objects.only("pub_date")
1194 with self.assertNumQueries(1):
1195 a.refresh_from_db(from_queryset=from_queryset)
1196 self.assertNotEqual(a.headline, headline)
1197 with self.assertNumQueries(1):
1198 a.refresh_from_db(fields=["headline"], from_queryset=from_queryset)
1199 self.assertEqual(a.headline, headline)