1
0
mirror of https://github.com/django/django.git synced 2025-10-31 09:41:08 +00:00

Refs #33476 -- Reformatted code with Black.

This commit is contained in:
django-bot
2022-02-03 20:24:19 +01:00
committed by Mariusz Felisiak
parent f68fa8b45d
commit 9c19aff7c7
1992 changed files with 139577 additions and 96284 deletions

View File

@@ -28,7 +28,7 @@ class Stuff(models.Model):
owner = models.ForeignKey(User, models.SET_NULL, null=True)
def __str__(self):
return self.name + ' is owned by ' + str(self.owner)
return self.name + " is owned by " + str(self.owner)
class Absolute(models.Model):
@@ -39,7 +39,7 @@ class Parent(models.Model):
name = models.CharField(max_length=10)
class Meta:
ordering = ('id',)
ordering = ("id",)
class Child(Parent):
@@ -56,7 +56,7 @@ class Article(models.Model):
channels = models.ManyToManyField(Channel)
class Meta:
ordering = ('id',)
ordering = ("id",)
# Subclass of a model with a ManyToManyField for test_ticket_20820
@@ -66,7 +66,6 @@ class SpecialArticle(Article):
# Models to regression test #22421
class CommonFeature(Article):
class Meta:
abstract = True
@@ -80,7 +79,7 @@ class Widget(models.Model):
name = models.CharField(max_length=255)
class Meta:
ordering = ('name',)
ordering = ("name",)
def __str__(self):
return self.name
@@ -99,12 +98,12 @@ class TestManager(models.Manager):
class Store(models.Model):
name = models.CharField(max_length=255, unique=True)
main = models.ForeignKey('self', models.SET_NULL, null=True)
main = models.ForeignKey("self", models.SET_NULL, null=True)
objects = TestManager()
class Meta:
ordering = ('name',)
ordering = ("name",)
def __str__(self):
return self.name
@@ -119,7 +118,7 @@ class Person(models.Model):
objects = TestManager()
class Meta:
ordering = ('name',)
ordering = ("name",)
def __str__(self):
return self.name
@@ -128,7 +127,8 @@ class Person(models.Model):
# one to test the behavior of the dependency resolution algorithm.
def natural_key(self):
return (self.name,)
natural_key.dependencies = ['fixtures_regress.store']
natural_key.dependencies = ["fixtures_regress.store"]
class Book(models.Model):
@@ -137,13 +137,13 @@ class Book(models.Model):
stores = models.ManyToManyField(Store)
class Meta:
ordering = ('name',)
ordering = ("name",)
def __str__(self):
return '%s by %s (available at %s)' % (
return "%s by %s (available at %s)" % (
self.name,
self.author.name,
', '.join(s.name for s in self.stores.all())
", ".join(s.name for s in self.stores.all()),
)
@@ -160,19 +160,19 @@ class NKChild(Parent):
return (self.data,)
def __str__(self):
return 'NKChild %s:%s' % (self.name, self.data)
return "NKChild %s:%s" % (self.name, self.data)
class RefToNKChild(models.Model):
text = models.CharField(max_length=10)
nk_fk = models.ForeignKey(NKChild, models.CASCADE, related_name='ref_fks')
nk_m2m = models.ManyToManyField(NKChild, related_name='ref_m2ms')
nk_fk = models.ForeignKey(NKChild, models.CASCADE, related_name="ref_fks")
nk_m2m = models.ManyToManyField(NKChild, related_name="ref_m2ms")
def __str__(self):
return '%s: Reference to %s [%s]' % (
return "%s: Reference to %s [%s]" % (
self.text,
self.nk_fk,
', '.join(str(o) for o in self.nk_m2m.all())
", ".join(str(o) for o in self.nk_m2m.all()),
)
@@ -182,7 +182,8 @@ class Circle1(models.Model):
def natural_key(self):
return (self.name,)
natural_key.dependencies = ['fixtures_regress.circle2']
natural_key.dependencies = ["fixtures_regress.circle2"]
class Circle2(models.Model):
@@ -190,7 +191,8 @@ class Circle2(models.Model):
def natural_key(self):
return (self.name,)
natural_key.dependencies = ['fixtures_regress.circle1']
natural_key.dependencies = ["fixtures_regress.circle1"]
class Circle3(models.Model):
@@ -198,7 +200,8 @@ class Circle3(models.Model):
def natural_key(self):
return (self.name,)
natural_key.dependencies = ['fixtures_regress.circle3']
natural_key.dependencies = ["fixtures_regress.circle3"]
class Circle4(models.Model):
@@ -206,7 +209,8 @@ class Circle4(models.Model):
def natural_key(self):
return (self.name,)
natural_key.dependencies = ['fixtures_regress.circle5']
natural_key.dependencies = ["fixtures_regress.circle5"]
class Circle5(models.Model):
@@ -214,7 +218,8 @@ class Circle5(models.Model):
def natural_key(self):
return (self.name,)
natural_key.dependencies = ['fixtures_regress.circle6']
natural_key.dependencies = ["fixtures_regress.circle6"]
class Circle6(models.Model):
@@ -222,7 +227,8 @@ class Circle6(models.Model):
def natural_key(self):
return (self.name,)
natural_key.dependencies = ['fixtures_regress.circle4']
natural_key.dependencies = ["fixtures_regress.circle4"]
class ExternalDependency(models.Model):
@@ -230,7 +236,8 @@ class ExternalDependency(models.Model):
def natural_key(self):
return (self.name,)
natural_key.dependencies = ['fixtures_regress.book']
natural_key.dependencies = ["fixtures_regress.book"]
# Model for regression test of #11101
@@ -246,6 +253,7 @@ class BaseNKModel(models.Model):
"""
Base model with a natural_key and a manager with `get_by_natural_key`
"""
data = models.CharField(max_length=20, unique=True)
objects = NKManager()
@@ -290,18 +298,21 @@ class M2MThroughAB(BaseNKModel):
class M2MComplexCircular1A(BaseNKModel):
b_set = models.ManyToManyField("M2MComplexCircular1B",
through="M2MCircular1ThroughAB")
b_set = models.ManyToManyField(
"M2MComplexCircular1B", through="M2MCircular1ThroughAB"
)
class M2MComplexCircular1B(BaseNKModel):
c_set = models.ManyToManyField("M2MComplexCircular1C",
through="M2MCircular1ThroughBC")
c_set = models.ManyToManyField(
"M2MComplexCircular1C", through="M2MCircular1ThroughBC"
)
class M2MComplexCircular1C(BaseNKModel):
a_set = models.ManyToManyField("M2MComplexCircular1A",
through="M2MCircular1ThroughCA")
a_set = models.ManyToManyField(
"M2MComplexCircular1A", through="M2MCircular1ThroughCA"
)
class M2MCircular1ThroughAB(BaseNKModel):
@@ -320,13 +331,15 @@ class M2MCircular1ThroughCA(BaseNKModel):
class M2MComplexCircular2A(BaseNKModel):
b_set = models.ManyToManyField("M2MComplexCircular2B",
through="M2MCircular2ThroughAB")
b_set = models.ManyToManyField(
"M2MComplexCircular2B", through="M2MCircular2ThroughAB"
)
class M2MComplexCircular2B(BaseNKModel):
def natural_key(self):
return (self.data,)
# Fake the dependency for a circularity
natural_key.dependencies = ["fixtures_regress.M2MComplexCircular2A"]

View File

@@ -11,30 +11,58 @@ from django.core.serializers.base import DeserializationError
from django.db import IntegrityError, transaction
from django.db.models import signals
from django.test import (
TestCase, TransactionTestCase, override_settings, skipIfDBFeature,
TestCase,
TransactionTestCase,
override_settings,
skipIfDBFeature,
skipUnlessDBFeature,
)
from .models import (
Absolute, Animal, Article, Book, Child, Circle1, Circle2, Circle3,
ExternalDependency, M2MCircular1ThroughAB, M2MCircular1ThroughBC,
M2MCircular1ThroughCA, M2MCircular2ThroughAB, M2MComplexA, M2MComplexB,
M2MComplexCircular1A, M2MComplexCircular1B, M2MComplexCircular1C,
M2MComplexCircular2A, M2MComplexCircular2B, M2MSimpleA, M2MSimpleB,
M2MSimpleCircularA, M2MSimpleCircularB, M2MThroughAB, NKChild, Parent,
Person, RefToNKChild, Store, Stuff, Thingy, Widget,
Absolute,
Animal,
Article,
Book,
Child,
Circle1,
Circle2,
Circle3,
ExternalDependency,
M2MCircular1ThroughAB,
M2MCircular1ThroughBC,
M2MCircular1ThroughCA,
M2MCircular2ThroughAB,
M2MComplexA,
M2MComplexB,
M2MComplexCircular1A,
M2MComplexCircular1B,
M2MComplexCircular1C,
M2MComplexCircular2A,
M2MComplexCircular2B,
M2MSimpleA,
M2MSimpleB,
M2MSimpleCircularA,
M2MSimpleCircularB,
M2MThroughAB,
NKChild,
Parent,
Person,
RefToNKChild,
Store,
Stuff,
Thingy,
Widget,
)
_cur_dir = os.path.dirname(os.path.abspath(__file__))
class TestFixtures(TestCase):
def animal_pre_save_check(self, signal, sender, instance, **kwargs):
self.pre_save_checks.append(
(
'Count = %s (%s)' % (instance.count, type(instance.count)),
'Weight = %s (%s)' % (instance.weight, type(instance.weight)),
"Count = %s (%s)" % (instance.count, type(instance.count)),
"Weight = %s (%s)" % (instance.weight, type(instance.weight)),
)
)
@@ -44,8 +72,8 @@ class TestFixtures(TestCase):
"""
# Load a fixture that uses PK=1
management.call_command(
'loaddata',
'sequence',
"loaddata",
"sequence",
verbosity=0,
)
@@ -53,8 +81,8 @@ class TestFixtures(TestCase):
# will take a PK of 1 (on Postgres), and the save will fail.
animal = Animal(
name='Platypus',
latin_name='Ornithorhynchus anatinus',
name="Platypus",
latin_name="Ornithorhynchus anatinus",
count=2,
weight=2.2,
)
@@ -69,8 +97,8 @@ class TestFixtures(TestCase):
"""
with self.assertRaises(DeserializationError):
management.call_command(
'loaddata',
'sequence_extra',
"loaddata",
"sequence_extra",
verbosity=0,
)
@@ -81,12 +109,12 @@ class TestFixtures(TestCase):
from the database.
"""
management.call_command(
'loaddata',
'sequence_extra',
"loaddata",
"sequence_extra",
ignore=True,
verbosity=0,
)
self.assertEqual(Animal.specimens.all()[0].name, 'Lion')
self.assertEqual(Animal.specimens.all()[0].name, "Lion")
def test_loaddata_not_found_fields_ignore_xml(self):
"""
@@ -94,14 +122,14 @@ class TestFixtures(TestCase):
for fields that have been removed from the model definition.
"""
management.call_command(
'loaddata',
'sequence_extra_xml',
"loaddata",
"sequence_extra_xml",
ignore=True,
verbosity=0,
)
self.assertEqual(Animal.specimens.all()[0].name, 'Wolf')
self.assertEqual(Animal.specimens.all()[0].name, "Wolf")
@skipIfDBFeature('interprets_empty_strings_as_nulls')
@skipIfDBFeature("interprets_empty_strings_as_nulls")
def test_pretty_print_xml(self):
"""
Regression test for ticket #4558 -- pretty printing of XML fixtures
@@ -109,14 +137,14 @@ class TestFixtures(TestCase):
"""
# Load a pretty-printed XML fixture with Nulls.
management.call_command(
'loaddata',
'pretty.xml',
"loaddata",
"pretty.xml",
verbosity=0,
)
self.assertIsNone(Stuff.objects.all()[0].name)
self.assertIsNone(Stuff.objects.all()[0].owner)
@skipUnlessDBFeature('interprets_empty_strings_as_nulls')
@skipUnlessDBFeature("interprets_empty_strings_as_nulls")
def test_pretty_print_xml_empty_strings(self):
"""
Regression test for ticket #4558 -- pretty printing of XML fixtures
@@ -124,11 +152,11 @@ class TestFixtures(TestCase):
"""
# Load a pretty-printed XML fixture with Nulls.
management.call_command(
'loaddata',
'pretty.xml',
"loaddata",
"pretty.xml",
verbosity=0,
)
self.assertEqual(Stuff.objects.all()[0].name, '')
self.assertEqual(Stuff.objects.all()[0].name, "")
self.assertIsNone(Stuff.objects.all()[0].owner)
def test_absolute_path(self):
@@ -141,24 +169,22 @@ class TestFixtures(TestCase):
fixture directory.
"""
load_absolute_path = os.path.join(
os.path.dirname(__file__),
'fixtures',
'absolute.json'
os.path.dirname(__file__), "fixtures", "absolute.json"
)
management.call_command(
'loaddata',
"loaddata",
load_absolute_path,
verbosity=0,
)
self.assertEqual(Absolute.objects.count(), 1)
def test_relative_path(self, path=['fixtures', 'absolute.json']):
def test_relative_path(self, path=["fixtures", "absolute.json"]):
relative_path = os.path.join(*path)
cwd = os.getcwd()
try:
os.chdir(_cur_dir)
management.call_command(
'loaddata',
"loaddata",
relative_path,
verbosity=0,
)
@@ -166,14 +192,14 @@ class TestFixtures(TestCase):
os.chdir(cwd)
self.assertEqual(Absolute.objects.count(), 1)
@override_settings(FIXTURE_DIRS=[os.path.join(_cur_dir, 'fixtures_1')])
@override_settings(FIXTURE_DIRS=[os.path.join(_cur_dir, "fixtures_1")])
def test_relative_path_in_fixture_dirs(self):
self.test_relative_path(path=['inner', 'absolute.json'])
self.test_relative_path(path=["inner", "absolute.json"])
def test_path_containing_dots(self):
management.call_command(
'loaddata',
'path.containing.dots.json',
"loaddata",
"path.containing.dots.json",
verbosity=0,
)
self.assertEqual(Absolute.objects.count(), 1)
@@ -186,20 +212,20 @@ class TestFixtures(TestCase):
msg = "Problem installing fixture 'bad_fix.ture1': unkn is not a known serialization format."
with self.assertRaisesMessage(management.CommandError, msg):
management.call_command(
'loaddata',
'bad_fix.ture1.unkn',
"loaddata",
"bad_fix.ture1.unkn",
verbosity=0,
)
@override_settings(SERIALIZATION_MODULES={'unkn': 'unexistent.path'})
@override_settings(SERIALIZATION_MODULES={"unkn": "unexistent.path"})
def test_unimportable_serializer(self):
"""
Failing serializer import raises the proper error
"""
with self.assertRaisesMessage(ImportError, "No module named 'unexistent'"):
management.call_command(
'loaddata',
'bad_fix.ture1.unkn',
"loaddata",
"bad_fix.ture1.unkn",
verbosity=0,
)
@@ -212,8 +238,8 @@ class TestFixtures(TestCase):
msg = "No fixture data found for 'bad_fixture2'. (File format may be invalid.)"
with self.assertWarnsMessage(RuntimeWarning, msg):
management.call_command(
'loaddata',
'bad_fixture2.xml',
"loaddata",
"bad_fixture2.xml",
verbosity=0,
)
@@ -226,8 +252,8 @@ class TestFixtures(TestCase):
msg = "No fixture data found for 'bad_fixture2'. (File format may be invalid.)"
with self.assertWarnsMessage(RuntimeWarning, msg):
management.call_command(
'loaddata',
'bad_fixture2',
"loaddata",
"bad_fixture2",
verbosity=0,
)
@@ -239,8 +265,8 @@ class TestFixtures(TestCase):
msg = "No fixture data found for 'empty'. (File format may be invalid.)"
with self.assertWarnsMessage(RuntimeWarning, msg):
management.call_command(
'loaddata',
'empty',
"loaddata",
"empty",
verbosity=0,
)
@@ -252,9 +278,9 @@ class TestFixtures(TestCase):
msg = "No fixture data found for 'bad_fixture2'. (File format may be invalid.)"
with self.assertWarnsMessage(RuntimeWarning, msg):
management.call_command(
'loaddata',
'bad_fixture2',
'animal',
"loaddata",
"bad_fixture2",
"animal",
verbosity=0,
)
@@ -265,8 +291,8 @@ class TestFixtures(TestCase):
(since they are treated individually).
"""
management.call_command(
'loaddata',
'model-inheritance.json',
"loaddata",
"model-inheritance.json",
verbosity=0,
)
self.assertEqual(Parent.objects.all()[0].id, 1)
@@ -281,21 +307,19 @@ class TestFixtures(TestCase):
issued.
"""
management.call_command(
'loaddata',
'big-fixture.json',
"loaddata",
"big-fixture.json",
verbosity=0,
)
articles = Article.objects.exclude(id=9)
self.assertEqual(
list(articles.values_list('id', flat=True)),
[1, 2, 3, 4, 5, 6, 7, 8]
list(articles.values_list("id", flat=True)), [1, 2, 3, 4, 5, 6, 7, 8]
)
# Just for good measure, run the same query again.
# Under the influence of ticket #7572, this will
# give a different result to the previous call.
self.assertEqual(
list(articles.values_list('id', flat=True)),
[1, 2, 3, 4, 5, 6, 7, 8]
list(articles.values_list("id", flat=True)), [1, 2, 3, 4, 5, 6, 7, 8]
)
def test_field_value_coerce(self):
@@ -307,16 +331,13 @@ class TestFixtures(TestCase):
signals.pre_save.connect(self.animal_pre_save_check)
try:
management.call_command(
'loaddata',
'animal.xml',
"loaddata",
"animal.xml",
verbosity=0,
)
self.assertEqual(
self.pre_save_checks,
[
("Count = 42 (<class 'int'>)",
"Weight = 1.2 (<class 'float'>)")
]
[("Count = 42 (<class 'int'>)", "Weight = 1.2 (<class 'float'>)")],
)
finally:
signals.pre_save.disconnect(self.animal_pre_save_check)
@@ -328,18 +349,18 @@ class TestFixtures(TestCase):
the database as a JSON fixture
"""
management.call_command(
'loaddata',
'animal.xml',
"loaddata",
"animal.xml",
verbosity=0,
)
management.call_command(
'loaddata',
'sequence.json',
"loaddata",
"sequence.json",
verbosity=0,
)
animal = Animal(
name='Platypus',
latin_name='Ornithorhynchus anatinus',
name="Platypus",
latin_name="Ornithorhynchus anatinus",
count=2,
weight=2.2,
)
@@ -347,9 +368,9 @@ class TestFixtures(TestCase):
out = StringIO()
management.call_command(
'dumpdata',
'fixtures_regress.animal',
format='json',
"dumpdata",
"fixtures_regress.animal",
format="json",
stdout=out,
)
@@ -358,22 +379,43 @@ class TestFixtures(TestCase):
# Get rid of artifacts like '000000002' to eliminate the differences
# between different Python versions.
data = re.sub('0{6,}[0-9]', '', data)
data = re.sub("0{6,}[0-9]", "", data)
animals_data = sorted([
{
"pk": 1, "model": "fixtures_regress.animal",
"fields": {"count": 3, "weight": 1.2, "name": "Lion", "latin_name": "Panthera leo"}
},
{
"pk": 10, "model": "fixtures_regress.animal",
"fields": {"count": 42, "weight": 1.2, "name": "Emu", "latin_name": "Dromaius novaehollandiae"}
},
{
"pk": animal.pk, "model": "fixtures_regress.animal",
"fields": {"count": 2, "weight": 2.2, "name": "Platypus", "latin_name": "Ornithorhynchus anatinus"}
},
], key=lambda x: x["pk"])
animals_data = sorted(
[
{
"pk": 1,
"model": "fixtures_regress.animal",
"fields": {
"count": 3,
"weight": 1.2,
"name": "Lion",
"latin_name": "Panthera leo",
},
},
{
"pk": 10,
"model": "fixtures_regress.animal",
"fields": {
"count": 42,
"weight": 1.2,
"name": "Emu",
"latin_name": "Dromaius novaehollandiae",
},
},
{
"pk": animal.pk,
"model": "fixtures_regress.animal",
"fields": {
"count": 2,
"weight": 2.2,
"name": "Platypus",
"latin_name": "Ornithorhynchus anatinus",
},
},
],
key=lambda x: x["pk"],
)
data = sorted(json.loads(data), key=lambda x: x["pk"])
@@ -386,28 +428,28 @@ class TestFixtures(TestCase):
"""
out = StringIO()
# Create an instance of the concrete class
widget = Widget.objects.create(name='grommet')
widget = Widget.objects.create(name="grommet")
management.call_command(
'dumpdata',
'fixtures_regress.widget',
'fixtures_regress.widgetproxy',
format='json',
"dumpdata",
"fixtures_regress.widget",
"fixtures_regress.widgetproxy",
format="json",
stdout=out,
)
self.assertJSONEqual(
out.getvalue(),
"""[{"pk": %d, "model": "fixtures_regress.widget", "fields": {"name": "grommet"}}]"""
% widget.pk
% widget.pk,
)
@skipUnlessDBFeature('supports_forward_references')
@skipUnlessDBFeature("supports_forward_references")
def test_loaddata_works_when_fixture_has_forward_refs(self):
"""
Regression for #3615 - Forward references cause fixtures not to load in MySQL (InnoDB)
"""
management.call_command(
'loaddata',
'forward_ref.json',
"loaddata",
"forward_ref.json",
verbosity=0,
)
self.assertEqual(Book.objects.all()[0].id, 1)
@@ -419,23 +461,27 @@ class TestFixtures(TestCase):
"""
with self.assertRaisesMessage(IntegrityError, "Problem installing fixture"):
management.call_command(
'loaddata',
'forward_ref_bad_data.json',
"loaddata",
"forward_ref_bad_data.json",
verbosity=0,
)
@skipUnlessDBFeature('supports_forward_references')
@override_settings(FIXTURE_DIRS=[os.path.join(_cur_dir, 'fixtures_1'),
os.path.join(_cur_dir, 'fixtures_2')])
@skipUnlessDBFeature("supports_forward_references")
@override_settings(
FIXTURE_DIRS=[
os.path.join(_cur_dir, "fixtures_1"),
os.path.join(_cur_dir, "fixtures_2"),
]
)
def test_loaddata_forward_refs_split_fixtures(self):
"""
Regression for #17530 - should be able to cope with forward references
when the fixtures are not in the same files or directories.
"""
management.call_command(
'loaddata',
'forward_ref_1.json',
'forward_ref_2.json',
"loaddata",
"forward_ref_1.json",
"forward_ref_2.json",
verbosity=0,
)
self.assertEqual(Book.objects.all()[0].id, 1)
@@ -448,7 +494,7 @@ class TestFixtures(TestCase):
msg = "No database fixture specified. Please provide the path of at least one fixture in the command line."
with self.assertRaisesMessage(management.CommandError, msg):
management.call_command(
'loaddata',
"loaddata",
verbosity=0,
)
@@ -458,8 +504,8 @@ class TestFixtures(TestCase):
from a model with a M2M shouldn't blow up.
"""
management.call_command(
'loaddata',
'special-article.json',
"loaddata",
"special-article.json",
verbosity=0,
)
@@ -470,8 +516,8 @@ class TestFixtures(TestCase):
blow up.
"""
management.call_command(
'loaddata',
'feature.json',
"loaddata",
"feature.json",
verbosity=0,
)
@@ -480,22 +526,28 @@ class TestFixtures(TestCase):
Regression test for ticket #17946.
"""
management.call_command(
'loaddata',
'm2mtoself.json',
"loaddata",
"m2mtoself.json",
verbosity=0,
)
@override_settings(FIXTURE_DIRS=[os.path.join(_cur_dir, 'fixtures_1'),
os.path.join(_cur_dir, 'fixtures_1')])
@override_settings(
FIXTURE_DIRS=[
os.path.join(_cur_dir, "fixtures_1"),
os.path.join(_cur_dir, "fixtures_1"),
]
)
def test_fixture_dirs_with_duplicates(self):
"""
settings.FIXTURE_DIRS cannot contain duplicates in order to avoid
repeated fixture loading.
"""
with self.assertRaisesMessage(ImproperlyConfigured, "settings.FIXTURE_DIRS contains duplicates."):
management.call_command('loaddata', 'absolute.json', verbosity=0)
with self.assertRaisesMessage(
ImproperlyConfigured, "settings.FIXTURE_DIRS contains duplicates."
):
management.call_command("loaddata", "absolute.json", verbosity=0)
@override_settings(FIXTURE_DIRS=[os.path.join(_cur_dir, 'fixtures')])
@override_settings(FIXTURE_DIRS=[os.path.join(_cur_dir, "fixtures")])
def test_fixture_dirs_with_default_fixture_path(self):
"""
settings.FIXTURE_DIRS cannot contain a default fixtures directory
@@ -504,52 +556,49 @@ class TestFixtures(TestCase):
msg = (
"'%s' is a default fixture directory for the '%s' app "
"and cannot be listed in settings.FIXTURE_DIRS."
% (os.path.join(_cur_dir, 'fixtures'), 'fixtures_regress')
% (os.path.join(_cur_dir, "fixtures"), "fixtures_regress")
)
with self.assertRaisesMessage(ImproperlyConfigured, msg):
management.call_command('loaddata', 'absolute.json', verbosity=0)
management.call_command("loaddata", "absolute.json", verbosity=0)
@override_settings(FIXTURE_DIRS=[os.path.join(_cur_dir, 'fixtures_1'),
os.path.join(_cur_dir, 'fixtures_2')])
@override_settings(
FIXTURE_DIRS=[
os.path.join(_cur_dir, "fixtures_1"),
os.path.join(_cur_dir, "fixtures_2"),
]
)
def test_loaddata_with_valid_fixture_dirs(self):
management.call_command(
'loaddata',
'absolute.json',
"loaddata",
"absolute.json",
verbosity=0,
)
@override_settings(FIXTURE_DIRS=[Path(_cur_dir) / 'fixtures_1'])
@override_settings(FIXTURE_DIRS=[Path(_cur_dir) / "fixtures_1"])
def test_fixtures_dir_pathlib(self):
management.call_command('loaddata', 'inner/absolute.json', verbosity=0)
management.call_command("loaddata", "inner/absolute.json", verbosity=0)
self.assertQuerysetEqual(Absolute.objects.all(), [1], transform=lambda o: o.pk)
class NaturalKeyFixtureTests(TestCase):
def test_nk_deserialize(self):
"""
Test for ticket #13030 - Python based parser version
natural keys deserialize with fk to inheriting model
"""
management.call_command(
'loaddata',
'model-inheritance.json',
"loaddata",
"model-inheritance.json",
verbosity=0,
)
management.call_command(
'loaddata',
'nk-inheritance.json',
"loaddata",
"nk-inheritance.json",
verbosity=0,
)
self.assertEqual(
NKChild.objects.get(pk=1).data,
'apple'
)
self.assertEqual(NKChild.objects.get(pk=1).data, "apple")
self.assertEqual(
RefToNKChild.objects.get(pk=1).nk_fk.data,
'apple'
)
self.assertEqual(RefToNKChild.objects.get(pk=1).nk_fk.data, "apple")
def test_nk_deserialize_xml(self):
"""
@@ -557,47 +606,41 @@ class NaturalKeyFixtureTests(TestCase):
natural keys deserialize with fk to inheriting model
"""
management.call_command(
'loaddata',
'model-inheritance.json',
"loaddata",
"model-inheritance.json",
verbosity=0,
)
management.call_command(
'loaddata',
'nk-inheritance.json',
"loaddata",
"nk-inheritance.json",
verbosity=0,
)
management.call_command(
'loaddata',
'nk-inheritance2.xml',
"loaddata",
"nk-inheritance2.xml",
verbosity=0,
)
self.assertEqual(
NKChild.objects.get(pk=2).data,
'banana'
)
self.assertEqual(
RefToNKChild.objects.get(pk=2).nk_fk.data,
'apple'
)
self.assertEqual(NKChild.objects.get(pk=2).data, "banana")
self.assertEqual(RefToNKChild.objects.get(pk=2).nk_fk.data, "apple")
def test_nk_on_serialize(self):
"""
Natural key requirements are taken into account when serializing models.
"""
management.call_command(
'loaddata',
'forward_ref_lookup.json',
"loaddata",
"forward_ref_lookup.json",
verbosity=0,
)
out = StringIO()
management.call_command(
'dumpdata',
'fixtures_regress.book',
'fixtures_regress.person',
'fixtures_regress.store',
"dumpdata",
"fixtures_regress.book",
"fixtures_regress.person",
"fixtures_regress.store",
verbosity=0,
format='json',
format="json",
use_natural_foreign_keys=True,
use_natural_primary_keys=True,
stdout=out,
@@ -610,7 +653,7 @@ class NaturalKeyFixtureTests(TestCase):
{"fields": {"name": "Neal Stephenson"}, "model": "fixtures_regress.person"},
{"pk": 1, "model": "fixtures_regress.book", "fields": {"stores": [["Amazon"], ["Borders"]],
"name": "Cryptonomicon", "author": ["Neal Stephenson"]}}]
"""
""",
)
def test_dependency_sorting(self):
@@ -619,131 +662,114 @@ class NaturalKeyFixtureTests(TestCase):
serialized before then Person, and both must be serialized before Book.
"""
sorted_deps = serializers.sort_dependencies(
[('fixtures_regress', [Book, Person, Store])]
)
self.assertEqual(
sorted_deps,
[Store, Person, Book]
[("fixtures_regress", [Book, Person, Store])]
)
self.assertEqual(sorted_deps, [Store, Person, Book])
def test_dependency_sorting_2(self):
sorted_deps = serializers.sort_dependencies(
[('fixtures_regress', [Book, Store, Person])]
)
self.assertEqual(
sorted_deps,
[Store, Person, Book]
[("fixtures_regress", [Book, Store, Person])]
)
self.assertEqual(sorted_deps, [Store, Person, Book])
def test_dependency_sorting_3(self):
sorted_deps = serializers.sort_dependencies(
[('fixtures_regress', [Store, Book, Person])]
)
self.assertEqual(
sorted_deps,
[Store, Person, Book]
[("fixtures_regress", [Store, Book, Person])]
)
self.assertEqual(sorted_deps, [Store, Person, Book])
def test_dependency_sorting_4(self):
sorted_deps = serializers.sort_dependencies(
[('fixtures_regress', [Store, Person, Book])]
)
self.assertEqual(
sorted_deps,
[Store, Person, Book]
[("fixtures_regress", [Store, Person, Book])]
)
self.assertEqual(sorted_deps, [Store, Person, Book])
def test_dependency_sorting_5(self):
sorted_deps = serializers.sort_dependencies(
[('fixtures_regress', [Person, Book, Store])]
)
self.assertEqual(
sorted_deps,
[Store, Person, Book]
[("fixtures_regress", [Person, Book, Store])]
)
self.assertEqual(sorted_deps, [Store, Person, Book])
def test_dependency_sorting_6(self):
sorted_deps = serializers.sort_dependencies(
[('fixtures_regress', [Person, Store, Book])]
)
self.assertEqual(
sorted_deps,
[Store, Person, Book]
[("fixtures_regress", [Person, Store, Book])]
)
self.assertEqual(sorted_deps, [Store, Person, Book])
def test_dependency_sorting_dangling(self):
sorted_deps = serializers.sort_dependencies(
[('fixtures_regress', [Person, Circle1, Store, Book])]
)
self.assertEqual(
sorted_deps,
[Circle1, Store, Person, Book]
[("fixtures_regress", [Person, Circle1, Store, Book])]
)
self.assertEqual(sorted_deps, [Circle1, Store, Person, Book])
def test_dependency_sorting_tight_circular(self):
with self.assertRaisesMessage(
RuntimeError,
"Can't resolve dependencies for fixtures_regress.Circle1, "
"fixtures_regress.Circle2 in serialized app list."
"fixtures_regress.Circle2 in serialized app list.",
):
serializers.sort_dependencies([('fixtures_regress', [Person, Circle2, Circle1, Store, Book])])
serializers.sort_dependencies(
[("fixtures_regress", [Person, Circle2, Circle1, Store, Book])]
)
def test_dependency_sorting_tight_circular_2(self):
with self.assertRaisesMessage(
RuntimeError,
"Can't resolve dependencies for fixtures_regress.Circle1, "
"fixtures_regress.Circle2 in serialized app list."
"fixtures_regress.Circle2 in serialized app list.",
):
serializers.sort_dependencies([('fixtures_regress', [Circle1, Book, Circle2])])
serializers.sort_dependencies(
[("fixtures_regress", [Circle1, Book, Circle2])]
)
def test_dependency_self_referential(self):
with self.assertRaisesMessage(
RuntimeError,
"Can't resolve dependencies for fixtures_regress.Circle3 in "
"serialized app list."
"serialized app list.",
):
serializers.sort_dependencies([('fixtures_regress', [Book, Circle3])])
serializers.sort_dependencies([("fixtures_regress", [Book, Circle3])])
def test_dependency_sorting_long(self):
with self.assertRaisesMessage(
RuntimeError,
"Can't resolve dependencies for fixtures_regress.Circle1, "
"fixtures_regress.Circle2, fixtures_regress.Circle3 in serialized "
"app list."
"app list.",
):
serializers.sort_dependencies([('fixtures_regress', [Person, Circle2, Circle1, Circle3, Store, Book])])
serializers.sort_dependencies(
[("fixtures_regress", [Person, Circle2, Circle1, Circle3, Store, Book])]
)
def test_dependency_sorting_normal(self):
sorted_deps = serializers.sort_dependencies(
[('fixtures_regress', [Person, ExternalDependency, Book])]
)
self.assertEqual(
sorted_deps,
[Person, Book, ExternalDependency]
[("fixtures_regress", [Person, ExternalDependency, Book])]
)
self.assertEqual(sorted_deps, [Person, Book, ExternalDependency])
def test_normal_pk(self):
"""
Normal primary keys work on a model with natural key capabilities.
"""
management.call_command(
'loaddata',
'non_natural_1.json',
"loaddata",
"non_natural_1.json",
verbosity=0,
)
management.call_command(
'loaddata',
'forward_ref_lookup.json',
"loaddata",
"forward_ref_lookup.json",
verbosity=0,
)
management.call_command(
'loaddata',
'non_natural_2.xml',
"loaddata",
"non_natural_2.xml",
verbosity=0,
)
books = Book.objects.all()
self.assertQuerysetEqual(
books, [
books,
[
"<Book: Cryptonomicon by Neal Stephenson (available at Amazon, Borders)>",
"<Book: Ender's Game by Orson Scott Card (available at Collins Bookstore)>",
"<Book: Permutation City by Greg Egan (available at Angus and Robertson)>",
@@ -764,7 +790,7 @@ class M2MNaturalKeyFixtureTests(TestCase):
altogether.
"""
sorted_deps = serializers.sort_dependencies(
[('fixtures_regress', [M2MSimpleA, M2MSimpleB])]
[("fixtures_regress", [M2MSimpleA, M2MSimpleB])]
)
self.assertEqual(sorted_deps, [M2MSimpleB, M2MSimpleA])
@@ -776,9 +802,11 @@ class M2MNaturalKeyFixtureTests(TestCase):
with self.assertRaisesMessage(
RuntimeError,
"Can't resolve dependencies for fixtures_regress.M2MSimpleCircularA, "
"fixtures_regress.M2MSimpleCircularB in serialized app list."
"fixtures_regress.M2MSimpleCircularB in serialized app list.",
):
serializers.sort_dependencies([('fixtures_regress', [M2MSimpleCircularA, M2MSimpleCircularB])])
serializers.sort_dependencies(
[("fixtures_regress", [M2MSimpleCircularA, M2MSimpleCircularB])]
)
def test_dependency_sorting_m2m_complex(self):
"""
@@ -786,7 +814,7 @@ class M2MNaturalKeyFixtureTests(TestCase):
dependencies. The through model itself will have dependencies, though.
"""
sorted_deps = serializers.sort_dependencies(
[('fixtures_regress', [M2MComplexA, M2MComplexB, M2MThroughAB])]
[("fixtures_regress", [M2MComplexA, M2MComplexB, M2MThroughAB])]
)
# Order between M2MComplexA and M2MComplexB doesn't matter. The through
# model has dependencies to them though, so it should come last.
@@ -796,11 +824,16 @@ class M2MNaturalKeyFixtureTests(TestCase):
"""
Circular M2M relations with explicit through models should be serializable
"""
A, B, C, AtoB, BtoC, CtoA = (M2MComplexCircular1A, M2MComplexCircular1B,
M2MComplexCircular1C, M2MCircular1ThroughAB,
M2MCircular1ThroughBC, M2MCircular1ThroughCA)
A, B, C, AtoB, BtoC, CtoA = (
M2MComplexCircular1A,
M2MComplexCircular1B,
M2MComplexCircular1C,
M2MCircular1ThroughAB,
M2MCircular1ThroughBC,
M2MCircular1ThroughCA,
)
sorted_deps = serializers.sort_dependencies(
[('fixtures_regress', [A, B, C, AtoB, BtoC, CtoA])]
[("fixtures_regress", [A, B, C, AtoB, BtoC, CtoA])]
)
# The dependency sorting should not result in an error, and the
# through model should have dependencies to the other models and as
@@ -813,9 +846,14 @@ class M2MNaturalKeyFixtureTests(TestCase):
Circular M2M relations with explicit through models should be serializable
This test tests the circularity with explicit natural_key.dependencies
"""
sorted_deps = serializers.sort_dependencies([
('fixtures_regress', [M2MComplexCircular2A, M2MComplexCircular2B, M2MCircular2ThroughAB])
])
sorted_deps = serializers.sort_dependencies(
[
(
"fixtures_regress",
[M2MComplexCircular2A, M2MComplexCircular2B, M2MCircular2ThroughAB],
)
]
)
self.assertEqual(sorted_deps[:2], [M2MComplexCircular2A, M2MComplexCircular2B])
self.assertEqual(sorted_deps[2:], [M2MCircular2ThroughAB])
@@ -831,9 +869,9 @@ class M2MNaturalKeyFixtureTests(TestCase):
out = StringIO()
management.call_command(
'dumpdata',
'fixtures_regress.M2MSimpleA',
'fixtures_regress.M2MSimpleB',
"dumpdata",
"fixtures_regress.M2MSimpleA",
"fixtures_regress.M2MSimpleB",
use_natural_foreign_keys=True,
stdout=out,
)
@@ -851,15 +889,15 @@ class M2MNaturalKeyFixtureTests(TestCase):
class TestTicket11101(TransactionTestCase):
available_apps = ['fixtures_regress']
available_apps = ["fixtures_regress"]
@skipUnlessDBFeature('supports_transactions')
@skipUnlessDBFeature("supports_transactions")
def test_ticket_11101(self):
"""Fixtures can be rolled back (ticket #11101)."""
with transaction.atomic():
management.call_command(
'loaddata',
'thingy.json',
"loaddata",
"thingy.json",
verbosity=0,
)
self.assertEqual(Thingy.objects.count(), 1)
@@ -872,13 +910,14 @@ class TestLoadFixtureFromOtherAppDirectory(TestCase):
#23612 -- fixtures path should be normalized to allow referencing relative
paths on Windows.
"""
current_dir = os.path.abspath(os.path.dirname(__file__))
# relative_prefix is something like tests/fixtures_regress or
# fixtures_regress depending on how runtests.py is invoked.
# All path separators must be / in order to be a proper regression test on
# Windows, so replace as appropriate.
relative_prefix = os.path.relpath(current_dir, os.getcwd()).replace('\\', '/')
fixtures = [relative_prefix + '/fixtures/absolute.json']
relative_prefix = os.path.relpath(current_dir, os.getcwd()).replace("\\", "/")
fixtures = [relative_prefix + "/fixtures/absolute.json"]
def test_fixtures_loaded(self):
count = Absolute.objects.count()