Refs #31395 -- Relied on setUpTestData() test data isolation in various tests.

This commit is contained in:
Simon Charette 2018-11-23 21:24:25 -05:00 committed by Mariusz Felisiak
parent 3cf80d3fcf
commit 94f63b926f
14 changed files with 187 additions and 163 deletions

View File

@ -15,19 +15,22 @@ from .models import Article, ArticleProxy, Site
@override_settings(ROOT_URLCONF='admin_utils.urls') @override_settings(ROOT_URLCONF='admin_utils.urls')
class LogEntryTests(TestCase): class LogEntryTests(TestCase):
def setUp(self): @classmethod
self.user = User.objects.create_superuser(username='super', password='secret', email='super@example.com') def setUpTestData(cls):
self.site = Site.objects.create(domain='example.org') cls.user = User.objects.create_superuser(username='super', password='secret', email='super@example.com')
self.a1 = Article.objects.create( cls.site = Site.objects.create(domain='example.org')
site=self.site, cls.a1 = Article.objects.create(
site=cls.site,
title="Title", title="Title",
created=datetime(2008, 3, 12, 11, 54), created=datetime(2008, 3, 12, 11, 54),
) )
content_type_pk = ContentType.objects.get_for_model(Article).pk content_type_pk = ContentType.objects.get_for_model(Article).pk
LogEntry.objects.log_action( LogEntry.objects.log_action(
self.user.pk, content_type_pk, self.a1.pk, repr(self.a1), CHANGE, cls.user.pk, content_type_pk, cls.a1.pk, repr(cls.a1), CHANGE,
change_message='Changed something' change_message='Changed something'
) )
def setUp(self):
self.client.force_login(self.user) self.client.force_login(self.user)
def test_logentry_save(self): def test_logentry_save(self):

View File

@ -22,9 +22,10 @@ class NestedObjectsTests(TestCase):
""" """
Tests for ``NestedObject`` utility collection. Tests for ``NestedObject`` utility collection.
""" """
def setUp(self): @classmethod
self.n = NestedObjects(using=DEFAULT_DB_ALIAS) def setUpTestData(cls):
self.objs = [Count.objects.create(num=i) for i in range(5)] cls.n = NestedObjects(using=DEFAULT_DB_ALIAS)
cls.objs = [Count.objects.create(num=i) for i in range(5)]
def _check(self, target): def _check(self, target):
self.assertEqual(self.n.nested(lambda obj: obj.num), target) self.assertEqual(self.n.nested(lambda obj: obj.num), target)

View File

@ -6,8 +6,11 @@ from django.test import TestCase
class TestAuthenticationMiddleware(TestCase): class TestAuthenticationMiddleware(TestCase):
@classmethod
def setUpTestData(cls):
cls.user = User.objects.create_user('test_user', 'test@example.com', 'test_password')
def setUp(self): def setUp(self):
self.user = User.objects.create_user('test_user', 'test@example.com', 'test_password')
self.middleware = AuthenticationMiddleware(lambda req: HttpResponse()) self.middleware = AuthenticationMiddleware(lambda req: HttpResponse())
self.client.force_login(self.user) self.client.force_login(self.user)
self.request = HttpRequest() self.request = HttpRequest()

View File

@ -20,9 +20,12 @@ class RemoveStaleContentTypesTests(TestCase):
'django.contrib.contenttypes', 'django.contrib.contenttypes',
] ]
@classmethod
def setUpTestData(cls):
cls.before_count = ContentType.objects.count()
cls.content_type = ContentType.objects.create(app_label='contenttypes_tests', model='Fake')
def setUp(self): def setUp(self):
self.before_count = ContentType.objects.count()
self.content_type = ContentType.objects.create(app_label='contenttypes_tests', model='Fake')
self.app_config = apps.get_app_config('contenttypes_tests') self.app_config = apps.get_app_config('contenttypes_tests')
def test_interactive_true_with_dependent_objects(self): def test_interactive_true_with_dependent_objects(self):

View File

