diff --git a/tests/admin_changelist/tests.py b/tests/admin_changelist/tests.py index ccf115a2e4..d0468e725b 100644 --- a/tests/admin_changelist/tests.py +++ b/tests/admin_changelist/tests.py @@ -50,9 +50,12 @@ def build_tbody_html(pk, href, extra_fields): @override_settings(ROOT_URLCONF="admin_changelist.urls") class ChangeListTests(TestCase): + @classmethod + def setUpTestData(cls): + cls.superuser = User.objects.create_superuser(username='super', email='a@b.com', password='xxx') + def setUp(self): self.factory = RequestFactory() - self.superuser = User.objects.create_superuser(username='super', email='a@b.com', password='xxx') def _create_superuser(self, username): return User.objects.create_superuser(username=username, email='a@b.com', password='xxx') diff --git a/tests/admin_filters/tests.py b/tests/admin_filters/tests.py index f901d32532..57a4d1acda 100644 --- a/tests/admin_filters/tests.py +++ b/tests/admin_filters/tests.py @@ -250,53 +250,55 @@ class BookmarkAdminGenericRelation(ModelAdmin): class ListFiltersTests(TestCase): - def setUp(self): - self.today = datetime.date.today() - self.tomorrow = self.today + datetime.timedelta(days=1) - self.one_week_ago = self.today - datetime.timedelta(days=7) - if self.today.month == 12: - self.next_month = self.today.replace(year=self.today.year + 1, month=1, day=1) + @classmethod + def setUpTestData(cls): + cls.today = datetime.date.today() + cls.tomorrow = cls.today + datetime.timedelta(days=1) + cls.one_week_ago = cls.today - datetime.timedelta(days=7) + if cls.today.month == 12: + cls.next_month = cls.today.replace(year=cls.today.year + 1, month=1, day=1) else: - self.next_month = self.today.replace(month=self.today.month + 1, day=1) - self.next_year = self.today.replace(year=self.today.year + 1, month=1, day=1) - - self.request_factory = RequestFactory() + cls.next_month = cls.today.replace(month=cls.today.month + 1, day=1) + cls.next_year = cls.today.replace(year=cls.today.year + 1, month=1, day=1) # Users - self.alfred = User.objects.create_superuser('alfred', 'alfred@example.com', 'password') - self.bob = User.objects.create_user('bob', 'bob@example.com') - self.lisa = User.objects.create_user('lisa', 'lisa@example.com') + cls.alfred = User.objects.create_superuser('alfred', 'alfred@example.com', 'password') + cls.bob = User.objects.create_user('bob', 'bob@example.com') + cls.lisa = User.objects.create_user('lisa', 'lisa@example.com') # Books - self.djangonaut_book = Book.objects.create( + cls.djangonaut_book = Book.objects.create( title='Djangonaut: an art of living', year=2009, - author=self.alfred, is_best_seller=True, date_registered=self.today, + author=cls.alfred, is_best_seller=True, date_registered=cls.today, is_best_seller2=True, ) - self.bio_book = Book.objects.create( - title='Django: a biography', year=1999, author=self.alfred, + cls.bio_book = Book.objects.create( + title='Django: a biography', year=1999, author=cls.alfred, is_best_seller=False, no=207, is_best_seller2=False, ) - self.django_book = Book.objects.create( - title='The Django Book', year=None, author=self.bob, - is_best_seller=None, date_registered=self.today, no=103, + cls.django_book = Book.objects.create( + title='The Django Book', year=None, author=cls.bob, + is_best_seller=None, date_registered=cls.today, no=103, is_best_seller2=None, ) - self.guitar_book = Book.objects.create( + cls.guitar_book = Book.objects.create( title='Guitar for dummies', year=2002, is_best_seller=True, - date_registered=self.one_week_ago, + date_registered=cls.one_week_ago, is_best_seller2=True, ) - self.guitar_book.contributors.set([self.bob, self.lisa]) + cls.guitar_book.contributors.set([cls.bob, cls.lisa]) # Departments - self.dev = Department.objects.create(code='DEV', description='Development') - self.design = Department.objects.create(code='DSN', description='Design') + cls.dev = Department.objects.create(code='DEV', description='Development') + cls.design = Department.objects.create(code='DSN', description='Design') # Employees - self.john = Employee.objects.create(name='John Blue', department=self.dev) - self.jack = Employee.objects.create(name='Jack Red', department=self.design) + cls.john = Employee.objects.create(name='John Blue', department=cls.dev) + cls.jack = Employee.objects.create(name='Jack Red', department=cls.design) + + def setUp(self): + self.request_factory = RequestFactory() def test_choicesfieldlistfilter_has_none_choice(self): """ diff --git a/tests/admin_inlines/tests.py b/tests/admin_inlines/tests.py index 66cf57dba1..9ba9bd279e 100644 --- a/tests/admin_inlines/tests.py +++ b/tests/admin_inlines/tests.py @@ -27,12 +27,13 @@ class TestDataMixin: @override_settings(ROOT_URLCONF='admin_inlines.urls') class TestInline(TestDataMixin, TestCase): + @classmethod + def setUpTestData(cls): + super().setUpTestData() + cls.holder = Holder.objects.create(dummy=13) + Inner(dummy=42, holder=cls.holder).save() def setUp(self): - holder = Holder(dummy=13) - holder.save() - Inner(dummy=42, holder=holder).save() - self.client.force_login(self.superuser) self.factory = RequestFactory() @@ -40,9 +41,8 @@ class TestInline(TestDataMixin, TestCase): """ can_delete should be passed to inlineformset factory. """ - holder = Holder.objects.get(dummy=13) response = self.client.get( - reverse('admin:admin_inlines_holder_change', args=(holder.id,)) + reverse('admin:admin_inlines_holder_change', args=(self.holder.id,)) ) inner_formset = response.context['inline_admin_formsets'][0].formset expected = InnerInline.can_delete @@ -570,41 +570,43 @@ class TestInlinePermissions(TestCase): inline. Refs #8060. """ - def setUp(self): - self.user = User(username='admin') - self.user.is_staff = True - self.user.is_active = True - self.user.set_password('secret') - self.user.save() + @classmethod + def setUpTestData(cls): + cls.user = User(username='admin') + cls.user.is_staff = True + cls.user.is_active = True + cls.user.set_password('secret') + cls.user.save() - self.author_ct = ContentType.objects.get_for_model(Author) - self.holder_ct = ContentType.objects.get_for_model(Holder2) - self.book_ct = ContentType.objects.get_for_model(Book) - self.inner_ct = ContentType.objects.get_for_model(Inner2) + cls.author_ct = ContentType.objects.get_for_model(Author) + cls.holder_ct = ContentType.objects.get_for_model(Holder2) + cls.book_ct = ContentType.objects.get_for_model(Book) + cls.inner_ct = ContentType.objects.get_for_model(Inner2) # User always has permissions to add and change Authors, and Holders, # the main (parent) models of the inlines. Permissions on the inlines # vary per test. - permission = Permission.objects.get(codename='add_author', content_type=self.author_ct) - self.user.user_permissions.add(permission) - permission = Permission.objects.get(codename='change_author', content_type=self.author_ct) - self.user.user_permissions.add(permission) - permission = Permission.objects.get(codename='add_holder2', content_type=self.holder_ct) - self.user.user_permissions.add(permission) - permission = Permission.objects.get(codename='change_holder2', content_type=self.holder_ct) - self.user.user_permissions.add(permission) + permission = Permission.objects.get(codename='add_author', content_type=cls.author_ct) + cls.user.user_permissions.add(permission) + permission = Permission.objects.get(codename='change_author', content_type=cls.author_ct) + cls.user.user_permissions.add(permission) + permission = Permission.objects.get(codename='add_holder2', content_type=cls.holder_ct) + cls.user.user_permissions.add(permission) + permission = Permission.objects.get(codename='change_holder2', content_type=cls.holder_ct) + cls.user.user_permissions.add(permission) author = Author.objects.create(pk=1, name='The Author') book = author.books.create(name='The inline Book') - self.author_change_url = reverse('admin:admin_inlines_author_change', args=(author.id,)) + cls.author_change_url = reverse('admin:admin_inlines_author_change', args=(author.id,)) # Get the ID of the automatically created intermediate model for the Author-Book m2m author_book_auto_m2m_intermediate = Author.books.through.objects.get(author=author, book=book) - self.author_book_auto_m2m_intermediate_id = author_book_auto_m2m_intermediate.pk + cls.author_book_auto_m2m_intermediate_id = author_book_auto_m2m_intermediate.pk - holder = Holder2.objects.create(dummy=13) - self.inner2 = Inner2.objects.create(dummy=42, holder=holder) - self.holder_change_url = reverse('admin:admin_inlines_holder2_change', args=(holder.id,)) + cls.holder = Holder2.objects.create(dummy=13) + cls.inner2 = Inner2.objects.create(dummy=42, holder=cls.holder) + def setUp(self): + self.holder_change_url = reverse('admin:admin_inlines_holder2_change', args=(self.holder.id,)) self.client.force_login(self.user) def test_inline_add_m2m_noperm(self): diff --git a/tests/admin_ordering/tests.py b/tests/admin_ordering/tests.py index 8de35fa32c..026c76fe23 100644 --- a/tests/admin_ordering/tests.py +++ b/tests/admin_ordering/tests.py @@ -35,14 +35,17 @@ class TestAdminOrdering(TestCase): class. """ - def setUp(self): - self.request_factory = RequestFactory() + @classmethod + def setUpTestData(cls): Band.objects.bulk_create([ Band(name='Aerosmith', bio='', rank=3), Band(name='Radiohead', bio='', rank=1), Band(name='Van Halen', bio='', rank=2), ]) + def setUp(self): + self.request_factory = RequestFactory() + def test_default_ordering(self): """ The default ordering should be by name, as specified in the inner Meta @@ -92,12 +95,13 @@ class TestInlineModelAdminOrdering(TestCase): define in InlineModelAdmin. """ - def setUp(self): - self.band = Band.objects.create(name='Aerosmith', bio='', rank=3) + @classmethod + def setUpTestData(cls): + cls.band = Band.objects.create(name='Aerosmith', bio='', rank=3) Song.objects.bulk_create([ - Song(band=self.band, name='Pink', duration=235), - Song(band=self.band, name='Dude (Looks Like a Lady)', duration=264), - Song(band=self.band, name='Jaded', duration=214), + Song(band=cls.band, name='Pink', duration=235), + Song(band=cls.band, name='Dude (Looks Like a Lady)', duration=264), + Song(band=cls.band, name='Jaded', duration=214), ]) def test_default_ordering(self): @@ -119,10 +123,12 @@ class TestInlineModelAdminOrdering(TestCase): class TestRelatedFieldsAdminOrdering(TestCase): - def setUp(self): - self.b1 = Band.objects.create(name='Pink Floyd', bio='', rank=1) - self.b2 = Band.objects.create(name='Foo Fighters', bio='', rank=5) + @classmethod + def setUpTestData(cls): + cls.b1 = Band.objects.create(name='Pink Floyd', bio='', rank=1) + cls.b2 = Band.objects.create(name='Foo Fighters', bio='', rank=5) + def setUp(self): # we need to register a custom ModelAdmin (instead of just using # ModelAdmin) because the field creator tries to find the ModelAdmin # for the related model diff --git a/tests/admin_views/test_actions.py b/tests/admin_views/test_actions.py index 1069f4a157..a98b80a1cb 100644 --- a/tests/admin_views/test_actions.py +++ b/tests/admin_views/test_actions.py @@ -410,15 +410,15 @@ class AdminActionsPermissionTests(TestCase): def setUpTestData(cls): cls.s1 = ExternalSubscriber.objects.create(name='John Doe', email='john@example.org') cls.s2 = Subscriber.objects.create(name='Max Mustermann', email='max@example.org') - - def setUp(self): - self.user = User.objects.create_user( + cls.user = User.objects.create_user( username='user', password='secret', email='user@example.com', is_staff=True, ) - self.client.force_login(self.user) permission = Permission.objects.get(codename='change_subscriber') - self.user.user_permissions.add(permission) + cls.user.user_permissions.add(permission) + + def setUp(self): + self.client.force_login(self.user) def test_model_admin_no_delete_permission(self): """ diff --git a/tests/admin_views/test_templatetags.py b/tests/admin_views/test_templatetags.py index 929ff7e045..65548bf7e0 100644 --- a/tests/admin_views/test_templatetags.py +++ b/tests/admin_views/test_templatetags.py @@ -72,8 +72,9 @@ class AdminTemplateTagsTest(AdminViewBasicTestCase): class DateHierarchyTests(TestCase): factory = RequestFactory() - def setUp(self): - self.superuser = User.objects.create_superuser(username='super', password='secret', email='super@example.com') + @classmethod + def setUpTestData(cls): + cls.superuser = User.objects.create_superuser(username='super', password='secret', email='super@example.com') def test_choice_links(self): modeladmin = ModelAdmin(Question, site) diff --git a/tests/admin_views/tests.py b/tests/admin_views/tests.py index c7ccf55fa0..8f486b93fe 100644 --- a/tests/admin_views/tests.py +++ b/tests/admin_views/tests.py @@ -3426,10 +3426,10 @@ class AdminCustomQuerysetTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser(username='super', password='secret', email='super@example.com') + cls.pks = [EmptyModel.objects.create().id for i in range(3)] def setUp(self): self.client.force_login(self.superuser) - self.pks = [EmptyModel.objects.create().id for i in range(3)] self.super_login = { REDIRECT_FIELD_NAME: reverse('admin:index'), 'username': 'super', @@ -3687,21 +3687,17 @@ class AdminInlineFileUploadTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser(username='super', password='secret', email='super@example.com') - - def setUp(self): - self.client.force_login(self.superuser) - - # Set up test Picture and Gallery. - # These must be set up here instead of in fixtures in order to allow Picture - # to use a NamedTemporaryFile. file1 = tempfile.NamedTemporaryFile(suffix=".file1") file1.write(b'a' * (2 ** 21)) filename = file1.name file1.close() - self.gallery = Gallery(name="Test Gallery") - self.gallery.save() - self.picture = Picture(name="Test Picture", image=filename, gallery=self.gallery) - self.picture.save() + cls.gallery = Gallery(name="Test Gallery") + cls.gallery.save() + cls.picture = Picture(name="Test Picture", image=filename, gallery=cls.gallery) + cls.picture.save() + + def setUp(self): + self.client.force_login(self.superuser) def test_form_has_multipart_enctype(self): response = self.client.get( @@ -3740,6 +3736,8 @@ class AdminInlineTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser(username='super', password='secret', email='super@example.com') + cls.collector = Collector(pk=1, name='John Fowles') + cls.collector.save() def setUp(self): self.post_data = { @@ -3828,8 +3826,6 @@ class AdminInlineTests(TestCase): } self.client.force_login(self.superuser) - self.collector = Collector(pk=1, name='John Fowles') - self.collector.save() def test_simple_inline(self): "A simple model can be saved as inlines" diff --git a/tests/auth_tests/test_auth_backends.py b/tests/auth_tests/test_auth_backends.py index 25a910cdf1..02f7d3ef27 100644 --- a/tests/auth_tests/test_auth_backends.py +++ b/tests/auth_tests/test_auth_backends.py @@ -376,10 +376,11 @@ class RowlevelBackendTest(TestCase): Tests for auth backend that supports object level permissions """ - def setUp(self): - self.user1 = User.objects.create_user('test', 'test@example.com', 'test') - self.user2 = User.objects.create_user('test2', 'test2@example.com', 'test') - self.user3 = User.objects.create_user('test3', 'test3@example.com', 'test') + @classmethod + def setUpTestData(cls): + cls.user1 = User.objects.create_user('test', 'test@example.com', 'test') + cls.user2 = User.objects.create_user('test2', 'test2@example.com', 'test') + cls.user3 = User.objects.create_user('test3', 'test3@example.com', 'test') def tearDown(self): # The get_group_permissions test messes with ContentTypes, which will @@ -439,8 +440,9 @@ class NoBackendsTest(TestCase): """ An appropriate error is raised if no auth backends are provided. """ - def setUp(self): - self.user = User.objects.create_user('test', 'test@example.com', 'test') + @classmethod + def setUpTestData(cls): + cls.user = User.objects.create_user('test', 'test@example.com', 'test') def test_raises_exception(self): msg = ( @@ -457,10 +459,11 @@ class InActiveUserBackendTest(TestCase): Tests for an inactive user """ - def setUp(self): - self.user1 = User.objects.create_user('test', 'test@example.com', 'test') - self.user1.is_active = False - self.user1.save() + @classmethod + def setUpTestData(cls): + cls.user1 = User.objects.create_user('test', 'test@example.com', 'test') + cls.user1.is_active = False + cls.user1.save() def test_has_perm(self): self.assertIs(self.user1.has_perm('perm', TestObj()), False) @@ -492,8 +495,11 @@ class PermissionDeniedBackendTest(TestCase): """ backend = 'auth_tests.test_auth_backends.PermissionDeniedBackend' + @classmethod + def setUpTestData(cls): + cls.user1 = User.objects.create_user('test', 'test@example.com', 'test') + def setUp(self): - self.user1 = User.objects.create_user('test', 'test@example.com', 'test') self.user_login_failed = [] signals.user_login_failed.connect(self.user_login_failed_listener) @@ -547,8 +553,9 @@ class ChangedBackendSettingsTest(TestCase): TEST_PASSWORD = 'test_password' TEST_EMAIL = 'test@example.com' - def setUp(self): - User.objects.create_user(self.TEST_USERNAME, self.TEST_EMAIL, self.TEST_PASSWORD) + @classmethod + def setUpTestData(cls): + User.objects.create_user(cls.TEST_USERNAME, cls.TEST_EMAIL, cls.TEST_PASSWORD) @override_settings(AUTHENTICATION_BACKENDS=[backend]) def test_changed_backend_settings(self): @@ -592,8 +599,9 @@ class SkippedBackend: class AuthenticateTests(TestCase): - def setUp(self): - self.user1 = User.objects.create_user('test', 'test@example.com', 'test') + @classmethod + def setUpTestData(cls): + cls.user1 = User.objects.create_user('test', 'test@example.com', 'test') @override_settings(AUTHENTICATION_BACKENDS=['auth_tests.test_auth_backends.TypeErrorBackend']) def test_type_error_raised(self): @@ -618,8 +626,11 @@ class ImproperlyConfiguredUserModelTest(TestCase): An exception from within get_user_model() is propagated and doesn't raise an UnboundLocalError (#21439). """ + @classmethod + def setUpTestData(cls): + cls.user1 = User.objects.create_user('test', 'test@example.com', 'test') + def setUp(self): - self.user1 = User.objects.create_user('test', 'test@example.com', 'test') self.client.login(username='test', password='test') @override_settings(AUTH_USER_MODEL='thismodel.doesntexist') diff --git a/tests/auth_tests/test_decorators.py b/tests/auth_tests/test_decorators.py index befe5c4d27..9cd79b4190 100644 --- a/tests/auth_tests/test_decorators.py +++ b/tests/auth_tests/test_decorators.py @@ -58,12 +58,15 @@ class PermissionsRequiredDecoratorTest(TestCase): """ Tests for the permission_required decorator """ - def setUp(self): - self.user = models.User.objects.create(username='joe', password='qwerty') - self.factory = RequestFactory() + @classmethod + def setUpTestData(cls): + cls.user = models.User.objects.create(username='joe', password='qwerty') # Add permissions auth.add_customuser and auth.change_customuser perms = models.Permission.objects.filter(codename__in=('add_customuser', 'change_customuser')) - self.user.user_permissions.add(*perms) + cls.user.user_permissions.add(*perms) + + def setUp(self): + self.factory = RequestFactory() def test_many_permissions_pass(self): diff --git a/tests/auth_tests/test_management.py b/tests/auth_tests/test_management.py index 07b913b8d2..b9bb092e78 100644 --- a/tests/auth_tests/test_management.py +++ b/tests/auth_tests/test_management.py @@ -132,8 +132,11 @@ class GetDefaultUsernameTestCase(TestCase): ]) class ChangepasswordManagementCommandTestCase(TestCase): + @classmethod + def setUpTestData(cls): + cls.user = User.objects.create_user(username='joe', password='qwerty') + def setUp(self): - self.user = User.objects.create_user(username='joe', password='qwerty') self.stdout = StringIO() self.stderr = StringIO() diff --git a/tests/auth_tests/test_views.py b/tests/auth_tests/test_views.py index 3d0c3ecadf..d4311a0fad 100644 --- a/tests/auth_tests/test_views.py +++ b/tests/auth_tests/test_views.py @@ -1109,10 +1109,15 @@ def get_perm(Model, perm): @override_settings(ROOT_URLCONF='auth_tests.urls_admin') class ChangelistTests(AuthViewsTestCase): - def setUp(self): + @classmethod + def setUpTestData(cls): + super().setUpTestData() # Make me a superuser before logging in. User.objects.filter(username='testclient').update(is_staff=True, is_superuser=True) + + def setUp(self): self.login() + # Get the latest last_login value. self.admin = User.objects.get(pk=self.u1.pk) def get_user_data(self, user): diff --git a/tests/basic/tests.py b/tests/basic/tests.py index b3bb4d02cc..909f3049b9 100644 --- a/tests/basic/tests.py +++ b/tests/basic/tests.py @@ -372,15 +372,16 @@ class ModelTest(TestCase): class ModelLookupTest(TestCase): - def setUp(self): + @classmethod + def setUpTestData(cls): # Create an Article. - self.a = Article( + cls.a = Article( id=None, headline='Swallow programs in Python', pub_date=datetime(2005, 7, 28), ) # Save it into the database. You have to call save() explicitly. - self.a.save() + cls.a.save() def test_all_lookup(self): # Change values by changing the attributes, then calling save(). diff --git a/tests/custom_columns/tests.py b/tests/custom_columns/tests.py index f5dfd9c0cd..874b024050 100644 --- a/tests/custom_columns/tests.py +++ b/tests/custom_columns/tests.py @@ -6,13 +6,14 @@ from .models import Article, Author class CustomColumnsTests(TestCase): - def setUp(self): - self.a1 = Author.objects.create(first_name="John", last_name="Smith") - self.a2 = Author.objects.create(first_name="Peter", last_name="Jones") - self.authors = [self.a1, self.a2] + @classmethod + def setUpTestData(cls): + cls.a1 = Author.objects.create(first_name="John", last_name="Smith") + cls.a2 = Author.objects.create(first_name="Peter", last_name="Jones") + cls.authors = [cls.a1, cls.a2] - self.article = Article.objects.create(headline="Django lets you build Web apps easily", primary_author=self.a1) - self.article.authors.set(self.authors) + cls.article = Article.objects.create(headline="Django lets you build Web apps easily", primary_author=cls.a1) + cls.article.authors.set(cls.authors) def test_query_all_available_authors(self): self.assertQuerysetEqual( diff --git a/tests/custom_lookups/tests.py b/tests/custom_lookups/tests.py index 981a45b74a..670f90f36c 100644 --- a/tests/custom_lookups/tests.py +++ b/tests/custom_lookups/tests.py @@ -400,12 +400,15 @@ class DateTimeLookupTests(TestCase): class YearLteTests(TestCase): + @classmethod + def setUpTestData(cls): + cls.a1 = Author.objects.create(name='a1', birthdate=date(1981, 2, 16)) + cls.a2 = Author.objects.create(name='a2', birthdate=date(2012, 2, 29)) + cls.a3 = Author.objects.create(name='a3', birthdate=date(2012, 1, 31)) + cls.a4 = Author.objects.create(name='a4', birthdate=date(2012, 3, 1)) + def setUp(self): models.DateField.register_lookup(YearTransform) - self.a1 = Author.objects.create(name='a1', birthdate=date(1981, 2, 16)) - self.a2 = Author.objects.create(name='a2', birthdate=date(2012, 2, 29)) - self.a3 = Author.objects.create(name='a3', birthdate=date(2012, 1, 31)) - self.a4 = Author.objects.create(name='a4', birthdate=date(2012, 3, 1)) def tearDown(self): models.DateField._unregister_lookup(YearTransform) diff --git a/tests/delete_regress/tests.py b/tests/delete_regress/tests.py index d4d39843e3..a1bead144e 100644 --- a/tests/delete_regress/tests.py +++ b/tests/delete_regress/tests.py @@ -258,11 +258,12 @@ class Ticket19102Tests(TestCase): Note that .values() is not tested here on purpose. .values().delete() doesn't work for non fast-path deletes at all. """ - def setUp(self): - self.o1 = OrgUnit.objects.create(name='o1') - self.o2 = OrgUnit.objects.create(name='o2') - self.l1 = Login.objects.create(description='l1', orgunit=self.o1) - self.l2 = Login.objects.create(description='l2', orgunit=self.o2) + @classmethod + def setUpTestData(cls): + cls.o1 = OrgUnit.objects.create(name='o1') + cls.o2 = OrgUnit.objects.create(name='o2') + cls.l1 = Login.objects.create(description='l1', orgunit=cls.o1) + cls.l2 = Login.objects.create(description='l2', orgunit=cls.o2) @skipUnlessDBFeature("update_can_self_select") def test_ticket_19102_annotate(self): diff --git a/tests/distinct_on_fields/tests.py b/tests/distinct_on_fields/tests.py index 6ed73cd75a..009b0191fb 100644 --- a/tests/distinct_on_fields/tests.py +++ b/tests/distinct_on_fields/tests.py @@ -9,27 +9,28 @@ from .models import Celebrity, Fan, Staff, StaffTag, Tag @skipUnlessDBFeature('can_distinct_on_fields') @skipUnlessDBFeature('supports_nullable_unique_constraints') class DistinctOnTests(TestCase): - def setUp(self): - self.t1 = Tag.objects.create(name='t1') - self.t2 = Tag.objects.create(name='t2', parent=self.t1) - self.t3 = Tag.objects.create(name='t3', parent=self.t1) - self.t4 = Tag.objects.create(name='t4', parent=self.t3) - self.t5 = Tag.objects.create(name='t5', parent=self.t3) + @classmethod + def setUpTestData(cls): + cls.t1 = Tag.objects.create(name='t1') + cls.t2 = Tag.objects.create(name='t2', parent=cls.t1) + cls.t3 = Tag.objects.create(name='t3', parent=cls.t1) + cls.t4 = Tag.objects.create(name='t4', parent=cls.t3) + cls.t5 = Tag.objects.create(name='t5', parent=cls.t3) - self.p1_o1 = Staff.objects.create(id=1, name="p1", organisation="o1") - self.p2_o1 = Staff.objects.create(id=2, name="p2", organisation="o1") - self.p3_o1 = Staff.objects.create(id=3, name="p3", organisation="o1") - self.p1_o2 = Staff.objects.create(id=4, name="p1", organisation="o2") - self.p1_o1.coworkers.add(self.p2_o1, self.p3_o1) - StaffTag.objects.create(staff=self.p1_o1, tag=self.t1) - StaffTag.objects.create(staff=self.p1_o1, tag=self.t1) + cls.p1_o1 = Staff.objects.create(id=1, name="p1", organisation="o1") + cls.p2_o1 = Staff.objects.create(id=2, name="p2", organisation="o1") + cls.p3_o1 = Staff.objects.create(id=3, name="p3", organisation="o1") + cls.p1_o2 = Staff.objects.create(id=4, name="p1", organisation="o2") + cls.p1_o1.coworkers.add(cls.p2_o1, cls.p3_o1) + StaffTag.objects.create(staff=cls.p1_o1, tag=cls.t1) + StaffTag.objects.create(staff=cls.p1_o1, tag=cls.t1) celeb1 = Celebrity.objects.create(name="c1") celeb2 = Celebrity.objects.create(name="c2") - self.fan1 = Fan.objects.create(fan_of=celeb1) - self.fan2 = Fan.objects.create(fan_of=celeb1) - self.fan3 = Fan.objects.create(fan_of=celeb2) + cls.fan1 = Fan.objects.create(fan_of=celeb1) + cls.fan2 = Fan.objects.create(fan_of=celeb1) + cls.fan3 = Fan.objects.create(fan_of=celeb2) def test_basic_distinct_on(self): """QuerySet.distinct('field', ...) works""" diff --git a/tests/expressions/tests.py b/tests/expressions/tests.py index 02d621a90c..2ed928915a 100644 --- a/tests/expressions/tests.py +++ b/tests/expressions/tests.py @@ -850,11 +850,12 @@ class SimpleExpressionTests(SimpleTestCase): class ExpressionsNumericTests(TestCase): - def setUp(self): + @classmethod + def setUpTestData(cls): Number(integer=-1).save() Number(integer=42).save() Number(integer=1337).save() - self.assertEqual(Number.objects.update(float=F('integer')), 3) + Number.objects.update(float=F('integer')) def test_fill_with_value_from_same_object(self): """ diff --git a/tests/extra_regress/tests.py b/tests/extra_regress/tests.py index e225d8cd62..67625235f4 100644 --- a/tests/extra_regress/tests.py +++ b/tests/extra_regress/tests.py @@ -9,8 +9,9 @@ from .models import Order, RevisionableModel, TestObject class ExtraRegressTests(TestCase): - def setUp(self): - self.u = User.objects.create_user( + @classmethod + def setUpTestData(cls): + cls.u = User.objects.create_user( username="fred", password="secret", email="fred@example.com" diff --git a/tests/foreign_object/test_empty_join.py b/tests/foreign_object/test_empty_join.py index 1fc6c450d7..83300fd25b 100644 --- a/tests/foreign_object/test_empty_join.py +++ b/tests/foreign_object/test_empty_join.py @@ -4,7 +4,8 @@ from .models import SlugPage class RestrictedConditionsTests(TestCase): - def setUp(self): + @classmethod + def setUpTestData(cls): slugs = [ 'a', 'a/a', diff --git a/tests/foreign_object/tests.py b/tests/foreign_object/tests.py index 6af6def6d7..2469250a12 100644 --- a/tests/foreign_object/tests.py +++ b/tests/foreign_object/tests.py @@ -18,28 +18,28 @@ from .models import ( class MultiColumnFKTests(TestCase): - def setUp(self): + @classmethod + def setUpTestData(cls): # Creating countries - self.usa = Country.objects.create(name="United States of America") - self.soviet_union = Country.objects.create(name="Soviet Union") - Person() + cls.usa = Country.objects.create(name="United States of America") + cls.soviet_union = Country.objects.create(name="Soviet Union") # Creating People - self.bob = Person() - self.bob.name = 'Bob' - self.bob.person_country = self.usa - self.bob.save() - self.jim = Person.objects.create(name='Jim', person_country=self.usa) - self.george = Person.objects.create(name='George', person_country=self.usa) + cls.bob = Person() + cls.bob.name = 'Bob' + cls.bob.person_country = cls.usa + cls.bob.save() + cls.jim = Person.objects.create(name='Jim', person_country=cls.usa) + cls.george = Person.objects.create(name='George', person_country=cls.usa) - self.jane = Person.objects.create(name='Jane', person_country=self.soviet_union) - self.mark = Person.objects.create(name='Mark', person_country=self.soviet_union) - self.sam = Person.objects.create(name='Sam', person_country=self.soviet_union) + cls.jane = Person.objects.create(name='Jane', person_country=cls.soviet_union) + cls.mark = Person.objects.create(name='Mark', person_country=cls.soviet_union) + cls.sam = Person.objects.create(name='Sam', person_country=cls.soviet_union) # Creating Groups - self.kgb = Group.objects.create(name='KGB', group_country=self.soviet_union) - self.cia = Group.objects.create(name='CIA', group_country=self.usa) - self.republican = Group.objects.create(name='Republican', group_country=self.usa) - self.democrat = Group.objects.create(name='Democrat', group_country=self.usa) + cls.kgb = Group.objects.create(name='KGB', group_country=cls.soviet_union) + cls.cia = Group.objects.create(name='CIA', group_country=cls.usa) + cls.republican = Group.objects.create(name='Republican', group_country=cls.usa) + cls.democrat = Group.objects.create(name='Democrat', group_country=cls.usa) def test_get_succeeds_on_multicolumn_match(self): # Membership objects have access to their related Person if both diff --git a/tests/from_db_value/tests.py b/tests/from_db_value/tests.py index c6cc07ed3c..ab92f37ccf 100644 --- a/tests/from_db_value/tests.py +++ b/tests/from_db_value/tests.py @@ -6,7 +6,8 @@ from .models import Cash, CashModel class FromDBValueTest(TestCase): - def setUp(self): + @classmethod + def setUpTestData(cls): CashModel.objects.create(cash='12.50') def test_simple_load(self): diff --git a/tests/get_or_create/tests.py b/tests/get_or_create/tests.py index 194d4159b6..ea9f137d7d 100644 --- a/tests/get_or_create/tests.py +++ b/tests/get_or_create/tests.py @@ -16,8 +16,9 @@ from .models import ( class GetOrCreateTests(TestCase): - def setUp(self): - self.lennon = Person.objects.create( + @classmethod + def setUpTestData(cls): + Person.objects.create( first_name='John', last_name='Lennon', birthday=date(1940, 10, 9) ) @@ -189,8 +190,9 @@ class GetOrCreateTests(TestCase): class GetOrCreateTestsWithManualPKs(TestCase): - def setUp(self): - self.first_pk = ManualPrimaryKeyTest.objects.create(id=1, data="Original") + @classmethod + def setUpTestData(cls): + ManualPrimaryKeyTest.objects.create(id=1, data="Original") def test_create_with_duplicate_primary_key(self): """ diff --git a/tests/gis_tests/geoapp/test_feeds.py b/tests/gis_tests/geoapp/test_feeds.py index 457754a004..037041e66e 100644 --- a/tests/gis_tests/geoapp/test_feeds.py +++ b/tests/gis_tests/geoapp/test_feeds.py @@ -12,7 +12,8 @@ from .models import City class GeoFeedTest(TestCase): fixtures = ['initial'] - def setUp(self): + @classmethod + def setUpTestData(cls): Site(id=settings.SITE_ID, domain="example.com", name="example.com").save() def assertChildNodes(self, elem, expected): diff --git a/tests/gis_tests/geoapp/test_sitemaps.py b/tests/gis_tests/geoapp/test_sitemaps.py index d1617860b5..1dbd57fd71 100644 --- a/tests/gis_tests/geoapp/test_sitemaps.py +++ b/tests/gis_tests/geoapp/test_sitemaps.py @@ -13,8 +13,8 @@ from .models import City, Country @override_settings(ROOT_URLCONF='gis_tests.geoapp.urls') class GeoSitemapTest(TestCase): - def setUp(self): - super().setUp() + @classmethod + def setUpTestData(cls): Site(id=settings.SITE_ID, domain="example.com", name="example.com").save() def assertChildNodes(self, elem, expected): diff --git a/tests/lookup/tests.py b/tests/lookup/tests.py index d759bbadff..3d68c04ea0 100644 --- a/tests/lookup/tests.py +++ b/tests/lookup/tests.py @@ -15,60 +15,61 @@ from .models import ( class LookupTests(TestCase): - def setUp(self): + @classmethod + def setUpTestData(cls): # Create a few Authors. - self.au1 = Author.objects.create(name='Author 1', alias='a1') - self.au2 = Author.objects.create(name='Author 2', alias='a2') + cls.au1 = Author.objects.create(name='Author 1', alias='a1') + cls.au2 = Author.objects.create(name='Author 2', alias='a2') # Create a few Articles. - self.a1 = Article.objects.create( + cls.a1 = Article.objects.create( headline='Article 1', pub_date=datetime(2005, 7, 26), - author=self.au1, + author=cls.au1, slug='a1', ) - self.a2 = Article.objects.create( + cls.a2 = Article.objects.create( headline='Article 2', pub_date=datetime(2005, 7, 27), - author=self.au1, + author=cls.au1, slug='a2', ) - self.a3 = Article.objects.create( + cls.a3 = Article.objects.create( headline='Article 3', pub_date=datetime(2005, 7, 27), - author=self.au1, + author=cls.au1, slug='a3', ) - self.a4 = Article.objects.create( + cls.a4 = Article.objects.create( headline='Article 4', pub_date=datetime(2005, 7, 28), - author=self.au1, + author=cls.au1, slug='a4', ) - self.a5 = Article.objects.create( + cls.a5 = Article.objects.create( headline='Article 5', pub_date=datetime(2005, 8, 1, 9, 0), - author=self.au2, + author=cls.au2, slug='a5', ) - self.a6 = Article.objects.create( + cls.a6 = Article.objects.create( headline='Article 6', pub_date=datetime(2005, 8, 1, 8, 0), - author=self.au2, + author=cls.au2, slug='a6', ) - self.a7 = Article.objects.create( + cls.a7 = Article.objects.create( headline='Article 7', pub_date=datetime(2005, 7, 27), - author=self.au2, + author=cls.au2, slug='a7', ) # Create a few Tags. - self.t1 = Tag.objects.create(name='Tag 1') - self.t1.articles.add(self.a1, self.a2, self.a3) - self.t2 = Tag.objects.create(name='Tag 2') - self.t2.articles.add(self.a3, self.a4, self.a5) - self.t3 = Tag.objects.create(name='Tag 3') - self.t3.articles.add(self.a5, self.a6, self.a7) + cls.t1 = Tag.objects.create(name='Tag 1') + cls.t1.articles.add(cls.a1, cls.a2, cls.a3) + cls.t2 = Tag.objects.create(name='Tag 2') + cls.t2.articles.add(cls.a3, cls.a4, cls.a5) + cls.t3 = Tag.objects.create(name='Tag 3') + cls.t3.articles.add(cls.a5, cls.a6, cls.a7) def test_exists(self): # We can use .exists() to check that there are some diff --git a/tests/m2m_recursive/tests.py b/tests/m2m_recursive/tests.py index b2667a8d52..ea0de1a329 100644 --- a/tests/m2m_recursive/tests.py +++ b/tests/m2m_recursive/tests.py @@ -6,17 +6,18 @@ from .models import Person class RecursiveM2MTests(TestCase): - def setUp(self): - self.a, self.b, self.c, self.d = [ + @classmethod + def setUpTestData(cls): + cls.a, cls.b, cls.c, cls.d = [ Person.objects.create(name=name) for name in ["Anne", "Bill", "Chuck", "David"] ] # Anne is friends with Bill and Chuck - self.a.friends.add(self.b, self.c) + cls.a.friends.add(cls.b, cls.c) # David is friends with Anne and Chuck - add in reverse direction - self.d.friends.add(self.a, self.c) + cls.d.friends.add(cls.a, cls.c) def test_recursive_m2m_all(self): # Who is friends with Anne? diff --git a/tests/m2m_signals/tests.py b/tests/m2m_signals/tests.py index 834897eb77..1e063e8a56 100644 --- a/tests/m2m_signals/tests.py +++ b/tests/m2m_signals/tests.py @@ -9,6 +9,26 @@ from .models import Car, Part, Person, SportsCar class ManyToManySignalsTest(TestCase): + @classmethod + def setUpTestData(cls): + cls.vw = Car.objects.create(name='VW') + cls.bmw = Car.objects.create(name='BMW') + cls.toyota = Car.objects.create(name='Toyota') + + cls.wheelset = Part.objects.create(name='Wheelset') + cls.doors = Part.objects.create(name='Doors') + cls.engine = Part.objects.create(name='Engine') + cls.airbag = Part.objects.create(name='Airbag') + cls.sunroof = Part.objects.create(name='Sunroof') + + cls.alice = Person.objects.create(name='Alice') + cls.bob = Person.objects.create(name='Bob') + cls.chuck = Person.objects.create(name='Chuck') + cls.daisy = Person.objects.create(name='Daisy') + + def setUp(self): + self.m2m_changed_messages = [] + def m2m_changed_signal_receiver(self, signal, sender, **kwargs): message = { 'instance': kwargs['instance'], @@ -22,24 +42,6 @@ class ManyToManySignalsTest(TestCase): ) self.m2m_changed_messages.append(message) - def setUp(self): - self.m2m_changed_messages = [] - - self.vw = Car.objects.create(name='VW') - self.bmw = Car.objects.create(name='BMW') - self.toyota = Car.objects.create(name='Toyota') - - self.wheelset = Part.objects.create(name='Wheelset') - self.doors = Part.objects.create(name='Doors') - self.engine = Part.objects.create(name='Engine') - self.airbag = Part.objects.create(name='Airbag') - self.sunroof = Part.objects.create(name='Sunroof') - - self.alice = Person.objects.create(name='Alice') - self.bob = Person.objects.create(name='Bob') - self.chuck = Person.objects.create(name='Chuck') - self.daisy = Person.objects.create(name='Daisy') - def tearDown(self): # disconnect all signal handlers models.signals.m2m_changed.disconnect( diff --git a/tests/m2m_through_regress/tests.py b/tests/m2m_through_regress/tests.py index 64be4252bd..7454bac99d 100644 --- a/tests/m2m_through_regress/tests.py +++ b/tests/m2m_through_regress/tests.py @@ -160,18 +160,19 @@ class M2MThroughSerializationTestCase(TestCase): class ToFieldThroughTests(TestCase): - def setUp(self): - self.car = Car.objects.create(make="Toyota") - self.driver = Driver.objects.create(name="Ryan Briscoe") - CarDriver.objects.create(car=self.car, driver=self.driver) + @classmethod + def setUpTestData(cls): + cls.car = Car.objects.create(make="Toyota") + cls.driver = Driver.objects.create(name="Ryan Briscoe") + CarDriver.objects.create(car=cls.car, driver=cls.driver) # We are testing if wrong objects get deleted due to using wrong # field value in m2m queries. So, it is essential that the pk # numberings do not match. # Create one intentionally unused driver to mix up the autonumbering - self.unused_driver = Driver.objects.create(name="Barney Gumble") + cls.unused_driver = Driver.objects.create(name="Barney Gumble") # And two intentionally unused cars. - self.unused_car1 = Car.objects.create(make="Trabant") - self.unused_car2 = Car.objects.create(make="Wartburg") + cls.unused_car1 = Car.objects.create(make="Trabant") + cls.unused_car2 = Car.objects.create(make="Wartburg") def test_to_field(self): self.assertQuerysetEqual( diff --git a/tests/m2o_recursive/tests.py b/tests/m2o_recursive/tests.py index 0f7ee9071d..309b61f260 100644 --- a/tests/m2o_recursive/tests.py +++ b/tests/m2o_recursive/tests.py @@ -5,11 +5,12 @@ from .models import Category, Person class ManyToOneRecursiveTests(TestCase): - def setUp(self): - self.r = Category(id=None, name='Root category', parent=None) - self.r.save() - self.c = Category(id=None, name='Child category', parent=self.r) - self.c.save() + @classmethod + def setUpTestData(cls): + cls.r = Category(id=None, name='Root category', parent=None) + cls.r.save() + cls.c = Category(id=None, name='Child category', parent=cls.r) + cls.c.save() def test_m2o_recursive(self): self.assertQuerysetEqual(self.r.child_set.all(), @@ -22,13 +23,14 @@ class ManyToOneRecursiveTests(TestCase): class MultipleManyToOneRecursiveTests(TestCase): - def setUp(self): - self.dad = Person(full_name='John Smith Senior', mother=None, father=None) - self.dad.save() - self.mom = Person(full_name='Jane Smith', mother=None, father=None) - self.mom.save() - self.kid = Person(full_name='John Smith Junior', mother=self.mom, father=self.dad) - self.kid.save() + @classmethod + def setUpTestData(cls): + cls.dad = Person(full_name='John Smith Senior', mother=None, father=None) + cls.dad.save() + cls.mom = Person(full_name='Jane Smith', mother=None, father=None) + cls.mom.save() + cls.kid = Person(full_name='John Smith Junior', mother=cls.mom, father=cls.dad) + cls.kid.save() def test_m2o_recursive2(self): self.assertEqual(self.kid.mother.id, self.mom.id) diff --git a/tests/model_fields/test_uuid.py b/tests/model_fields/test_uuid.py index 40fc82812f..c07d064d4d 100644 --- a/tests/model_fields/test_uuid.py +++ b/tests/model_fields/test_uuid.py @@ -82,8 +82,9 @@ class TestMethods(SimpleTestCase): class TestQuerying(TestCase): - def setUp(self): - self.objs = [ + @classmethod + def setUpTestData(cls): + cls.objs = [ NullableUUIDModel.objects.create(field=uuid.uuid4()), NullableUUIDModel.objects.create(field='550e8400e29b41d4a716446655440000'), NullableUUIDModel.objects.create(field=None), diff --git a/tests/model_forms/tests.py b/tests/model_forms/tests.py index 194e97a08b..77075e52f9 100644 --- a/tests/model_forms/tests.py +++ b/tests/model_forms/tests.py @@ -832,8 +832,9 @@ class UniqueTest(TestCase): """ unique/unique_together validation. """ - def setUp(self): - self.writer = Writer.objects.create(name='Mike Royko') + @classmethod + def setUpTestData(cls): + cls.writer = Writer.objects.create(name='Mike Royko') def test_simple_unique(self): form = ProductForm({'slug': 'teddy-bear-blue'}) @@ -1587,10 +1588,11 @@ class ModelFormBasicTests(TestCase): class ModelMultipleChoiceFieldTests(TestCase): - def setUp(self): - self.c1 = Category.objects.create(name='Entertainment', slug='entertainment', url='entertainment') - self.c2 = Category.objects.create(name="It's a test", slug='its-test', url='test') - self.c3 = Category.objects.create(name='Third', slug='third-test', url='third') + @classmethod + def setUpTestData(cls): + cls.c1 = Category.objects.create(name='Entertainment', slug='entertainment', url='entertainment') + cls.c2 = Category.objects.create(name="It's a test", slug='its-test', url='test') + cls.c3 = Category.objects.create(name='Third', slug='third-test', url='third') def test_model_multiple_choice_field(self): f = forms.ModelMultipleChoiceField(Category.objects.all()) diff --git a/tests/modeladmin/test_has_add_permission_obj_deprecation.py b/tests/modeladmin/test_has_add_permission_obj_deprecation.py index f5489a41db..17bbacc1fe 100644 --- a/tests/modeladmin/test_has_add_permission_obj_deprecation.py +++ b/tests/modeladmin/test_has_add_permission_obj_deprecation.py @@ -81,9 +81,12 @@ class BandAdmin(ModelAdmin): class ModelAdminTests(TestCase): + @classmethod + def setUpTestData(cls): + cls.band = Band.objects.create(name='The Doors', bio='', sign_date=date(1965, 1, 1)) + cls.song = Song.objects.create(name='test', band=cls.band) + def setUp(self): - self.band = Band.objects.create(name='The Doors', bio='', sign_date=date(1965, 1, 1)) - self.song = Song.objects.create(name='test', band=self.band) self.site = AdminSite() self.request = MockRequest() self.request.user = self.MockAddUser() diff --git a/tests/nested_foreign_keys/tests.py b/tests/nested_foreign_keys/tests.py index 098023d23a..08a19504e4 100644 --- a/tests/nested_foreign_keys/tests.py +++ b/tests/nested_foreign_keys/tests.py @@ -25,9 +25,10 @@ from .models import ( # relation such as introduced by one-to-one relations (through multi-table # inheritance). class NestedForeignKeysTests(TestCase): - def setUp(self): - self.director = Person.objects.create(name='Terry Gilliam / Terry Jones') - self.movie = Movie.objects.create(title='Monty Python and the Holy Grail', director=self.director) + @classmethod + def setUpTestData(cls): + cls.director = Person.objects.create(name='Terry Gilliam / Terry Jones') + cls.movie = Movie.objects.create(title='Monty Python and the Holy Grail', director=cls.director) # This test failed in #16715 because in some cases INNER JOIN was selected # for the second foreign key relation instead of LEFT OUTER JOIN. @@ -124,9 +125,10 @@ class NestedForeignKeysTests(TestCase): # nesting as we now use 4 models instead of 3 (and thus 3 relations). This # checks if promotion of join types works for deeper nesting too. class DeeplyNestedForeignKeysTests(TestCase): - def setUp(self): - self.director = Person.objects.create(name='Terry Gilliam / Terry Jones') - self.movie = Movie.objects.create(title='Monty Python and the Holy Grail', director=self.director) + @classmethod + def setUpTestData(cls): + cls.director = Person.objects.create(name='Terry Gilliam / Terry Jones') + cls.movie = Movie.objects.create(title='Monty Python and the Holy Grail', director=cls.director) def test_inheritance(self): Event.objects.create() diff --git a/tests/or_lookups/tests.py b/tests/or_lookups/tests.py index fd4cc3369b..f2d2ec2fad 100644 --- a/tests/or_lookups/tests.py +++ b/tests/or_lookups/tests.py @@ -9,14 +9,15 @@ from .models import Article class OrLookupsTests(TestCase): - def setUp(self): - self.a1 = Article.objects.create( + @classmethod + def setUpTestData(cls): + cls.a1 = Article.objects.create( headline='Hello', pub_date=datetime(2005, 11, 27) ).pk - self.a2 = Article.objects.create( + cls.a2 = Article.objects.create( headline='Goodbye', pub_date=datetime(2005, 11, 28) ).pk - self.a3 = Article.objects.create( + cls.a3 = Article.objects.create( headline='Hello and goodbye', pub_date=datetime(2005, 11, 29) ).pk diff --git a/tests/pagination/tests.py b/tests/pagination/tests.py index 20e74981cd..ef5108e42b 100644 --- a/tests/pagination/tests.py +++ b/tests/pagination/tests.py @@ -309,7 +309,8 @@ class ModelPaginationTests(TestCase): """ Test pagination with Django model instances """ - def setUp(self): + @classmethod + def setUpTestData(cls): # Prepare a list of objects for pagination. for x in range(1, 10): a = Article(headline='Article %s' % x, pub_date=datetime(2005, 7, 29)) diff --git a/tests/postgres_tests/test_array.py b/tests/postgres_tests/test_array.py index 9c678bb588..f878ad3fb5 100644 --- a/tests/postgres_tests/test_array.py +++ b/tests/postgres_tests/test_array.py @@ -138,14 +138,15 @@ class TestSaveLoad(PostgreSQLTestCase): class TestQuerying(PostgreSQLTestCase): - def setUp(self): - self.objs = [ - NullableIntegerArrayModel.objects.create(field=[1]), - NullableIntegerArrayModel.objects.create(field=[2]), - NullableIntegerArrayModel.objects.create(field=[2, 3]), - NullableIntegerArrayModel.objects.create(field=[20, 30, 40]), - NullableIntegerArrayModel.objects.create(field=None), - ] + @classmethod + def setUpTestData(cls): + cls.objs = NullableIntegerArrayModel.objects.bulk_create([ + NullableIntegerArrayModel(field=[1]), + NullableIntegerArrayModel(field=[2]), + NullableIntegerArrayModel(field=[2, 3]), + NullableIntegerArrayModel(field=[20, 30, 40]), + NullableIntegerArrayModel(field=None), + ]) def test_exact(self): self.assertSequenceEqual( @@ -368,16 +369,17 @@ class TestQuerying(PostgreSQLTestCase): class TestDateTimeExactQuerying(PostgreSQLTestCase): - def setUp(self): + @classmethod + def setUpTestData(cls): now = timezone.now() - self.datetimes = [now] - self.dates = [now.date()] - self.times = [now.time()] - self.objs = [ + cls.datetimes = [now] + cls.dates = [now.date()] + cls.times = [now.time()] + cls.objs = [ DateTimeArrayModel.objects.create( - datetimes=self.datetimes, - dates=self.dates, - times=self.times, + datetimes=cls.datetimes, + dates=cls.dates, + times=cls.times, ) ] @@ -402,17 +404,18 @@ class TestDateTimeExactQuerying(PostgreSQLTestCase): class TestOtherTypesExactQuerying(PostgreSQLTestCase): - def setUp(self): - self.ips = ['192.168.0.1', '::1'] - self.uuids = [uuid.uuid4()] - self.decimals = [decimal.Decimal(1.25), 1.75] - self.tags = [Tag(1), Tag(2), Tag(3)] - self.objs = [ + @classmethod + def setUpTestData(cls): + cls.ips = ['192.168.0.1', '::1'] + cls.uuids = [uuid.uuid4()] + cls.decimals = [decimal.Decimal(1.25), 1.75] + cls.tags = [Tag(1), Tag(2), Tag(3)] + cls.objs = [ OtherTypesArrayModel.objects.create( - ips=self.ips, - uuids=self.uuids, - decimals=self.decimals, - tags=self.tags, + ips=cls.ips, + uuids=cls.uuids, + decimals=cls.decimals, + tags=cls.tags, ) ] diff --git a/tests/postgres_tests/test_hstore.py b/tests/postgres_tests/test_hstore.py index 0a2d77e4a4..1d7403fb20 100644 --- a/tests/postgres_tests/test_hstore.py +++ b/tests/postgres_tests/test_hstore.py @@ -66,14 +66,15 @@ class SimpleTests(PostgreSQLTestCase): class TestQuerying(PostgreSQLTestCase): - def setUp(self): - self.objs = [ - HStoreModel.objects.create(field={'a': 'b'}), - HStoreModel.objects.create(field={'a': 'b', 'c': 'd'}), - HStoreModel.objects.create(field={'c': 'd'}), - HStoreModel.objects.create(field={}), - HStoreModel.objects.create(field=None), - ] + @classmethod + def setUpTestData(cls): + cls.objs = HStoreModel.objects.bulk_create([ + HStoreModel(field={'a': 'b'}), + HStoreModel(field={'a': 'b', 'c': 'd'}), + HStoreModel(field={'c': 'd'}), + HStoreModel(field={}), + HStoreModel(field=None), + ]) def test_exact(self): self.assertSequenceEqual( diff --git a/tests/postgres_tests/test_unaccent.py b/tests/postgres_tests/test_unaccent.py index 477bb3d653..6d52f1d7dd 100644 --- a/tests/postgres_tests/test_unaccent.py +++ b/tests/postgres_tests/test_unaccent.py @@ -10,11 +10,12 @@ class UnaccentTest(PostgreSQLTestCase): Model = CharFieldModel - def setUp(self): - self.Model.objects.bulk_create([ - self.Model(field="àéÖ"), - self.Model(field="aeO"), - self.Model(field="aeo"), + @classmethod + def setUpTestData(cls): + cls.Model.objects.bulk_create([ + cls.Model(field="àéÖ"), + cls.Model(field="aeO"), + cls.Model(field="aeo"), ]) def test_unaccent(self): diff --git a/tests/properties/tests.py b/tests/properties/tests.py index 9ba28c0d0d..38f39a1dbb 100644 --- a/tests/properties/tests.py +++ b/tests/properties/tests.py @@ -5,9 +5,10 @@ from .models import Person class PropertyTests(TestCase): - def setUp(self): - self.a = Person(first_name='John', last_name='Lennon') - self.a.save() + @classmethod + def setUpTestData(cls): + cls.a = Person(first_name='John', last_name='Lennon') + cls.a.save() def test_getter(self): self.assertEqual(self.a.full_name, 'John Lennon') diff --git a/tests/queryset_pickle/tests.py b/tests/queryset_pickle/tests.py index 7eec47379c..e5cee5fd66 100644 --- a/tests/queryset_pickle/tests.py +++ b/tests/queryset_pickle/tests.py @@ -9,7 +9,8 @@ from .models import Container, Event, Group, Happening, M2MModel class PickleabilityTestCase(TestCase): - def setUp(self): + @classmethod + def setUpTestData(cls): Happening.objects.create() # make sure the defaults are working (#20158) def assert_pickles(self, qs): diff --git a/tests/redirects_tests/tests.py b/tests/redirects_tests/tests.py index e7f5dfb97d..7e683a0ab7 100644 --- a/tests/redirects_tests/tests.py +++ b/tests/redirects_tests/tests.py @@ -11,8 +11,9 @@ from django.test import TestCase, modify_settings, override_settings @override_settings(APPEND_SLASH=False, ROOT_URLCONF='redirects_tests.urls', SITE_ID=1) class RedirectTests(TestCase): - def setUp(self): - self.site = Site.objects.get(pk=settings.SITE_ID) + @classmethod + def setUpTestData(cls): + cls.site = Site.objects.get(pk=settings.SITE_ID) def test_model(self): r1 = Redirect.objects.create(site=self.site, old_path='/initial', new_path='/new_target') @@ -75,8 +76,9 @@ class OverriddenRedirectFallbackMiddleware(RedirectFallbackMiddleware): @override_settings(SITE_ID=1) class OverriddenRedirectMiddlewareTests(TestCase): - def setUp(self): - self.site = Site.objects.get(pk=settings.SITE_ID) + @classmethod + def setUpTestData(cls): + cls.site = Site.objects.get(pk=settings.SITE_ID) def test_response_gone_class(self): Redirect.objects.create(site=self.site, old_path='/initial/', new_path='') diff --git a/tests/reverse_lookup/tests.py b/tests/reverse_lookup/tests.py index ece30a2a1b..e9eee35f47 100644 --- a/tests/reverse_lookup/tests.py +++ b/tests/reverse_lookup/tests.py @@ -6,7 +6,8 @@ from .models import Choice, Poll, User class ReverseLookupTests(TestCase): - def setUp(self): + @classmethod + def setUpTestData(cls): john = User.objects.create(name="John Doe") jim = User.objects.create(name="Jim Bo") first_poll = Poll.objects.create( diff --git a/tests/select_related_onetoone/tests.py b/tests/select_related_onetoone/tests.py index 0438257a0d..a7eee5efb8 100644 --- a/tests/select_related_onetoone/tests.py +++ b/tests/select_related_onetoone/tests.py @@ -10,7 +10,8 @@ from .models import ( class ReverseSelectRelatedTestCase(TestCase): - def setUp(self): + @classmethod + def setUpTestData(cls): user = User.objects.create(username="test") UserProfile.objects.create(user=user, state="KS", city="Lawrence") results = UserStatResult.objects.create(results='first results') diff --git a/tests/sitemaps_tests/base.py b/tests/sitemaps_tests/base.py index af5f78f327..3373af98e7 100644 --- a/tests/sitemaps_tests/base.py +++ b/tests/sitemaps_tests/base.py @@ -13,12 +13,15 @@ class SitemapTestsBase(TestCase): sites_installed = apps.is_installed('django.contrib.sites') domain = 'example.com' if sites_installed else 'testserver' + @classmethod + def setUpTestData(cls): + # Create an object for sitemap content. + TestModel.objects.create(name='Test Object') + cls.i18n_model = I18nTestModel.objects.create(name='Test Object') + def setUp(self): self.base_url = '%s://%s' % (self.protocol, self.domain) cache.clear() - # Create an object for sitemap content. - TestModel.objects.create(name='Test Object') - self.i18n_model = I18nTestModel.objects.create(name='Test Object') @classmethod def setUpClass(cls): diff --git a/tests/sites_framework/tests.py b/tests/sites_framework/tests.py index de37bb5a00..e44b3a6d84 100644 --- a/tests/sites_framework/tests.py +++ b/tests/sites_framework/tests.py @@ -10,7 +10,8 @@ from .models import CustomArticle, ExclusiveArticle, SyndicatedArticle class SitesFrameworkTestCase(TestCase): - def setUp(self): + @classmethod + def setUpTestData(cls): Site.objects.get_or_create(id=settings.SITE_ID, domain="example.com", name="example.com") Site.objects.create(id=settings.SITE_ID + 1, domain="example2.com", name="example2.com") diff --git a/tests/sites_tests/tests.py b/tests/sites_tests/tests.py index 4bbf9d2907..95b4373642 100644 --- a/tests/sites_tests/tests.py +++ b/tests/sites_tests/tests.py @@ -20,13 +20,14 @@ from django.test.utils import captured_stdout class SitesFrameworkTests(TestCase): multi_db = True - def setUp(self): - self.site = Site( + @classmethod + def setUpTestData(cls): + cls.site = Site( id=settings.SITE_ID, domain="example.com", name="example.com", ) - self.site.save() + cls.site.save() def tearDown(self): Site.objects.clear_cache() @@ -241,11 +242,14 @@ class JustOtherRouter: class CreateDefaultSiteTests(TestCase): multi_db = True - def setUp(self): - self.app_config = apps.get_app_config('sites') + @classmethod + def setUpTestData(cls): # Delete the site created as part of the default migration process. Site.objects.all().delete() + def setUp(self): + self.app_config = apps.get_app_config('sites') + def test_basic(self): """ #15346, #15573 - create_default_site() creates an example site only if diff --git a/tests/test_utils/tests.py b/tests/test_utils/tests.py index b484518687..320531e32c 100644 --- a/tests/test_utils/tests.py +++ b/tests/test_utils/tests.py @@ -185,9 +185,10 @@ class AssertNumQueriesUponConnectionTests(TransactionTestCase): class AssertQuerysetEqualTests(TestCase): - def setUp(self): - self.p1 = Person.objects.create(name='p1') - self.p2 = Person.objects.create(name='p2') + @classmethod + def setUpTestData(cls): + cls.p1 = Person.objects.create(name='p1') + cls.p2 = Person.objects.create(name='p2') def test_ordered(self): self.assertQuerysetEqual( @@ -255,8 +256,9 @@ class AssertQuerysetEqualTests(TestCase): @override_settings(ROOT_URLCONF='test_utils.urls') class CaptureQueriesContextManagerTests(TestCase): - def setUp(self): - self.person_pk = str(Person.objects.create(name='test').pk) + @classmethod + def setUpTestData(cls): + cls.person_pk = str(Person.objects.create(name='test').pk) def test_simple(self): with CaptureQueriesContext(connection) as captured_queries: diff --git a/tests/update/tests.py b/tests/update/tests.py index f99e16b3d3..63e930bfa0 100644 --- a/tests/update/tests.py +++ b/tests/update/tests.py @@ -6,12 +6,13 @@ from .models import A, B, Bar, D, DataPoint, Foo, RelatedPoint class SimpleTest(TestCase): - def setUp(self): - self.a1 = A.objects.create() - self.a2 = A.objects.create() + @classmethod + def setUpTestData(cls): + cls.a1 = A.objects.create() + cls.a2 = A.objects.create() for x in range(20): - B.objects.create(a=self.a1) - D.objects.create(a=self.a1) + B.objects.create(a=cls.a1) + D.objects.create(a=cls.a1) def test_nonempty_update(self): """ @@ -62,11 +63,12 @@ class SimpleTest(TestCase): class AdvancedTests(TestCase): - def setUp(self): - self.d0 = DataPoint.objects.create(name="d0", value="apple") - self.d2 = DataPoint.objects.create(name="d2", value="banana") - self.d3 = DataPoint.objects.create(name="d3", value="banana") - self.r1 = RelatedPoint.objects.create(name="r1", data=self.d3) + @classmethod + def setUpTestData(cls): + cls.d0 = DataPoint.objects.create(name="d0", value="apple") + cls.d2 = DataPoint.objects.create(name="d2", value="banana") + cls.d3 = DataPoint.objects.create(name="d3", value="banana") + cls.r1 = RelatedPoint.objects.create(name="r1", data=cls.d3) def test_update(self): """ diff --git a/tests/validation/tests.py b/tests/validation/tests.py index bc23ac5808..46fe2f0c7b 100644 --- a/tests/validation/tests.py +++ b/tests/validation/tests.py @@ -83,8 +83,9 @@ class ArticleForm(forms.ModelForm): class ModelFormsTests(TestCase): - def setUp(self): - self.author = Author.objects.create(name='Joseph Kocherhans') + @classmethod + def setUpTestData(cls): + cls.author = Author.objects.create(name='Joseph Kocherhans') def test_partial_validation(self): # Make sure the "commit=False and set field values later" idiom still