summaryrefslogtreecommitdiff
path: root/tests/basic
diff options
context:
space:
mode:
authordjango-bot <ops@djangoproject.com>2022-02-03 20:24:19 +0100
committerMariusz Felisiak <felisiak.mariusz@gmail.com>2022-02-07 20:37:05 +0100
commit9c19aff7c7561e3a82978a272ecdaad40dda5c00 (patch)
treef0506b668a013d0063e5fba3dbf4863b466713ba /tests/basic
parentf68fa8b45dfac545cfc4111d4e52804c86db68d3 (diff)
Refs #33476 -- Reformatted code with Black.
Diffstat (limited to 'tests/basic')
-rw-r--r--tests/basic/models.py13
-rw-r--r--tests/basic/tests.py451
2 files changed, 275 insertions, 189 deletions
diff --git a/tests/basic/models.py b/tests/basic/models.py
index 6dcdfa90c0..59a6a8d67f 100644
--- a/tests/basic/models.py
+++ b/tests/basic/models.py
@@ -9,18 +9,18 @@ from django.db import models
class Article(models.Model):
- headline = models.CharField(max_length=100, default='Default headline')
+ headline = models.CharField(max_length=100, default="Default headline")
pub_date = models.DateTimeField()
class Meta:
- ordering = ('pub_date', 'headline')
+ ordering = ("pub_date", "headline")
def __str__(self):
return self.headline
class FeaturedArticle(models.Model):
- article = models.OneToOneField(Article, models.CASCADE, related_name='featured')
+ article = models.OneToOneField(Article, models.CASCADE, related_name="featured")
class ArticleSelectOnSave(Article):
@@ -31,10 +31,11 @@ class ArticleSelectOnSave(Article):
class SelfRef(models.Model):
selfref = models.ForeignKey(
- 'self',
+ "self",
models.SET_NULL,
- null=True, blank=True,
- related_name='+',
+ null=True,
+ blank=True,
+ related_name="+",
)
article = models.ForeignKey(Article, models.SET_NULL, null=True, blank=True)
diff --git a/tests/basic/tests.py b/tests/basic/tests.py
index a3aab7baa7..4ff91388e6 100644
--- a/tests/basic/tests.py
+++ b/tests/basic/tests.py
@@ -7,22 +7,28 @@ from django.db import DEFAULT_DB_ALIAS, DatabaseError, connections, models
from django.db.models.manager import BaseManager
from django.db.models.query import MAX_GET_RESULTS, EmptyQuerySet
from django.test import (
- SimpleTestCase, TestCase, TransactionTestCase, skipUnlessDBFeature,
+ SimpleTestCase,
+ TestCase,
+ TransactionTestCase,
+ skipUnlessDBFeature,
)
from django.utils.translation import gettext_lazy
from .models import (
- Article, ArticleSelectOnSave, ChildPrimaryKeyWithDefault, FeaturedArticle,
- PrimaryKeyWithDefault, SelfRef,
+ Article,
+ ArticleSelectOnSave,
+ ChildPrimaryKeyWithDefault,
+ FeaturedArticle,
+ PrimaryKeyWithDefault,
+ SelfRef,
)
class ModelInstanceCreationTests(TestCase):
-
def test_object_is_not_written_to_database_until_save_was_called(self):
a = Article(
id=None,
- headline='Parrot programs in Python',
+ headline="Parrot programs in Python",
pub_date=datetime(2005, 7, 28),
)
self.assertIsNone(a.id)
@@ -38,62 +44,68 @@ class ModelInstanceCreationTests(TestCase):
You can initialize a model instance using positional arguments,
which should match the field order as defined in the model.
"""
- a = Article(None, 'Second article', datetime(2005, 7, 29))
+ a = Article(None, "Second article", datetime(2005, 7, 29))
a.save()
- self.assertEqual(a.headline, 'Second article')
+ self.assertEqual(a.headline, "Second article")
self.assertEqual(a.pub_date, datetime(2005, 7, 29, 0, 0))
def test_can_create_instance_using_kwargs(self):
a = Article(
id=None,
- headline='Third article',
+ headline="Third article",
pub_date=datetime(2005, 7, 30),
)
a.save()
- self.assertEqual(a.headline, 'Third article')
+ self.assertEqual(a.headline, "Third article")
self.assertEqual(a.pub_date, datetime(2005, 7, 30, 0, 0))
def test_autofields_generate_different_values_for_each_instance(self):
- a1 = Article.objects.create(headline='First', pub_date=datetime(2005, 7, 30, 0, 0))
- a2 = Article.objects.create(headline='First', pub_date=datetime(2005, 7, 30, 0, 0))
- a3 = Article.objects.create(headline='First', pub_date=datetime(2005, 7, 30, 0, 0))
+ a1 = Article.objects.create(
+ headline="First", pub_date=datetime(2005, 7, 30, 0, 0)
+ )
+ a2 = Article.objects.create(
+ headline="First", pub_date=datetime(2005, 7, 30, 0, 0)
+ )
+ a3 = Article.objects.create(
+ headline="First", pub_date=datetime(2005, 7, 30, 0, 0)
+ )
self.assertNotEqual(a3.id, a1.id)
self.assertNotEqual(a3.id, a2.id)
def test_can_mix_and_match_position_and_kwargs(self):
# You can also mix and match position and keyword arguments, but
# be sure not to duplicate field information.
- a = Article(None, 'Fourth article', pub_date=datetime(2005, 7, 31))
+ a = Article(None, "Fourth article", pub_date=datetime(2005, 7, 31))
a.save()
- self.assertEqual(a.headline, 'Fourth article')
+ self.assertEqual(a.headline, "Fourth article")
def test_positional_and_keyword_args_for_the_same_field(self):
msg = "Article() got both positional and keyword arguments for field '%s'."
- with self.assertRaisesMessage(TypeError, msg % 'headline'):
- Article(None, 'Fifth article', headline='Other headline.')
- with self.assertRaisesMessage(TypeError, msg % 'headline'):
- Article(None, 'Sixth article', headline='')
- with self.assertRaisesMessage(TypeError, msg % 'pub_date'):
- Article(None, 'Seventh article', datetime(2021, 3, 1), pub_date=None)
+ with self.assertRaisesMessage(TypeError, msg % "headline"):
+ Article(None, "Fifth article", headline="Other headline.")
+ with self.assertRaisesMessage(TypeError, msg % "headline"):
+ Article(None, "Sixth article", headline="")
+ with self.assertRaisesMessage(TypeError, msg % "pub_date"):
+ Article(None, "Seventh article", datetime(2021, 3, 1), pub_date=None)
def test_cannot_create_instance_with_invalid_kwargs(self):
msg = "Article() got unexpected keyword arguments: 'foo'"
with self.assertRaisesMessage(TypeError, msg):
Article(
id=None,
- headline='Some headline',
+ headline="Some headline",
pub_date=datetime(2005, 7, 31),
- foo='bar',
+ foo="bar",
)
msg = "Article() got unexpected keyword arguments: 'foo', 'bar'"
with self.assertRaisesMessage(TypeError, msg):
Article(
id=None,
- headline='Some headline',
+ headline="Some headline",
pub_date=datetime(2005, 7, 31),
- foo='bar',
- bar='baz',
+ foo="bar",
+ bar="baz",
)
def test_can_leave_off_value_for_autofield_and_it_gets_value_on_save(self):
@@ -101,51 +113,55 @@ class ModelInstanceCreationTests(TestCase):
You can leave off the value for an AutoField when creating an
object, because it'll get filled in automatically when you save().
"""
- a = Article(headline='Article 5', pub_date=datetime(2005, 7, 31))
+ a = Article(headline="Article 5", pub_date=datetime(2005, 7, 31))
a.save()
- self.assertEqual(a.headline, 'Article 5')
+ self.assertEqual(a.headline, "Article 5")
self.assertIsNotNone(a.id)
def test_leaving_off_a_field_with_default_set_the_default_will_be_saved(self):
a = Article(pub_date=datetime(2005, 7, 31))
a.save()
- self.assertEqual(a.headline, 'Default headline')
+ self.assertEqual(a.headline, "Default headline")
def test_for_datetimefields_saves_as_much_precision_as_was_given(self):
"""as much precision in *seconds*"""
a1 = Article(
- headline='Article 7',
+ headline="Article 7",
pub_date=datetime(2005, 7, 31, 12, 30),
)
a1.save()
- self.assertEqual(Article.objects.get(id__exact=a1.id).pub_date, datetime(2005, 7, 31, 12, 30))
+ self.assertEqual(
+ Article.objects.get(id__exact=a1.id).pub_date, datetime(2005, 7, 31, 12, 30)
+ )
a2 = Article(
- headline='Article 8',
+ headline="Article 8",
pub_date=datetime(2005, 7, 31, 12, 30, 45),
)
a2.save()
- self.assertEqual(Article.objects.get(id__exact=a2.id).pub_date, datetime(2005, 7, 31, 12, 30, 45))
+ self.assertEqual(
+ Article.objects.get(id__exact=a2.id).pub_date,
+ datetime(2005, 7, 31, 12, 30, 45),
+ )
def test_saving_an_object_again_does_not_create_a_new_object(self):
- a = Article(headline='original', pub_date=datetime(2014, 5, 16))
+ a = Article(headline="original", pub_date=datetime(2014, 5, 16))
a.save()
current_id = a.id
a.save()
self.assertEqual(a.id, current_id)
- a.headline = 'Updated headline'
+ a.headline = "Updated headline"
a.save()
self.assertEqual(a.id, current_id)
def test_querysets_checking_for_membership(self):
- headlines = [
- 'Parrot programs in Python', 'Second article', 'Third article']
+ headlines = ["Parrot programs in Python", "Second article", "Third article"]
some_pub_date = datetime(2014, 5, 16, 12, 1)
for headline in headlines:
Article(headline=headline, pub_date=some_pub_date).save()
- a = Article(headline='Some headline', pub_date=some_pub_date)
+ a = Article(headline="Some headline", pub_date=some_pub_date)
a.save()
# You can use 'in' to test for membership...
@@ -167,52 +183,61 @@ class ModelInstanceCreationTests(TestCase):
class ModelTest(TestCase):
def test_objects_attribute_is_only_available_on_the_class_itself(self):
- with self.assertRaisesMessage(AttributeError, "Manager isn't accessible via Article instances"):
- getattr(Article(), "objects",)
- self.assertFalse(hasattr(Article(), 'objects'))
- self.assertTrue(hasattr(Article, 'objects'))
+ with self.assertRaisesMessage(
+ AttributeError, "Manager isn't accessible via Article instances"
+ ):
+ getattr(
+ Article(),
+ "objects",
+ )
+ self.assertFalse(hasattr(Article(), "objects"))
+ self.assertTrue(hasattr(Article, "objects"))
def test_queryset_delete_removes_all_items_in_that_queryset(self):
- headlines = [
- 'An article', 'Article One', 'Amazing article', 'Boring article']
+ headlines = ["An article", "Article One", "Amazing article", "Boring article"]
some_pub_date = datetime(2014, 5, 16, 12, 1)
for headline in headlines:
Article(headline=headline, pub_date=some_pub_date).save()
self.assertQuerysetEqual(
- Article.objects.all().order_by('headline'),
+ Article.objects.all().order_by("headline"),
sorted(headlines),
transform=lambda a: a.headline,
)
- Article.objects.filter(headline__startswith='A').delete()
- self.assertEqual(Article.objects.get().headline, 'Boring article')
+ Article.objects.filter(headline__startswith="A").delete()
+ self.assertEqual(Article.objects.get().headline, "Boring article")
def test_not_equal_and_equal_operators_behave_as_expected_on_instances(self):
some_pub_date = datetime(2014, 5, 16, 12, 1)
- a1 = Article.objects.create(headline='First', pub_date=some_pub_date)
- a2 = Article.objects.create(headline='Second', pub_date=some_pub_date)
+ a1 = Article.objects.create(headline="First", pub_date=some_pub_date)
+ a2 = Article.objects.create(headline="Second", pub_date=some_pub_date)
self.assertNotEqual(a1, a2)
self.assertEqual(a1, Article.objects.get(id__exact=a1.id))
- self.assertNotEqual(Article.objects.get(id__exact=a1.id), Article.objects.get(id__exact=a2.id))
+ self.assertNotEqual(
+ Article.objects.get(id__exact=a1.id), Article.objects.get(id__exact=a2.id)
+ )
def test_microsecond_precision(self):
a9 = Article(
- headline='Article 9',
+ headline="Article 9",
pub_date=datetime(2005, 7, 31, 12, 30, 45, 180),
)
a9.save()
- self.assertEqual(Article.objects.get(pk=a9.pk).pub_date, datetime(2005, 7, 31, 12, 30, 45, 180))
+ self.assertEqual(
+ Article.objects.get(pk=a9.pk).pub_date,
+ datetime(2005, 7, 31, 12, 30, 45, 180),
+ )
def test_manually_specify_primary_key(self):
# You can manually specify the primary key when creating a new object.
a101 = Article(
id=101,
- headline='Article 101',
+ headline="Article 101",
pub_date=datetime(2005, 7, 31, 12, 30, 45),
)
a101.save()
a101 = Article.objects.get(pk=101)
- self.assertEqual(a101.headline, 'Article 101')
+ self.assertEqual(a101.headline, "Article 101")
def test_create_method(self):
# You can create saved objects in a single step
@@ -226,11 +251,11 @@ class ModelTest(TestCase):
# Edge-case test: A year lookup should retrieve all objects in
# the given year, including Jan. 1 and Dec. 31.
a11 = Article.objects.create(
- headline='Article 11',
+ headline="Article 11",
pub_date=datetime(2008, 1, 1),
)
a12 = Article.objects.create(
- headline='Article 12',
+ headline="Article 12",
pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999),
)
self.assertSequenceEqual(
@@ -241,11 +266,13 @@ class ModelTest(TestCase):
def test_unicode_data(self):
# Unicode data works, too.
a = Article(
- headline='\u6797\u539f \u3081\u3050\u307f',
+ headline="\u6797\u539f \u3081\u3050\u307f",
pub_date=datetime(2005, 7, 28),
)
a.save()
- self.assertEqual(Article.objects.get(pk=a.id).headline, '\u6797\u539f \u3081\u3050\u307f')
+ self.assertEqual(
+ Article.objects.get(pk=a.id).headline, "\u6797\u539f \u3081\u3050\u307f"
+ )
def test_hash_function(self):
# Model instances have a hash function, so they can be used in sets
@@ -256,44 +283,64 @@ class ModelTest(TestCase):
pub_date=datetime(2005, 7, 31, 12, 30, 45),
)
a11 = Article.objects.create(
- headline='Article 11',
+ headline="Article 11",
pub_date=datetime(2008, 1, 1),
)
a12 = Article.objects.create(
- headline='Article 12',
+ headline="Article 12",
pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999),
)
s = {a10, a11, a12}
- self.assertIn(Article.objects.get(headline='Article 11'), s)
+ self.assertIn(Article.objects.get(headline="Article 11"), s)
def test_extra_method_select_argument_with_dashes_and_values(self):
# The 'select' argument to extra() supports names with dashes in
# them, as long as you use values().
- Article.objects.bulk_create([
- Article(headline='Article 10', pub_date=datetime(2005, 7, 31, 12, 30, 45)),
- Article(headline='Article 11', pub_date=datetime(2008, 1, 1)),
- Article(headline='Article 12', pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999)),
- ])
- dicts = Article.objects.filter(
- pub_date__year=2008).extra(
- select={'dashed-value': '1'}).values('headline', 'dashed-value')
+ Article.objects.bulk_create(
+ [
+ Article(
+ headline="Article 10", pub_date=datetime(2005, 7, 31, 12, 30, 45)
+ ),
+ Article(headline="Article 11", pub_date=datetime(2008, 1, 1)),
+ Article(
+ headline="Article 12",
+ pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999),
+ ),
+ ]
+ )
+ dicts = (
+ Article.objects.filter(pub_date__year=2008)
+ .extra(select={"dashed-value": "1"})
+ .values("headline", "dashed-value")
+ )
self.assertEqual(
[sorted(d.items()) for d in dicts],
- [[('dashed-value', 1), ('headline', 'Article 11')], [('dashed-value', 1), ('headline', 'Article 12')]]
+ [
+ [("dashed-value", 1), ("headline", "Article 11")],
+ [("dashed-value", 1), ("headline", "Article 12")],
+ ],
)
def test_extra_method_select_argument_with_dashes(self):
# If you use 'select' with extra() and names containing dashes on a
# query that's *not* a values() query, those extra 'select' values
# will silently be ignored.
- Article.objects.bulk_create([
- Article(headline='Article 10', pub_date=datetime(2005, 7, 31, 12, 30, 45)),
- Article(headline='Article 11', pub_date=datetime(2008, 1, 1)),
- Article(headline='Article 12', pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999)),
- ])
- articles = Article.objects.filter(
- pub_date__year=2008).extra(select={'dashed-value': '1', 'undashedvalue': '2'})
+ Article.objects.bulk_create(
+ [
+ Article(
+ headline="Article 10", pub_date=datetime(2005, 7, 31, 12, 30, 45)
+ ),
+ Article(headline="Article 11", pub_date=datetime(2008, 1, 1)),
+ Article(
+ headline="Article 12",
+ pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999),
+ ),
+ ]
+ )
+ articles = Article.objects.filter(pub_date__year=2008).extra(
+ select={"dashed-value": "1", "undashedvalue": "2"}
+ )
self.assertEqual(articles[0].undashedvalue, 2)
def test_create_relation_with_gettext_lazy(self):
@@ -301,7 +348,7 @@ class ModelTest(TestCase):
gettext_lazy objects work when saving model instances
through various methods. Refs #10498.
"""
- notlazy = 'test'
+ notlazy = "test"
lazy = gettext_lazy(notlazy)
Article.objects.create(headline=lazy, pub_date=datetime.now())
article = Article.objects.get()
@@ -325,23 +372,23 @@ class ModelTest(TestCase):
with self.assertRaisesMessage(TypeError, msg):
EmptyQuerySet()
self.assertIsInstance(Article.objects.none(), EmptyQuerySet)
- self.assertNotIsInstance('', EmptyQuerySet)
+ self.assertNotIsInstance("", EmptyQuerySet)
def test_emptyqs_values(self):
# test for #15959
- Article.objects.create(headline='foo', pub_date=datetime.now())
+ Article.objects.create(headline="foo", pub_date=datetime.now())
with self.assertNumQueries(0):
- qs = Article.objects.none().values_list('pk')
+ qs = Article.objects.none().values_list("pk")
self.assertIsInstance(qs, EmptyQuerySet)
self.assertEqual(len(qs), 0)
def test_emptyqs_customqs(self):
# A hacky test for custom QuerySet subclass - refs #17271
- Article.objects.create(headline='foo', pub_date=datetime.now())
+ Article.objects.create(headline="foo", pub_date=datetime.now())
class CustomQuerySet(models.QuerySet):
def do_something(self):
- return 'did something'
+ return "did something"
qs = Article.objects.all()
qs.__class__ = CustomQuerySet
@@ -349,23 +396,33 @@ class ModelTest(TestCase):
with self.assertNumQueries(0):
self.assertEqual(len(qs), 0)
self.assertIsInstance(qs, EmptyQuerySet)
- self.assertEqual(qs.do_something(), 'did something')
+ self.assertEqual(qs.do_something(), "did something")
def test_emptyqs_values_order(self):
# Tests for ticket #17712
- Article.objects.create(headline='foo', pub_date=datetime.now())
+ Article.objects.create(headline="foo", pub_date=datetime.now())
with self.assertNumQueries(0):
- self.assertEqual(len(Article.objects.none().values_list('id').order_by('id')), 0)
+ self.assertEqual(
+ len(Article.objects.none().values_list("id").order_by("id")), 0
+ )
with self.assertNumQueries(0):
- self.assertEqual(len(Article.objects.none().filter(
- id__in=Article.objects.values_list('id', flat=True))), 0)
+ self.assertEqual(
+ len(
+ Article.objects.none().filter(
+ id__in=Article.objects.values_list("id", flat=True)
+ )
+ ),
+ 0,
+ )
- @skipUnlessDBFeature('can_distinct_on_fields')
+ @skipUnlessDBFeature("can_distinct_on_fields")
def test_emptyqs_distinct(self):
# Tests for #19426
- Article.objects.create(headline='foo', pub_date=datetime.now())
+ Article.objects.create(headline="foo", pub_date=datetime.now())
with self.assertNumQueries(0):
- self.assertEqual(len(Article.objects.none().distinct('headline', 'pub_date')), 0)
+ self.assertEqual(
+ len(Article.objects.none().distinct("headline", "pub_date")), 0
+ )
def test_ticket_20278(self):
sr = SelfRef.objects.create()
@@ -384,7 +441,7 @@ class ModelTest(TestCase):
def test_hash(self):
# Value based on PK
self.assertEqual(hash(Article(id=1)), hash(1))
- msg = 'Model instances without primary key value are unhashable'
+ msg = "Model instances without primary key value are unhashable"
with self.assertRaisesMessage(TypeError, msg):
# No PK value -> unhashable (because save() would then change
# hash)
@@ -410,34 +467,37 @@ class ModelTest(TestCase):
def test_delete_and_access_field(self):
# Accessing a field after it's deleted from a model reloads its value.
pub_date = datetime.now()
- article = Article.objects.create(headline='foo', pub_date=pub_date)
+ article = Article.objects.create(headline="foo", pub_date=pub_date)
new_pub_date = article.pub_date + timedelta(days=10)
- article.headline = 'bar'
+ article.headline = "bar"
article.pub_date = new_pub_date
del article.headline
with self.assertNumQueries(1):
- self.assertEqual(article.headline, 'foo')
+ self.assertEqual(article.headline, "foo")
# Fields that weren't deleted aren't reloaded.
self.assertEqual(article.pub_date, new_pub_date)
def test_multiple_objects_max_num_fetched(self):
max_results = MAX_GET_RESULTS - 1
Article.objects.bulk_create(
- Article(headline='Area %s' % i, pub_date=datetime(2005, 7, 28))
+ Article(headline="Area %s" % i, pub_date=datetime(2005, 7, 28))
for i in range(max_results)
)
self.assertRaisesMessage(
MultipleObjectsReturned,
- 'get() returned more than one Article -- it returned %d!' % max_results,
+ "get() returned more than one Article -- it returned %d!" % max_results,
Article.objects.get,
- headline__startswith='Area',
+ headline__startswith="Area",
+ )
+ Article.objects.create(
+ headline="Area %s" % max_results, pub_date=datetime(2005, 7, 28)
)
- Article.objects.create(headline='Area %s' % max_results, pub_date=datetime(2005, 7, 28))
self.assertRaisesMessage(
MultipleObjectsReturned,
- 'get() returned more than one Article -- it returned more than %d!' % max_results,
+ "get() returned more than one Article -- it returned more than %d!"
+ % max_results,
Article.objects.get,
- headline__startswith='Area',
+ headline__startswith="Area",
)
@@ -447,7 +507,7 @@ class ModelLookupTest(TestCase):
# Create an Article.
cls.a = Article(
id=None,
- headline='Swallow programs in Python',
+ headline="Swallow programs in Python",
pub_date=datetime(2005, 7, 28),
)
# Save it into the database. You have to call save() explicitly.
@@ -455,7 +515,7 @@ class ModelLookupTest(TestCase):
def test_all_lookup(self):
# Change values by changing the attributes, then calling save().
- self.a.headline = 'Parrot programs in Python'
+ self.a.headline = "Parrot programs in Python"
self.a.save()
# Article.objects.all() returns all the articles in the database.
@@ -464,16 +524,25 @@ class ModelLookupTest(TestCase):
def test_rich_lookup(self):
# Django provides a rich database lookup API.
self.assertEqual(Article.objects.get(id__exact=self.a.id), self.a)
- self.assertEqual(Article.objects.get(headline__startswith='Swallow'), self.a)
+ self.assertEqual(Article.objects.get(headline__startswith="Swallow"), self.a)
self.assertEqual(Article.objects.get(pub_date__year=2005), self.a)
- self.assertEqual(Article.objects.get(pub_date__year=2005, pub_date__month=7), self.a)
- self.assertEqual(Article.objects.get(pub_date__year=2005, pub_date__month=7, pub_date__day=28), self.a)
+ self.assertEqual(
+ Article.objects.get(pub_date__year=2005, pub_date__month=7), self.a
+ )
+ self.assertEqual(
+ Article.objects.get(
+ pub_date__year=2005, pub_date__month=7, pub_date__day=28
+ ),
+ self.a,
+ )
self.assertEqual(Article.objects.get(pub_date__week_day=5), self.a)
def test_equal_lookup(self):
# The "__exact" lookup type can be omitted, as a shortcut.
self.assertEqual(Article.objects.get(id=self.a.id), self.a)
- self.assertEqual(Article.objects.get(headline='Swallow programs in Python'), self.a)
+ self.assertEqual(
+ Article.objects.get(headline="Swallow programs in Python"), self.a
+ )
self.assertSequenceEqual(
Article.objects.filter(pub_date__year=2005),
@@ -500,14 +569,22 @@ class ModelLookupTest(TestCase):
def test_does_not_exist(self):
# Django raises an Article.DoesNotExist exception for get() if the
# parameters don't match any object.
- with self.assertRaisesMessage(ObjectDoesNotExist, "Article matching query does not exist."):
- Article.objects.get(id__exact=2000,)
+ with self.assertRaisesMessage(
+ ObjectDoesNotExist, "Article matching query does not exist."
+ ):
+ Article.objects.get(
+ id__exact=2000,
+ )
# To avoid dict-ordering related errors check only one lookup
# in single assert.
with self.assertRaises(ObjectDoesNotExist):
Article.objects.get(pub_date__year=2005, pub_date__month=8)
- with self.assertRaisesMessage(ObjectDoesNotExist, "Article matching query does not exist."):
- Article.objects.get(pub_date__week_day=6,)
+ with self.assertRaisesMessage(
+ ObjectDoesNotExist, "Article matching query does not exist."
+ ):
+ Article.objects.get(
+ pub_date__week_day=6,
+ )
def test_lookup_by_primary_key(self):
# Lookup by a primary key is the most common case, so Django
@@ -527,7 +604,7 @@ class ModelLookupTest(TestCase):
# Create a very similar object
a = Article(
id=None,
- headline='Swallow bites Python',
+ headline="Swallow bites Python",
pub_date=datetime(2005, 7, 28),
)
a.save()
@@ -538,24 +615,28 @@ class ModelLookupTest(TestCase):
# lookup matches more than one object
msg = "get() returned more than one Article -- it returned 2!"
with self.assertRaisesMessage(MultipleObjectsReturned, msg):
- Article.objects.get(headline__startswith='Swallow',)
+ Article.objects.get(
+ headline__startswith="Swallow",
+ )
with self.assertRaisesMessage(MultipleObjectsReturned, msg):
- Article.objects.get(pub_date__year=2005,)
+ Article.objects.get(
+ pub_date__year=2005,
+ )
with self.assertRaisesMessage(MultipleObjectsReturned, msg):
Article.objects.get(pub_date__year=2005, pub_date__month=7)
class ConcurrentSaveTests(TransactionTestCase):
- available_apps = ['basic']
+ available_apps = ["basic"]
- @skipUnlessDBFeature('test_db_allows_multiple_connections')
+ @skipUnlessDBFeature("test_db_allows_multiple_connections")
def test_concurrent_delete_with_save(self):
"""
Test fetching, deleting and finally saving an object - we should get
an insert in this case.
"""
- a = Article.objects.create(headline='foo', pub_date=datetime.now())
+ a = Article.objects.create(headline="foo", pub_date=datetime.now())
exceptions = []
def deleter():
@@ -566,60 +647,61 @@ class ConcurrentSaveTests(TransactionTestCase):
exceptions.append(e)
finally:
connections[DEFAULT_DB_ALIAS].close()
+
self.assertEqual(len(exceptions), 0)
t = threading.Thread(target=deleter)
t.start()
t.join()
a.save()
- self.assertEqual(Article.objects.get(pk=a.pk).headline, 'foo')
+ self.assertEqual(Article.objects.get(pk=a.pk).headline, "foo")
class ManagerTest(SimpleTestCase):
QUERYSET_PROXY_METHODS = [
- 'none',
- 'count',
- 'dates',
- 'datetimes',
- 'distinct',
- 'extra',
- 'get',
- 'get_or_create',
- 'update_or_create',
- 'create',
- 'bulk_create',
- 'bulk_update',
- 'filter',
- 'aggregate',
- 'annotate',
- 'alias',
- 'complex_filter',
- 'exclude',
- 'in_bulk',
- 'iterator',
- 'earliest',
- 'latest',
- 'first',
- 'last',
- 'order_by',
- 'select_for_update',
- 'select_related',
- 'prefetch_related',
- 'values',
- 'values_list',
- 'update',
- 'reverse',
- 'defer',
- 'only',
- 'using',
- 'exists',
- 'contains',
- 'explain',
- '_insert',
- '_update',
- 'raw',
- 'union',
- 'intersection',
- 'difference',
+ "none",
+ "count",
+ "dates",
+ "datetimes",
+ "distinct",
+ "extra",
+ "get",
+ "get_or_create",
+ "update_or_create",
+ "create",
+ "bulk_create",
+ "bulk_update",
+ "filter",
+ "aggregate",
+ "annotate",
+ "alias",
+ "complex_filter",
+ "exclude",
+ "in_bulk",
+ "iterator",
+ "earliest",
+ "latest",
+ "first",
+ "last",
+ "order_by",
+ "select_for_update",
+ "select_related",
+ "prefetch_related",
+ "values",
+ "values_list",
+ "update",
+ "reverse",
+ "defer",
+ "only",
+ "using",
+ "exists",
+ "contains",
+ "explain",
+ "_insert",
+ "_update",
+ "raw",
+ "union",
+ "intersection",
+ "difference",
]
def test_manager_methods(self):
@@ -648,7 +730,9 @@ class SelectOnSaveTests(TestCase):
with self.assertNumQueries(1):
asos.save(force_update=True)
Article.objects.all().delete()
- with self.assertRaisesMessage(DatabaseError, 'Forced update did not affect any rows.'):
+ with self.assertRaisesMessage(
+ DatabaseError, "Forced update did not affect any rows."
+ ):
with self.assertNumQueries(1):
asos.save(force_update=True)
@@ -683,34 +767,35 @@ class SelectOnSaveTests(TestCase):
# This is not wanted behavior, but this is how Django has always
# behaved for databases that do not return correct information
# about matched rows for UPDATE.
- with self.assertRaisesMessage(DatabaseError, 'Forced update did not affect any rows.'):
+ with self.assertRaisesMessage(
+ DatabaseError, "Forced update did not affect any rows."
+ ):
asos.save(force_update=True)
msg = (
"An error occurred in the current transaction. You can't "
"execute queries until the end of the 'atomic' block."
)
with self.assertRaisesMessage(DatabaseError, msg):
- asos.save(update_fields=['pub_date'])
+ asos.save(update_fields=["pub_date"])
finally:
Article._base_manager._queryset_class = orig_class
class ModelRefreshTests(TestCase):
-
def test_refresh(self):
a = Article.objects.create(pub_date=datetime.now())
Article.objects.create(pub_date=datetime.now())
- Article.objects.filter(pk=a.pk).update(headline='new headline')
+ Article.objects.filter(pk=a.pk).update(headline="new headline")
with self.assertNumQueries(1):
a.refresh_from_db()
- self.assertEqual(a.headline, 'new headline')
+ self.assertEqual(a.headline, "new headline")
orig_pub_date = a.pub_date
new_pub_date = a.pub_date + timedelta(10)
- Article.objects.update(headline='new headline 2', pub_date=new_pub_date)
+ Article.objects.update(headline="new headline 2", pub_date=new_pub_date)
with self.assertNumQueries(1):
- a.refresh_from_db(fields=['headline'])
- self.assertEqual(a.headline, 'new headline 2')
+ a.refresh_from_db(fields=["headline"])
+ self.assertEqual(a.headline, "new headline 2")
self.assertEqual(a.pub_date, orig_pub_date)
with self.assertNumQueries(1):
a.refresh_from_db()
@@ -726,7 +811,7 @@ class ModelRefreshTests(TestCase):
s = SelfRef.objects.create()
msg = 'Found "__" in fields argument. Relations and transforms are not allowed in fields.'
with self.assertRaisesMessage(ValueError, msg):
- s.refresh_from_db(fields=['foo__bar'])
+ s.refresh_from_db(fields=["foo__bar"])
def test_refresh_fk(self):
s1 = SelfRef.objects.create()
@@ -742,7 +827,7 @@ class ModelRefreshTests(TestCase):
# The old related instance was thrown away (the selfref_id has
# changed). It needs to be reloaded on access, so one query
# executed.
- self.assertFalse(hasattr(s3_copy.selfref, 'touched'))
+ self.assertFalse(hasattr(s3_copy.selfref, "touched"))
self.assertEqual(s3_copy.selfref, s2)
def test_refresh_null_fk(self):
@@ -763,7 +848,7 @@ class ModelRefreshTests(TestCase):
def test_refresh_fk_on_delete_set_null(self):
a = Article.objects.create(
- headline='Parrot programs in Python',
+ headline="Parrot programs in Python",
pub_date=datetime(2005, 7, 28),
)
s1 = SelfRef.objects.create(article=a)
@@ -780,31 +865,31 @@ class ModelRefreshTests(TestCase):
def test_refresh_clears_reverse_related(self):
"""refresh_from_db() clear cached reverse relations."""
article = Article.objects.create(
- headline='Parrot programs in Python',
+ headline="Parrot programs in Python",
pub_date=datetime(2005, 7, 28),
)
- self.assertFalse(hasattr(article, 'featured'))
+ self.assertFalse(hasattr(article, "featured"))
FeaturedArticle.objects.create(article_id=article.pk)
article.refresh_from_db()
- self.assertTrue(hasattr(article, 'featured'))
+ self.assertTrue(hasattr(article, "featured"))
def test_refresh_clears_one_to_one_field(self):
article = Article.objects.create(
- headline='Parrot programs in Python',
+ headline="Parrot programs in Python",
pub_date=datetime(2005, 7, 28),
)
featured = FeaturedArticle.objects.create(article_id=article.pk)
- self.assertEqual(featured.article.headline, 'Parrot programs in Python')
- article.headline = 'Parrot programs in Python 2.0'
+ self.assertEqual(featured.article.headline, "Parrot programs in Python")
+ article.headline = "Parrot programs in Python 2.0"
article.save()
featured.refresh_from_db()
- self.assertEqual(featured.article.headline, 'Parrot programs in Python 2.0')
+ self.assertEqual(featured.article.headline, "Parrot programs in Python 2.0")
def test_prefetched_cache_cleared(self):
a = Article.objects.create(pub_date=datetime(2005, 7, 28))
s = SelfRef.objects.create(article=a)
# refresh_from_db() without fields=[...]
- a1_prefetched = Article.objects.prefetch_related('selfref_set').first()
+ a1_prefetched = Article.objects.prefetch_related("selfref_set").first()
self.assertCountEqual(a1_prefetched.selfref_set.all(), [s])
s.article = None
s.save()
@@ -814,12 +899,12 @@ class ModelRefreshTests(TestCase):
# Cache was cleared and new results are available.
self.assertCountEqual(a1_prefetched.selfref_set.all(), [])
# refresh_from_db() with fields=[...]
- a2_prefetched = Article.objects.prefetch_related('selfref_set').first()
+ a2_prefetched = Article.objects.prefetch_related("selfref_set").first()
self.assertCountEqual(a2_prefetched.selfref_set.all(), [])
s.article = a
s.save()
# Relation is added and prefetch cache is stale.
self.assertCountEqual(a2_prefetched.selfref_set.all(), [])
- a2_prefetched.refresh_from_db(fields=['selfref_set'])
+ a2_prefetched.refresh_from_db(fields=["selfref_set"])
# Cache was cleared and new results are available.
self.assertCountEqual(a2_prefetched.selfref_set.all(), [s])