@ -13,25 +13,26 @@ from .models import (
class GenericRelationsTests(TestCase): class GenericRelationsTests(TestCase):
def setUp(self): @classmethod
self.lion = Animal.objects.create( def setUpTestData(cls):
common_name="Lion", latin_name="Panthera leo") cls.lion = Animal.objects.create(common_name='Lion', latin_name='Panthera leo')
self.platypus = Animal.objects.create( cls.platypus = Animal.objects.create(
common_name="Platypus", latin_name="Ornithorhynchus anatinus") common_name='Platypus',
latin_name='Ornithorhynchus anatinus',
)
Vegetable.objects.create(name="Eggplant", is_yucky=True) Vegetable.objects.create(name="Eggplant", is_yucky=True)
self.bacon = Vegetable.objects.create(name="Bacon", is_yucky=False) cls.bacon = Vegetable.objects.create(name='Bacon', is_yucky=False)
self.quartz = Mineral.objects.create(name="Quartz", hardness=7) cls.quartz = Mineral.objects.create(name='Quartz', hardness=7)
# Tagging stuff. # Tagging stuff.
self.bacon.tags.create(tag="fatty") cls.bacon.tags.create(tag='fatty')
self.bacon.tags.create(tag="salty") cls.bacon.tags.create(tag='salty')
self.lion.tags.create(tag="yellow") cls.lion.tags.create(tag='yellow')
self.lion.tags.create(tag="hairy") cls.lion.tags.create(tag='hairy')
def comp_func(self, obj):
# Original list of tags: # Original list of tags:
self.comp_func = lambda obj: ( return obj.tag, obj.content_type.model_class(), obj.object_id
obj.tag, obj.content_type.model_class(), obj.object_id
)
def test_generic_update_or_create_when_created(self): def test_generic_update_or_create_when_created(self):
""" """

View File

@ -10,24 +10,25 @@ from .models import (
class ManyToManyTests(TestCase): class ManyToManyTests(TestCase):
def setUp(self): @classmethod
def setUpTestData(cls):
# Create a couple of Publications. # Create a couple of Publications.
self.p1 = Publication.objects.create(title='The Python Journal') cls.p1 = Publication.objects.create(title='The Python Journal')
self.p2 = Publication.objects.create(title='Science News') cls.p2 = Publication.objects.create(title='Science News')
self.p3 = Publication.objects.create(title='Science Weekly') cls.p3 = Publication.objects.create(title='Science Weekly')
self.p4 = Publication.objects.create(title='Highlights for Children') cls.p4 = Publication.objects.create(title='Highlights for Children')
self.a1 = Article.objects.create(headline='Django lets you build Web apps easily') cls.a1 = Article.objects.create(headline='Django lets you build Web apps easily')
self.a1.publications.add(self.p1) cls.a1.publications.add(cls.p1)
self.a2 = Article.objects.create(headline='NASA uses Python') cls.a2 = Article.objects.create(headline='NASA uses Python')
self.a2.publications.add(self.p1, self.p2, self.p3, self.p4) cls.a2.publications.add(cls.p1, cls.p2, cls.p3, cls.p4)
self.a3 = Article.objects.create(headline='NASA finds intelligent life on Earth') cls.a3 = Article.objects.create(headline='NASA finds intelligent life on Earth')
self.a3.publications.add(self.p2) cls.a3.publications.add(cls.p2)
self.a4 = Article.objects.create(headline='Oxygen-free diet works wonders') cls.a4 = Article.objects.create(headline='Oxygen-free diet works wonders')
self.a4.publications.add(self.p2) cls.a4.publications.add(cls.p2)
def test_add(self): def test_add(self):
# Create an Article. # Create an Article.

View File

@ -14,15 +14,16 @@ from .models import (
class ManyToOneTests(TestCase): class ManyToOneTests(TestCase):
def setUp(self): @classmethod
def setUpTestData(cls):
# Create a few Reporters. # Create a few Reporters.
self.r = Reporter(first_name='John', last_name='Smith', email='john@example.com') cls.r = Reporter(first_name='John', last_name='Smith', email='john@example.com')
self.r.save() cls.r.save()
self.r2 = Reporter(first_name='Paul', last_name='Jones', email='paul@example.com') cls.r2 = Reporter(first_name='Paul', last_name='Jones', email='paul@example.com')
self.r2.save() cls.r2.save()
# Create an Article. # Create an Article.
self.a = Article(headline="This is a test", pub_date=datetime.date(2005, 7, 27), reporter=self.r) cls.a = Article(headline='This is a test', pub_date=datetime.date(2005, 7, 27), reporter=cls.r)
self.a.save() cls.a.save()
def test_get(self): def test_get(self):
# Article objects have access to their related Reporter objects. # Article objects have access to their related Reporter objects.

View File

@ -4,22 +4,23 @@ from .models import Article, Car, Driver, Reporter
class ManyToOneNullTests(TestCase): class ManyToOneNullTests(TestCase):
def setUp(self): @classmethod
def setUpTestData(cls):
# Create a Reporter. # Create a Reporter.
self.r = Reporter(name='John Smith') cls.r = Reporter(name='John Smith')
self.r.save() cls.r.save()
# Create an Article. # Create an Article.
self.a = Article(headline="First", reporter=self.r) cls.a = Article(headline='First', reporter=cls.r)
self.a.save() cls.a.save()
# Create an Article via the Reporter object. # Create an Article via the Reporter object.
self.a2 = self.r.article_set.create(headline="Second") cls.a2 = cls.r.article_set.create(headline='Second')
# Create an Article with no Reporter by passing "reporter=None". # Create an Article with no Reporter by passing "reporter=None".
self.a3 = Article(headline="Third", reporter=None) cls.a3 = Article(headline='Third', reporter=None)
self.a3.save() cls.a3.save()
# Create another article and reporter # Create another article and reporter
self.r2 = Reporter(name='Paul Jones') cls.r2 = Reporter(name='Paul Jones')
self.r2.save() cls.r2.save()
self.a4 = self.r2.article_set.create(headline='Fourth') cls.a4 = cls.r2.article_set.create(headline='Fourth')
def test_get_related(self): def test_get_related(self):
self.assertEqual(self.a.reporter.id, self.r.id) self.assertEqual(self.a.reporter.id, self.r.id)

View File

@ -35,12 +35,15 @@ request.user = MockSuperUser()
class ModelAdminTests(TestCase): class ModelAdminTests(TestCase):
def setUp(self): @classmethod
self.band = Band.objects.create( def setUpTestData(cls):
cls.band = Band.objects.create(
name='The Doors', name='The Doors',
bio='', bio='',
sign_date=date(1965, 1, 1), sign_date=date(1965, 1, 1),
) )
def setUp(self):
self.site = AdminSite() self.site = AdminSite()
def test_modeladmin_str(self): def test_modeladmin_str(self):

View File

@ -10,11 +10,12 @@ from .models import (
class OneToOneTests(TestCase): class OneToOneTests(TestCase):
def setUp(self): @classmethod
self.p1 = Place.objects.create(name='Demon Dogs', address='944 W. Fullerton') def setUpTestData(cls):
self.p2 = Place.objects.create(name='Ace Hardware', address='1013 N. Ashland') cls.p1 = Place.objects.create(name='Demon Dogs', address='944 W. Fullerton')
self.r1 = Restaurant.objects.create(place=self.p1, serves_hot_dogs=True, serves_pizza=False) cls.p2 = Place.objects.create(name='Ace Hardware', address='1013 N. Ashland')
self.b1 = Bar.objects.create(place=self.p1, serves_cocktails=False) cls.r1 = Restaurant.objects.create(place=cls.p1, serves_hot_dogs=True, serves_pizza=False)
cls.b1 = Bar.objects.create(place=cls.p1, serves_cocktails=False)
def test_getter(self): def test_getter(self):
# A Restaurant can access its place. # A Restaurant can access its place.

View File

@ -865,25 +865,24 @@ class CustomPrefetchTests(TestCase):
class DefaultManagerTests(TestCase): class DefaultManagerTests(TestCase):
def setUp(self): @classmethod
self.qual1 = Qualification.objects.create(name="BA") def setUpTestData(cls):
self.qual2 = Qualification.objects.create(name="BSci") cls.qual1 = Qualification.objects.create(name='BA')
self.qual3 = Qualification.objects.create(name="MA") cls.qual2 = Qualification.objects.create(name='BSci')
self.qual4 = Qualification.objects.create(name="PhD") cls.qual3 = Qualification.objects.create(name='MA')
cls.qual4 = Qualification.objects.create(name='PhD')
self.teacher1 = Teacher.objects.create(name="Mr Cleese") cls.teacher1 = Teacher.objects.create(name='Mr Cleese')
self.teacher2 = Teacher.objects.create(name="Mr Idle") cls.teacher2 = Teacher.objects.create(name='Mr Idle')
self.teacher3 = Teacher.objects.create(name="Mr Chapman") cls.teacher3 = Teacher.objects.create(name='Mr Chapman')
cls.teacher1.qualifications.add(cls.qual1, cls.qual2, cls.qual3, cls.qual4)
cls.teacher2.qualifications.add(cls.qual1)
cls.teacher3.qualifications.add(cls.qual2)
self.teacher1.qualifications.add(self.qual1, self.qual2, self.qual3, self.qual4) cls.dept1 = Department.objects.create(name='English')
self.teacher2.qualifications.add(self.qual1) cls.dept2 = Department.objects.create(name='Physics')
self.teacher3.qualifications.add(self.qual2) cls.dept1.teachers.add(cls.teacher1, cls.teacher2)
cls.dept2.teachers.add(cls.teacher1, cls.teacher3)
self.dept1 = Department.objects.create(name="English")
self.dept2 = Department.objects.create(name="Physics")
self.dept1.teachers.add(self.teacher1, self.teacher2)
self.dept2.teachers.add(self.teacher1, self.teacher3)
def test_m2m_then_m2m(self): def test_m2m_then_m2m(self):
with self.assertNumQueries(3): with self.assertNumQueries(3):
@ -1127,42 +1126,42 @@ class LookupOrderingTest(TestCase):
ensure it is preserved. ensure it is preserved.
""" """
def setUp(self): @classmethod
self.person1 = Person.objects.create(name="Joe") def setUpTestData(cls):
self.person2 = Person.objects.create(name="Mary") person1 = Person.objects.create(name='Joe')
person2 = Person.objects.create(name='Mary')
# Set main_room for each house before creating the next one for # Set main_room for each house before creating the next one for
# databases where supports_nullable_unique_constraints is False. # databases where supports_nullable_unique_constraints is False.
house1 = House.objects.create(address='123 Main St')
room1_1 = Room.objects.create(name='Dining room', house=house1)
Room.objects.create(name='Lounge', house=house1)
Room.objects.create(name='Kitchen', house=house1)
house1.main_room = room1_1
house1.save()
person1.houses.add(house1)
self.house1 = House.objects.create(address="123 Main St") house2 = House.objects.create(address='45 Side St')
self.room1_1 = Room.objects.create(name="Dining room", house=self.house1) room2_1 = Room.objects.create(name='Dining room', house=house2)
self.room1_2 = Room.objects.create(name="Lounge", house=self.house1) Room.objects.create(name='Lounge', house=house2)
self.room1_3 = Room.objects.create(name="Kitchen", house=self.house1) house2.main_room = room2_1
self.house1.main_room = self.room1_1 house2.save()
self.house1.save() person1.houses.add(house2)
self.person1.houses.add(self.house1)
self.house2 = House.objects.create(address="45 Side St") house3 = House.objects.create(address='6 Downing St')
self.room2_1 = Room.objects.create(name="Dining room", house=self.house2) room3_1 = Room.objects.create(name='Dining room', house=house3)
self.room2_2 = Room.objects.create(name="Lounge", house=self.house2) Room.objects.create(name='Lounge', house=house3)
self.house2.main_room = self.room2_1 Room.objects.create(name='Kitchen', house=house3)
self.house2.save() house3.main_room = room3_1
self.person1.houses.add(self.house2) house3.save()
person2.houses.add(house3)
self.house3 = House.objects.create(address="6 Downing St") house4 = House.objects.create(address='7 Regents St')
self.room3_1 = Room.objects.create(name="Dining room", house=self.house3) room4_1 = Room.objects.create(name='Dining room', house=house4)
self.room3_2 = Room.objects.create(name="Lounge", house=self.house3) Room.objects.create(name='Lounge', house=house4)
self.room3_3 = Room.objects.create(name="Kitchen", house=self.house3) house4.main_room = room4_1
self.house3.main_room = self.room3_1 house4.save()
self.house3.save() person2.houses.add(house4)
self.person2.houses.add(self.house3)
self.house4 = House.objects.create(address="7 Regents St")
self.room4_1 = Room.objects.create(name="Dining room", house=self.house4)
self.room4_2 = Room.objects.create(name="Lounge", house=self.house4)
self.house4.main_room = self.room4_1
self.house4.save()
self.person2.houses.add(self.house4)
def test_order(self): def test_order(self):
with self.assertNumQueries(4): with self.assertNumQueries(4):
@ -1349,44 +1348,46 @@ class MultiDbTests(TestCase):
class Ticket19607Tests(TestCase): class Ticket19607Tests(TestCase):
@classmethod
def setUp(self): def setUpTestData(cls):
LessonEntry.objects.bulk_create(
for id, name1, name2 in [ LessonEntry(id=id_, name1=name1, name2=name2)
(1, 'einfach', 'simple'), for id_, name1, name2 in [
(2, 'schwierig', 'difficult'), (1, 'einfach', 'simple'),
]: (2, 'schwierig', 'difficult'),
LessonEntry.objects.create(id=id, name1=name1, name2=name2) ]
)
for id, lesson_entry_id, name in [ WordEntry.objects.bulk_create(
(1, 1, 'einfach'), WordEntry(id=id_, lesson_entry_id=lesson_entry_id, name=name)
(2, 1, 'simple'), for id_, lesson_entry_id, name in [
(3, 2, 'schwierig'), (1, 1, 'einfach'),
(4, 2, 'difficult'), (2, 1, 'simple'),
]: (3, 2, 'schwierig'),
WordEntry.objects.create(id=id, lesson_entry_id=lesson_entry_id, name=name) (4, 2, 'difficult'),
]
)
def test_bug(self): def test_bug(self):
list(WordEntry.objects.prefetch_related('lesson_entry', 'lesson_entry__wordentry_set')) list(WordEntry.objects.prefetch_related('lesson_entry', 'lesson_entry__wordentry_set'))
class Ticket21410Tests(TestCase): class Ticket21410Tests(TestCase):
@classmethod
def setUpTestData(cls):
book1 = Book.objects.create(title='Poems')
book2 = Book.objects.create(title='Jane Eyre')
book3 = Book.objects.create(title='Wuthering Heights')
book4 = Book.objects.create(title='Sense and Sensibility')
def setUp(self): author1 = Author2.objects.create(name='Charlotte', first_book=book1)
self.book1 = Book.objects.create(title="Poems") author2 = Author2.objects.create(name='Anne', first_book=book1)
self.book2 = Book.objects.create(title="Jane Eyre") author3 = Author2.objects.create(name='Emily', first_book=book1)
self.book3 = Book.objects.create(title="Wuthering Heights") author4 = Author2.objects.create(name='Jane', first_book=book4)
self.book4 = Book.objects.create(title="Sense and Sensibility")
self.author1 = Author2.objects.create(name="Charlotte", first_book=self.book1) author1.favorite_books.add(book1, book2, book3)
self.author2 = Author2.objects.create(name="Anne", first_book=self.book1) author2.favorite_books.add(book1)
self.author3 = Author2.objects.create(name="Emily", first_book=self.book1) author3.favorite_books.add(book2)
self.author4 = Author2.objects.create(name="Jane", first_book=self.book4) author4.favorite_books.add(book3)
self.author1.favorite_books.add(self.book1, self.book2, self.book3)
self.author2.favorite_books.add(self.book1)
self.author3.favorite_books.add(self.book2)
self.author4.favorite_books.add(self.book3)
def test_bug(self): def test_bug(self):
list(Author2.objects.prefetch_related('first_book', 'favorite_books')) list(Author2.objects.prefetch_related('first_book', 'favorite_books'))
@ -1394,15 +1395,16 @@ class Ticket21410Tests(TestCase):
class Ticket21760Tests(TestCase): class Ticket21760Tests(TestCase):
def setUp(self): @classmethod
self.rooms = [] def setUpTestData(cls):
cls.rooms = []
for _ in range(3): for _ in range(3):
house = House.objects.create() house = House.objects.create()
for _ in range(3): for _ in range(3):
self.rooms.append(Room.objects.create(house=house)) cls.rooms.append(Room.objects.create(house=house))
# Set main_room for each house before creating the next one for # Set main_room for each house before creating the next one for
# databases where supports_nullable_unique_constraints is False. # databases where supports_nullable_unique_constraints is False.
house.main_room = self.rooms[-3] house.main_room = cls.rooms[-3]
house.save() house.save()
def test_bug(self): def test_bug(self):

View File

@ -12,8 +12,9 @@ from .models import (
class BulkUpdateNoteTests(TestCase): class BulkUpdateNoteTests(TestCase):
def setUp(self): @classmethod
self.notes = [ def setUpTestData(cls):
cls.notes = [
Note.objects.create(note=str(i), misc=str(i)) Note.objects.create(note=str(i), misc=str(i))
for i in range(10) for i in range(10)
] ]

View File

@ -1962,7 +1962,8 @@ class Queries6Tests(TestCase):
class RawQueriesTests(TestCase): class RawQueriesTests(TestCase):
def setUp(self): @classmethod
def setUpTestData(cls):
Note.objects.create(note='n1', misc='foo', id=1) Note.objects.create(note='n1', misc='foo', id=1)
def test_ticket14729(self): def test_ticket14729(self):
@ -1986,10 +1987,11 @@ class GeneratorExpressionTests(SimpleTestCase):
class ComparisonTests(TestCase): class ComparisonTests(TestCase):
def setUp(self): @classmethod
self.n1 = Note.objects.create(note='n1', misc='foo', id=1) def setUpTestData(cls):
e1 = ExtraInfo.objects.create(info='e1', note=self.n1) cls.n1 = Note.objects.create(note='n1', misc='foo', id=1)
self.a2 = Author.objects.create(name='a2', num=2002, extra=e1) e1 = ExtraInfo.objects.create(info='e1', note=cls.n1)
cls.a2 = Author.objects.create(name='a2', num=2002, extra=e1)
def test_ticket8597(self): def test_ticket8597(self):
# Regression tests for case-insensitive comparisons # Regression tests for case-insensitive comparisons

View File

@ -90,29 +90,30 @@ class SerializerRegistrationTests(SimpleTestCase):
class SerializersTestBase: class SerializersTestBase:
serializer_name = None # Set by subclasses to the serialization format name serializer_name = None # Set by subclasses to the serialization format name
def setUp(self): @classmethod
def setUpTestData(cls):
sports = Category.objects.create(name="Sports") sports = Category.objects.create(name="Sports")
music = Category.objects.create(name="Music") music = Category.objects.create(name="Music")
op_ed = Category.objects.create(name="Op-Ed") op_ed = Category.objects.create(name="Op-Ed")
self.joe = Author.objects.create(name="Joe") cls.joe = Author.objects.create(name='Joe')
self.jane = Author.objects.create(name="Jane") cls.jane = Author.objects.create(name='Jane')
self.a1 = Article( cls.a1 = Article(
author=self.jane, author=cls.jane,
headline="Poker has no place on ESPN", headline="Poker has no place on ESPN",
pub_date=datetime(2006, 6, 16, 11, 00) pub_date=datetime(2006, 6, 16, 11, 00)
) )
self.a1.save() cls.a1.save()
self.a1.categories.set([sports, op_ed]) cls.a1.categories.set([sports, op_ed])
self.a2 = Article( cls.a2 = Article(
author=self.joe, author=cls.joe,
headline="Time to reform copyright", headline="Time to reform copyright",
pub_date=datetime(2006, 6, 16, 13, 00, 11, 345) pub_date=datetime(2006, 6, 16, 13, 00, 11, 345)
) )
self.a2.save() cls.a2.save()
self.a2.categories.set([music, op_ed]) cls.a2.categories.set([music, op_ed])
def test_serialize(self): def test_serialize(self):
"""Basic serialization works.""" """Basic serialization works."""