Switched setUp() to setUpTestData() where possible in Django's tests.

This commit is contained in:
Simon Charette 2018-11-23 20:59:38 -05:00 committed by Tim Graham
parent 9a7d336c38
commit 84e7a9f4a7
49 changed files with 421 additions and 334 deletions

View File

@ -50,9 +50,12 @@ def build_tbody_html(pk, href, extra_fields):
@override_settings(ROOT_URLCONF="admin_changelist.urls") @override_settings(ROOT_URLCONF="admin_changelist.urls")
class ChangeListTests(TestCase): class ChangeListTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.superuser = User.objects.create_superuser(username='super', email='a@b.com', password='xxx')
def setUp(self): def setUp(self):
self.factory = RequestFactory() self.factory = RequestFactory()
self.superuser = User.objects.create_superuser(username='super', email='a@b.com', password='xxx')
def _create_superuser(self, username): def _create_superuser(self, username):
return User.objects.create_superuser(username=username, email='a@b.com', password='xxx') return User.objects.create_superuser(username=username, email='a@b.com', password='xxx')

View File

@ -250,53 +250,55 @@ class BookmarkAdminGenericRelation(ModelAdmin):
class ListFiltersTests(TestCase): class ListFiltersTests(TestCase):
def setUp(self): @classmethod
self.today = datetime.date.today() def setUpTestData(cls):
self.tomorrow = self.today + datetime.timedelta(days=1) cls.today = datetime.date.today()
self.one_week_ago = self.today - datetime.timedelta(days=7) cls.tomorrow = cls.today + datetime.timedelta(days=1)
if self.today.month == 12: cls.one_week_ago = cls.today - datetime.timedelta(days=7)
self.next_month = self.today.replace(year=self.today.year + 1, month=1, day=1) if cls.today.month == 12:
cls.next_month = cls.today.replace(year=cls.today.year + 1, month=1, day=1)
else: else:
self.next_month = self.today.replace(month=self.today.month + 1, day=1) cls.next_month = cls.today.replace(month=cls.today.month + 1, day=1)
self.next_year = self.today.replace(year=self.today.year + 1, month=1, day=1) cls.next_year = cls.today.replace(year=cls.today.year + 1, month=1, day=1)
self.request_factory = RequestFactory()
# Users # Users
self.alfred = User.objects.create_superuser('alfred', 'alfred@example.com', 'password') cls.alfred = User.objects.create_superuser('alfred', 'alfred@example.com', 'password')
self.bob = User.objects.create_user('bob', 'bob@example.com') cls.bob = User.objects.create_user('bob', 'bob@example.com')
self.lisa = User.objects.create_user('lisa', 'lisa@example.com') cls.lisa = User.objects.create_user('lisa', 'lisa@example.com')
# Books # Books
self.djangonaut_book = Book.objects.create( cls.djangonaut_book = Book.objects.create(
title='Djangonaut: an art of living', year=2009, 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, is_best_seller2=True,
) )
self.bio_book = Book.objects.create( cls.bio_book = Book.objects.create(
title='Django: a biography', year=1999, author=self.alfred, title='Django: a biography', year=1999, author=cls.alfred,
is_best_seller=False, no=207, is_best_seller=False, no=207,
is_best_seller2=False, is_best_seller2=False,
) )
self.django_book = Book.objects.create( cls.django_book = Book.objects.create(
title='The Django Book', year=None, author=self.bob, title='The Django Book', year=None, author=cls.bob,
is_best_seller=None, date_registered=self.today, no=103, is_best_seller=None, date_registered=cls.today, no=103,
is_best_seller2=None, 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, 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, is_best_seller2=True,
) )
self.guitar_book.contributors.set([self.bob, self.lisa]) cls.guitar_book.contributors.set([cls.bob, cls.lisa])
# Departments # Departments
self.dev = Department.objects.create(code='DEV', description='Development') cls.dev = Department.objects.create(code='DEV', description='Development')
self.design = Department.objects.create(code='DSN', description='Design') cls.design = Department.objects.create(code='DSN', description='Design')
# Employees # Employees
self.john = Employee.objects.create(name='John Blue', department=self.dev) cls.john = Employee.objects.create(name='John Blue', department=cls.dev)
self.jack = Employee.objects.create(name='Jack Red', department=self.design) 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): def test_choicesfieldlistfilter_has_none_choice(self):
""" """

View File

@ -27,12 +27,13 @@ class TestDataMixin:
@override_settings(ROOT_URLCONF='admin_inlines.urls') @override_settings(ROOT_URLCONF='admin_inlines.urls')
class TestInline(TestDataMixin, TestCase): 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): def setUp(self):
holder = Holder(dummy=13)
holder.save()
Inner(dummy=42, holder=holder).save()
self.client.force_login(self.superuser) self.client.force_login(self.superuser)
self.factory = RequestFactory() self.factory = RequestFactory()
@ -40,9 +41,8 @@ class TestInline(TestDataMixin, TestCase):
""" """
can_delete should be passed to inlineformset factory. can_delete should be passed to inlineformset factory.
""" """
holder = Holder.objects.get(dummy=13)
response = self.client.get( 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 inner_formset = response.context['inline_admin_formsets'][0].formset
expected = InnerInline.can_delete expected = InnerInline.can_delete
@ -570,41 +570,43 @@ class TestInlinePermissions(TestCase):
inline. Refs #8060. inline. Refs #8060.
""" """
def setUp(self): @classmethod
self.user = User(username='admin') def setUpTestData(cls):
self.user.is_staff = True cls.user = User(username='admin')
self.user.is_active = True cls.user.is_staff = True
self.user.set_password('secret') cls.user.is_active = True
self.user.save() cls.user.set_password('secret')
cls.user.save()
self.author_ct = ContentType.objects.get_for_model(Author) cls.author_ct = ContentType.objects.get_for_model(Author)
self.holder_ct = ContentType.objects.get_for_model(Holder2) cls.holder_ct = ContentType.objects.get_for_model(Holder2)
self.book_ct = ContentType.objects.get_for_model(Book) cls.book_ct = ContentType.objects.get_for_model(Book)
self.inner_ct = ContentType.objects.get_for_model(Inner2) cls.inner_ct = ContentType.objects.get_for_model(Inner2)
# User always has permissions to add and change Authors, and Holders, # User always has permissions to add and change Authors, and Holders,
# the main (parent) models of the inlines. Permissions on the inlines # the main (parent) models of the inlines. Permissions on the inlines
# vary per test. # vary per test.
permission = Permission.objects.get(codename='add_author', content_type=self.author_ct) permission = Permission.objects.get(codename='add_author', content_type=cls.author_ct)
self.user.user_permissions.add(permission) cls.user.user_permissions.add(permission)
permission = Permission.objects.get(codename='change_author', content_type=self.author_ct) permission = Permission.objects.get(codename='change_author', content_type=cls.author_ct)
self.user.user_permissions.add(permission) cls.user.user_permissions.add(permission)
permission = Permission.objects.get(codename='add_holder2', content_type=self.holder_ct) permission = Permission.objects.get(codename='add_holder2', content_type=cls.holder_ct)
self.user.user_permissions.add(permission) cls.user.user_permissions.add(permission)
permission = Permission.objects.get(codename='change_holder2', content_type=self.holder_ct) permission = Permission.objects.get(codename='change_holder2', content_type=cls.holder_ct)
self.user.user_permissions.add(permission) cls.user.user_permissions.add(permission)
author = Author.objects.create(pk=1, name='The Author') author = Author.objects.create(pk=1, name='The Author')
book = author.books.create(name='The inline Book') 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 # 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) 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) cls.holder = Holder2.objects.create(dummy=13)
self.inner2 = Inner2.objects.create(dummy=42, holder=holder) cls.inner2 = Inner2.objects.create(dummy=42, holder=cls.holder)
self.holder_change_url = reverse('admin:admin_inlines_holder2_change', args=(holder.id,))
def setUp(self):
self.holder_change_url = reverse('admin:admin_inlines_holder2_change', args=(self.holder.id,))
self.client.force_login(self.user) self.client.force_login(self.user)
def test_inline_add_m2m_noperm(self): def test_inline_add_m2m_noperm(self):

View File

@ -35,14 +35,17 @@ class TestAdminOrdering(TestCase):
class. class.
""" """
def setUp(self): @classmethod
self.request_factory = RequestFactory() def setUpTestData(cls):
Band.objects.bulk_create([ Band.objects.bulk_create([
Band(name='Aerosmith', bio='', rank=3), Band(name='Aerosmith', bio='', rank=3),
Band(name='Radiohead', bio='', rank=1), Band(name='Radiohead', bio='', rank=1),
Band(name='Van Halen', bio='', rank=2), Band(name='Van Halen', bio='', rank=2),
]) ])
def setUp(self):
self.request_factory = RequestFactory()
def test_default_ordering(self): def test_default_ordering(self):
""" """
The default ordering should be by name, as specified in the inner Meta The default ordering should be by name, as specified in the inner Meta
@ -92,12 +95,13 @@ class TestInlineModelAdminOrdering(TestCase):
define in InlineModelAdmin. define in InlineModelAdmin.
""" """
def setUp(self): @classmethod
self.band = Band.objects.create(name='Aerosmith', bio='', rank=3) def setUpTestData(cls):
cls.band = Band.objects.create(name='Aerosmith', bio='', rank=3)
Song.objects.bulk_create([ Song.objects.bulk_create([
Song(band=self.band, name='Pink', duration=235), Song(band=cls.band, name='Pink', duration=235),
Song(band=self.band, name='Dude (Looks Like a Lady)', duration=264), Song(band=cls.band, name='Dude (Looks Like a Lady)', duration=264),
Song(band=self.band, name='Jaded', duration=214), Song(band=cls.band, name='Jaded', duration=214),
]) ])
def test_default_ordering(self): def test_default_ordering(self):
@ -119,10 +123,12 @@ class TestInlineModelAdminOrdering(TestCase):
class TestRelatedFieldsAdminOrdering(TestCase): class TestRelatedFieldsAdminOrdering(TestCase):
def setUp(self): @classmethod
self.b1 = Band.objects.create(name='Pink Floyd', bio='', rank=1) def setUpTestData(cls):
self.b2 = Band.objects.create(name='Foo Fighters', bio='', rank=5) 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 # we need to register a custom ModelAdmin (instead of just using
# ModelAdmin) because the field creator tries to find the ModelAdmin # ModelAdmin) because the field creator tries to find the ModelAdmin
# for the related model # for the related model

View File

@ -410,15 +410,15 @@ class AdminActionsPermissionTests(TestCase):
def setUpTestData(cls): def setUpTestData(cls):
cls.s1 = ExternalSubscriber.objects.create(name='John Doe', email='john@example.org') cls.s1 = ExternalSubscriber.objects.create(name='John Doe', email='john@example.org')
cls.s2 = Subscriber.objects.create(name='Max Mustermann', email='max@example.org') cls.s2 = Subscriber.objects.create(name='Max Mustermann', email='max@example.org')
cls.user = User.objects.create_user(
def setUp(self):
self.user = User.objects.create_user(
username='user', password='secret', email='user@example.com', username='user', password='secret', email='user@example.com',
is_staff=True, is_staff=True,
) )
self.client.force_login(self.user)
permission = Permission.objects.get(codename='change_subscriber') 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): def test_model_admin_no_delete_permission(self):
""" """

View File

@ -72,8 +72,9 @@ class AdminTemplateTagsTest(AdminViewBasicTestCase):
class DateHierarchyTests(TestCase): class DateHierarchyTests(TestCase):
factory = RequestFactory() factory = RequestFactory()
def setUp(self): @classmethod
self.superuser = User.objects.create_superuser(username='super', password='secret', email='super@example.com') def setUpTestData(cls):
cls.superuser = User.objects.create_superuser(username='super', password='secret', email='super@example.com')
def test_choice_links(self): def test_choice_links(self):
modeladmin = ModelAdmin(Question, site) modeladmin = ModelAdmin(Question, site)

View File

@ -3426,10 +3426,10 @@ class AdminCustomQuerysetTest(TestCase):
@classmethod @classmethod
def setUpTestData(cls): def setUpTestData(cls):
cls.superuser = User.objects.create_superuser(username='super', password='secret', email='super@example.com') 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): def setUp(self):
self.client.force_login(self.superuser) self.client.force_login(self.superuser)
self.pks = [EmptyModel.objects.create().id for i in range(3)]
self.super_login = { self.super_login = {
REDIRECT_FIELD_NAME: reverse('admin:index'), REDIRECT_FIELD_NAME: reverse('admin:index'),
'username': 'super', 'username': 'super',
@ -3687,21 +3687,17 @@ class AdminInlineFileUploadTest(TestCase):
@classmethod @classmethod
def setUpTestData(cls): def setUpTestData(cls):
cls.superuser = User.objects.create_superuser(username='super', password='secret', email='super@example.com') 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 = tempfile.NamedTemporaryFile(suffix=".file1")
file1.write(b'a' * (2 ** 21)) file1.write(b'a' * (2 ** 21))
filename = file1.name filename = file1.name
file1.close() file1.close()
self.gallery = Gallery(name="Test Gallery") cls.gallery = Gallery(name="Test Gallery")
self.gallery.save() cls.gallery.save()
self.picture = Picture(name="Test Picture", image=filename, gallery=self.gallery) cls.picture = Picture(name="Test Picture", image=filename, gallery=cls.gallery)
self.picture.save() cls.picture.save()
def setUp(self):
self.client.force_login(self.superuser)
def test_form_has_multipart_enctype(self): def test_form_has_multipart_enctype(self):
response = self.client.get( response = self.client.get(
@ -3740,6 +3736,8 @@ class AdminInlineTests(TestCase):
@classmethod @classmethod
def setUpTestData(cls): def setUpTestData(cls):
cls.superuser = User.objects.create_superuser(username='super', password='secret', email='super@example.com') 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): def setUp(self):
self.post_data = { self.post_data = {
@ -3828,8 +3826,6 @@ class AdminInlineTests(TestCase):
} }
self.client.force_login(self.superuser) self.client.force_login(self.superuser)
self.collector = Collector(pk=1, name='John Fowles')
self.collector.save()
def test_simple_inline(self): def test_simple_inline(self):
"A simple model can be saved as inlines" "A simple model can be saved as inlines"

View File

@ -376,10 +376,11 @@ class RowlevelBackendTest(TestCase):
Tests for auth backend that supports object level permissions Tests for auth backend that supports object level permissions
""" """
def setUp(self): @classmethod
self.user1 = User.objects.create_user('test', 'test@example.com', 'test') def setUpTestData(cls):
self.user2 = User.objects.create_user('test2', 'test2@example.com', 'test') cls.user1 = User.objects.create_user('test', 'test@example.com', 'test')
self.user3 = User.objects.create_user('test3', 'test3@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): def tearDown(self):
# The get_group_permissions test messes with ContentTypes, which will # 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. An appropriate error is raised if no auth backends are provided.
""" """
def setUp(self): @classmethod
self.user = User.objects.create_user('test', 'test@example.com', 'test') def setUpTestData(cls):
cls.user = User.objects.create_user('test', 'test@example.com', 'test')
def test_raises_exception(self): def test_raises_exception(self):
msg = ( msg = (
@ -457,10 +459,11 @@ class InActiveUserBackendTest(TestCase):
Tests for an inactive user Tests for an inactive user
""" """
def setUp(self): @classmethod
self.user1 = User.objects.create_user('test', 'test@example.com', 'test') def setUpTestData(cls):
self.user1.is_active = False cls.user1 = User.objects.create_user('test', 'test@example.com', 'test')
self.user1.save() cls.user1.is_active = False
cls.user1.save()
def test_has_perm(self): def test_has_perm(self):
self.assertIs(self.user1.has_perm('perm', TestObj()), False) self.assertIs(self.user1.has_perm('perm', TestObj()), False)
@ -492,8 +495,11 @@ class PermissionDeniedBackendTest(TestCase):
""" """
backend = 'auth_tests.test_auth_backends.PermissionDeniedBackend' 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): def setUp(self):
self.user1 = User.objects.create_user('test', 'test@example.com', 'test')
self.user_login_failed = [] self.user_login_failed = []
signals.user_login_failed.connect(self.user_login_failed_listener) signals.user_login_failed.connect(self.user_login_failed_listener)
@ -547,8 +553,9 @@ class ChangedBackendSettingsTest(TestCase):
TEST_PASSWORD = 'test_password' TEST_PASSWORD = 'test_password'
TEST_EMAIL = 'test@example.com' TEST_EMAIL = 'test@example.com'
def setUp(self): @classmethod
User.objects.create_user(self.TEST_USERNAME, self.TEST_EMAIL, self.TEST_PASSWORD) def setUpTestData(cls):
User.objects.create_user(cls.TEST_USERNAME, cls.TEST_EMAIL, cls.TEST_PASSWORD)
@override_settings(AUTHENTICATION_BACKENDS=[backend]) @override_settings(AUTHENTICATION_BACKENDS=[backend])
def test_changed_backend_settings(self): def test_changed_backend_settings(self):
@ -592,8 +599,9 @@ class SkippedBackend:
class AuthenticateTests(TestCase): class AuthenticateTests(TestCase):
def setUp(self): @classmethod
self.user1 = User.objects.create_user('test', 'test@example.com', 'test') def setUpTestData(cls):
cls.user1 = User.objects.create_user('test', 'test@example.com', 'test')
@override_settings(AUTHENTICATION_BACKENDS=['auth_tests.test_auth_backends.TypeErrorBackend']) @override_settings(AUTHENTICATION_BACKENDS=['auth_tests.test_auth_backends.TypeErrorBackend'])
def test_type_error_raised(self): 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 An exception from within get_user_model() is propagated and doesn't
raise an UnboundLocalError (#21439). raise an UnboundLocalError (#21439).
""" """
@classmethod
def setUpTestData(cls):
cls.user1 = User.objects.create_user('test', 'test@example.com', 'test')
def setUp(self): def setUp(self):
self.user1 = User.objects.create_user('test', 'test@example.com', 'test')
self.client.login(username='test', password='test') self.client.login(username='test', password='test')
@override_settings(AUTH_USER_MODEL='thismodel.doesntexist') @override_settings(AUTH_USER_MODEL='thismodel.doesntexist')

View File

@ -58,12 +58,15 @@ class PermissionsRequiredDecoratorTest(TestCase):
""" """
Tests for the permission_required decorator Tests for the permission_required decorator
""" """
def setUp(self): @classmethod
self.user = models.User.objects.create(username='joe', password='qwerty') def setUpTestData(cls):
self.factory = RequestFactory() cls.user = models.User.objects.create(username='joe', password='qwerty')
# Add permissions auth.add_customuser and auth.change_customuser # Add permissions auth.add_customuser and auth.change_customuser
perms = models.Permission.objects.filter(codename__in=('add_customuser', '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): def test_many_permissions_pass(self):

View File

@ -132,8 +132,11 @@ class GetDefaultUsernameTestCase(TestCase):
]) ])
class ChangepasswordManagementCommandTestCase(TestCase): class ChangepasswordManagementCommandTestCase(TestCase):
@classmethod
def setUpTestData(cls):
cls.user = User.objects.create_user(username='joe', password='qwerty')
def setUp(self): def setUp(self):
self.user = User.objects.create_user(username='joe', password='qwerty')
self.stdout = StringIO() self.stdout = StringIO()
self.stderr = StringIO() self.stderr = StringIO()

View File

@ -1109,10 +1109,15 @@ def get_perm(Model, perm):
@override_settings(ROOT_URLCONF='auth_tests.urls_admin') @override_settings(ROOT_URLCONF='auth_tests.urls_admin')
class ChangelistTests(AuthViewsTestCase): class ChangelistTests(AuthViewsTestCase):
def setUp(self): @classmethod
def setUpTestData(cls):
super().setUpTestData()
# Make me a superuser before logging in. # Make me a superuser before logging in.
User.objects.filter(username='testclient').update(is_staff=True, is_superuser=True) User.objects.filter(username='testclient').update(is_staff=True, is_superuser=True)
def setUp(self):
self.login() self.login()
# Get the latest last_login value.
self.admin = User.objects.get(pk=self.u1.pk) self.admin = User.objects.get(pk=self.u1.pk)
def get_user_data(self, user): def get_user_data(self, user):

View File

@ -372,15 +372,16 @@ class ModelTest(TestCase):
class ModelLookupTest(TestCase): class ModelLookupTest(TestCase):
def setUp(self): @classmethod
def setUpTestData(cls):
# Create an Article. # Create an Article.
self.a = Article( cls.a = Article(
id=None, id=None,
headline='Swallow programs in Python', headline='Swallow programs in Python',
pub_date=datetime(2005, 7, 28), pub_date=datetime(2005, 7, 28),
) )
# Save it into the database. You have to call save() explicitly. # Save it into the database. You have to call save() explicitly.
self.a.save() cls.a.save()
def test_all_lookup(self): def test_all_lookup(self):
# Change values by changing the attributes, then calling save(). # Change values by changing the attributes, then calling save().

View File

@ -6,13 +6,14 @@ from .models import Article, Author
class CustomColumnsTests(TestCase): class CustomColumnsTests(TestCase):
def setUp(self): @classmethod
self.a1 = Author.objects.create(first_name="John", last_name="Smith") def setUpTestData(cls):
self.a2 = Author.objects.create(first_name="Peter", last_name="Jones") cls.a1 = Author.objects.create(first_name="John", last_name="Smith")
self.authors = [self.a1, self.a2] 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) cls.article = Article.objects.create(headline="Django lets you build Web apps easily", primary_author=cls.a1)
self.article.authors.set(self.authors) cls.article.authors.set(cls.authors)
def test_query_all_available_authors(self): def test_query_all_available_authors(self):
self.assertQuerysetEqual( self.assertQuerysetEqual(

View File

@ -400,12 +400,15 @@ class DateTimeLookupTests(TestCase):
class YearLteTests(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): def setUp(self):
models.DateField.register_lookup(YearTransform) 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): def tearDown(self):
models.DateField._unregister_lookup(YearTransform) models.DateField._unregister_lookup(YearTransform)

View File

@ -258,11 +258,12 @@ class Ticket19102Tests(TestCase):
Note that .values() is not tested here on purpose. .values().delete() Note that .values() is not tested here on purpose. .values().delete()
doesn't work for non fast-path deletes at all. doesn't work for non fast-path deletes at all.
""" """
def setUp(self): @classmethod
self.o1 = OrgUnit.objects.create(name='o1') def setUpTestData(cls):
self.o2 = OrgUnit.objects.create(name='o2') cls.o1 = OrgUnit.objects.create(name='o1')
self.l1 = Login.objects.create(description='l1', orgunit=self.o1) cls.o2 = OrgUnit.objects.create(name='o2')
self.l2 = Login.objects.create(description='l2', orgunit=self.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") @skipUnlessDBFeature("update_can_self_select")
def test_ticket_19102_annotate(self): def test_ticket_19102_annotate(self):

View File

@ -9,27 +9,28 @@ from .models import Celebrity, Fan, Staff, StaffTag, Tag
@skipUnlessDBFeature('can_distinct_on_fields') @skipUnlessDBFeature('can_distinct_on_fields')
@skipUnlessDBFeature('supports_nullable_unique_constraints') @skipUnlessDBFeature('supports_nullable_unique_constraints')
class DistinctOnTests(TestCase): class DistinctOnTests(TestCase):
def setUp(self): @classmethod
self.t1 = Tag.objects.create(name='t1') def setUpTestData(cls):
self.t2 = Tag.objects.create(name='t2', parent=self.t1) cls.t1 = Tag.objects.create(name='t1')
self.t3 = Tag.objects.create(name='t3', parent=self.t1) cls.t2 = Tag.objects.create(name='t2', parent=cls.t1)
self.t4 = Tag.objects.create(name='t4', parent=self.t3) cls.t3 = Tag.objects.create(name='t3', parent=cls.t1)
self.t5 = Tag.objects.create(name='t5', parent=self.t3) 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") cls.p1_o1 = Staff.objects.create(id=1, name="p1", organisation="o1")
self.p2_o1 = Staff.objects.create(id=2, name="p2", organisation="o1") cls.p2_o1 = Staff.objects.create(id=2, name="p2", organisation="o1")
self.p3_o1 = Staff.objects.create(id=3, name="p3", organisation="o1") cls.p3_o1 = Staff.objects.create(id=3, name="p3", organisation="o1")
self.p1_o2 = Staff.objects.create(id=4, name="p1", organisation="o2") cls.p1_o2 = Staff.objects.create(id=4, name="p1", organisation="o2")
self.p1_o1.coworkers.add(self.p2_o1, self.p3_o1) cls.p1_o1.coworkers.add(cls.p2_o1, cls.p3_o1)
StaffTag.objects.create(staff=self.p1_o1, tag=self.t1) StaffTag.objects.create(staff=cls.p1_o1, tag=cls.t1)
StaffTag.objects.create(staff=self.p1_o1, tag=self.t1) StaffTag.objects.create(staff=cls.p1_o1, tag=cls.t1)
celeb1 = Celebrity.objects.create(name="c1") celeb1 = Celebrity.objects.create(name="c1")
celeb2 = Celebrity.objects.create(name="c2") celeb2 = Celebrity.objects.create(name="c2")
self.fan1 = Fan.objects.create(fan_of=celeb1) cls.fan1 = Fan.objects.create(fan_of=celeb1)
self.fan2 = Fan.objects.create(fan_of=celeb1) cls.fan2 = Fan.objects.create(fan_of=celeb1)
self.fan3 = Fan.objects.create(fan_of=celeb2) cls.fan3 = Fan.objects.create(fan_of=celeb2)
def test_basic_distinct_on(self): def test_basic_distinct_on(self):
"""QuerySet.distinct('field', ...) works""" """QuerySet.distinct('field', ...) works"""

View File

@ -850,11 +850,12 @@ class SimpleExpressionTests(SimpleTestCase):
class ExpressionsNumericTests(TestCase): class ExpressionsNumericTests(TestCase):
def setUp(self): @classmethod
def setUpTestData(cls):
Number(integer=-1).save() Number(integer=-1).save()
Number(integer=42).save() Number(integer=42).save()
Number(integer=1337).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): def test_fill_with_value_from_same_object(self):
""" """

View File

@ -9,8 +9,9 @@ from .models import Order, RevisionableModel, TestObject
class ExtraRegressTests(TestCase): class ExtraRegressTests(TestCase):
def setUp(self): @classmethod
self.u = User.objects.create_user( def setUpTestData(cls):
cls.u = User.objects.create_user(
username="fred", username="fred",
password="secret", password="secret",
email="fred@example.com" email="fred@example.com"

View File

@ -4,7 +4,8 @@ from .models import SlugPage
class RestrictedConditionsTests(TestCase): class RestrictedConditionsTests(TestCase):
def setUp(self): @classmethod
def setUpTestData(cls):
slugs = [ slugs = [
'a', 'a',
'a/a', 'a/a',

View File

@ -18,28 +18,28 @@ from .models import (
class MultiColumnFKTests(TestCase): class MultiColumnFKTests(TestCase):
def setUp(self): @classmethod
def setUpTestData(cls):
# Creating countries # Creating countries
self.usa = Country.objects.create(name="United States of America") cls.usa = Country.objects.create(name="United States of America")
self.soviet_union = Country.objects.create(name="Soviet Union") cls.soviet_union = Country.objects.create(name="Soviet Union")
Person()
# Creating People # Creating People
self.bob = Person() cls.bob = Person()
self.bob.name = 'Bob' cls.bob.name = 'Bob'
self.bob.person_country = self.usa cls.bob.person_country = cls.usa
self.bob.save() cls.bob.save()
self.jim = Person.objects.create(name='Jim', person_country=self.usa) cls.jim = Person.objects.create(name='Jim', person_country=cls.usa)
self.george = Person.objects.create(name='George', person_country=self.usa) cls.george = Person.objects.create(name='George', person_country=cls.usa)
self.jane = Person.objects.create(name='Jane', person_country=self.soviet_union) cls.jane = Person.objects.create(name='Jane', person_country=cls.soviet_union)
self.mark = Person.objects.create(name='Mark', person_country=self.soviet_union) cls.mark = Person.objects.create(name='Mark', person_country=cls.soviet_union)
self.sam = Person.objects.create(name='Sam', person_country=self.soviet_union) cls.sam = Person.objects.create(name='Sam', person_country=cls.soviet_union)
# Creating Groups # Creating Groups
self.kgb = Group.objects.create(name='KGB', group_country=self.soviet_union) cls.kgb = Group.objects.create(name='KGB', group_country=cls.soviet_union)
self.cia = Group.objects.create(name='CIA', group_country=self.usa) cls.cia = Group.objects.create(name='CIA', group_country=cls.usa)
self.republican = Group.objects.create(name='Republican', group_country=self.usa) cls.republican = Group.objects.create(name='Republican', group_country=cls.usa)
self.democrat = Group.objects.create(name='Democrat', group_country=self.usa) cls.democrat = Group.objects.create(name='Democrat', group_country=cls.usa)
def test_get_succeeds_on_multicolumn_match(self): def test_get_succeeds_on_multicolumn_match(self):
# Membership objects have access to their related Person if both # Membership objects have access to their related Person if both

View File

@ -6,7 +6,8 @@ from .models import Cash, CashModel
class FromDBValueTest(TestCase): class FromDBValueTest(TestCase):
def setUp(self): @classmethod
def setUpTestData(cls):
CashModel.objects.create(cash='12.50') CashModel.objects.create(cash='12.50')
def test_simple_load(self): def test_simple_load(self):

View File

@ -16,8 +16,9 @@ from .models import (
class GetOrCreateTests(TestCase): class GetOrCreateTests(TestCase):
def setUp(self): @classmethod
self.lennon = Person.objects.create( def setUpTestData(cls):
Person.objects.create(
first_name='John', last_name='Lennon', birthday=date(1940, 10, 9) first_name='John', last_name='Lennon', birthday=date(1940, 10, 9)
) )
@ -189,8 +190,9 @@ class GetOrCreateTests(TestCase):
class GetOrCreateTestsWithManualPKs(TestCase): class GetOrCreateTestsWithManualPKs(TestCase):
def setUp(self): @classmethod
self.first_pk = ManualPrimaryKeyTest.objects.create(id=1, data="Original") def setUpTestData(cls):
ManualPrimaryKeyTest.objects.create(id=1, data="Original")
def test_create_with_duplicate_primary_key(self): def test_create_with_duplicate_primary_key(self):
""" """

View File

@ -12,7 +12,8 @@ from .models import City
class GeoFeedTest(TestCase): class GeoFeedTest(TestCase):
fixtures = ['initial'] fixtures = ['initial']
def setUp(self): @classmethod
def setUpTestData(cls):
Site(id=settings.SITE_ID, domain="example.com", name="example.com").save() Site(id=settings.SITE_ID, domain="example.com", name="example.com").save()
def assertChildNodes(self, elem, expected): def assertChildNodes(self, elem, expected):

View File

@ -13,8 +13,8 @@ from .models import City, Country
@override_settings(ROOT_URLCONF='gis_tests.geoapp.urls') @override_settings(ROOT_URLCONF='gis_tests.geoapp.urls')
class GeoSitemapTest(TestCase): class GeoSitemapTest(TestCase):
def setUp(self): @classmethod
super().setUp() def setUpTestData(cls):
Site(id=settings.SITE_ID, domain="example.com", name="example.com").save() Site(id=settings.SITE_ID, domain="example.com", name="example.com").save()
def assertChildNodes(self, elem, expected): def assertChildNodes(self, elem, expected):

View File

@ -15,60 +15,61 @@ from .models import (
class LookupTests(TestCase): class LookupTests(TestCase):
def setUp(self): @classmethod
def setUpTestData(cls):
# Create a few Authors. # Create a few Authors.
self.au1 = Author.objects.create(name='Author 1', alias='a1') cls.au1 = Author.objects.create(name='Author 1', alias='a1')
self.au2 = Author.objects.create(name='Author 2', alias='a2') cls.au2 = Author.objects.create(name='Author 2', alias='a2')
# Create a few Articles. # Create a few Articles.
self.a1 = Article.objects.create( cls.a1 = Article.objects.create(
headline='Article 1', headline='Article 1',
pub_date=datetime(2005, 7, 26), pub_date=datetime(2005, 7, 26),
author=self.au1, author=cls.au1,
slug='a1', slug='a1',
) )
self.a2 = Article.objects.create( cls.a2 = Article.objects.create(
headline='Article 2', headline='Article 2',
pub_date=datetime(2005, 7, 27), pub_date=datetime(2005, 7, 27),
author=self.au1, author=cls.au1,
slug='a2', slug='a2',
) )
self.a3 = Article.objects.create( cls.a3 = Article.objects.create(
headline='Article 3', headline='Article 3',
pub_date=datetime(2005, 7, 27), pub_date=datetime(2005, 7, 27),
author=self.au1, author=cls.au1,
slug='a3', slug='a3',
) )
self.a4 = Article.objects.create( cls.a4 = Article.objects.create(
headline='Article 4', headline='Article 4',
pub_date=datetime(2005, 7, 28), pub_date=datetime(2005, 7, 28),
author=self.au1, author=cls.au1,
slug='a4', slug='a4',
) )
self.a5 = Article.objects.create( cls.a5 = Article.objects.create(
headline='Article 5', headline='Article 5',
pub_date=datetime(2005, 8, 1, 9, 0), pub_date=datetime(2005, 8, 1, 9, 0),
author=self.au2, author=cls.au2,
slug='a5', slug='a5',
) )
self.a6 = Article.objects.create( cls.a6 = Article.objects.create(
headline='Article 6', headline='Article 6',
pub_date=datetime(2005, 8, 1, 8, 0), pub_date=datetime(2005, 8, 1, 8, 0),
author=self.au2, author=cls.au2,
slug='a6', slug='a6',
) )
self.a7 = Article.objects.create( cls.a7 = Article.objects.create(
headline='Article 7', headline='Article 7',
pub_date=datetime(2005, 7, 27), pub_date=datetime(2005, 7, 27),
author=self.au2, author=cls.au2,
slug='a7', slug='a7',
) )
# Create a few Tags. # Create a few Tags.
self.t1 = Tag.objects.create(name='Tag 1') cls.t1 = Tag.objects.create(name='Tag 1')
self.t1.articles.add(self.a1, self.a2, self.a3) cls.t1.articles.add(cls.a1, cls.a2, cls.a3)
self.t2 = Tag.objects.create(name='Tag 2') cls.t2 = Tag.objects.create(name='Tag 2')
self.t2.articles.add(self.a3, self.a4, self.a5) cls.t2.articles.add(cls.a3, cls.a4, cls.a5)
self.t3 = Tag.objects.create(name='Tag 3') cls.t3 = Tag.objects.create(name='Tag 3')
self.t3.articles.add(self.a5, self.a6, self.a7) cls.t3.articles.add(cls.a5, cls.a6, cls.a7)
def test_exists(self): def test_exists(self):
# We can use .exists() to check that there are some # We can use .exists() to check that there are some

View File

@ -6,17 +6,18 @@ from .models import Person
class RecursiveM2MTests(TestCase): class RecursiveM2MTests(TestCase):
def setUp(self): @classmethod
self.a, self.b, self.c, self.d = [ def setUpTestData(cls):
cls.a, cls.b, cls.c, cls.d = [
Person.objects.create(name=name) Person.objects.create(name=name)
for name in ["Anne", "Bill", "Chuck", "David"] for name in ["Anne", "Bill", "Chuck", "David"]
] ]
# Anne is friends with Bill and Chuck # 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 # 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): def test_recursive_m2m_all(self):
# Who is friends with Anne? # Who is friends with Anne?

View File

@ -9,6 +9,26 @@ from .models import Car, Part, Person, SportsCar
class ManyToManySignalsTest(TestCase): 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): def m2m_changed_signal_receiver(self, signal, sender, **kwargs):
message = { message = {
'instance': kwargs['instance'], 'instance': kwargs['instance'],
@ -22,24 +42,6 @@ class ManyToManySignalsTest(TestCase):
) )
self.m2m_changed_messages.append(message) 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): def tearDown(self):
# disconnect all signal handlers # disconnect all signal handlers
models.signals.m2m_changed.disconnect( models.signals.m2m_changed.disconnect(

View File

@ -160,18 +160,19 @@ class M2MThroughSerializationTestCase(TestCase):
class ToFieldThroughTests(TestCase): class ToFieldThroughTests(TestCase):
def setUp(self): @classmethod
self.car = Car.objects.create(make="Toyota") def setUpTestData(cls):
self.driver = Driver.objects.create(name="Ryan Briscoe") cls.car = Car.objects.create(make="Toyota")
CarDriver.objects.create(car=self.car, driver=self.driver) 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 # We are testing if wrong objects get deleted due to using wrong
# field value in m2m queries. So, it is essential that the pk # field value in m2m queries. So, it is essential that the pk
# numberings do not match. # numberings do not match.
# Create one intentionally unused driver to mix up the autonumbering # 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. # And two intentionally unused cars.
self.unused_car1 = Car.objects.create(make="Trabant") cls.unused_car1 = Car.objects.create(make="Trabant")
self.unused_car2 = Car.objects.create(make="Wartburg") cls.unused_car2 = Car.objects.create(make="Wartburg")
def test_to_field(self): def test_to_field(self):
self.assertQuerysetEqual( self.assertQuerysetEqual(

View File

@ -5,11 +5,12 @@ from .models import Category, Person
class ManyToOneRecursiveTests(TestCase): class ManyToOneRecursiveTests(TestCase):
def setUp(self): @classmethod
self.r = Category(id=None, name='Root category', parent=None) def setUpTestData(cls):
self.r.save() cls.r = Category(id=None, name='Root category', parent=None)
self.c = Category(id=None, name='Child category', parent=self.r) cls.r.save()
self.c.save() cls.c = Category(id=None, name='Child category', parent=cls.r)
cls.c.save()
def test_m2o_recursive(self): def test_m2o_recursive(self):
self.assertQuerysetEqual(self.r.child_set.all(), self.assertQuerysetEqual(self.r.child_set.all(),
@ -22,13 +23,14 @@ class ManyToOneRecursiveTests(TestCase):
class MultipleManyToOneRecursiveTests(TestCase): class MultipleManyToOneRecursiveTests(TestCase):
def setUp(self): @classmethod
self.dad = Person(full_name='John Smith Senior', mother=None, father=None) def setUpTestData(cls):
self.dad.save() cls.dad = Person(full_name='John Smith Senior', mother=None, father=None)
self.mom = Person(full_name='Jane Smith', mother=None, father=None) cls.dad.save()
self.mom.save() cls.mom = Person(full_name='Jane Smith', mother=None, father=None)
self.kid = Person(full_name='John Smith Junior', mother=self.mom, father=self.dad) cls.mom.save()
self.kid.save() cls.kid = Person(full_name='John Smith Junior', mother=cls.mom, father=cls.dad)
cls.kid.save()
def test_m2o_recursive2(self): def test_m2o_recursive2(self):
self.assertEqual(self.kid.mother.id, self.mom.id) self.assertEqual(self.kid.mother.id, self.mom.id)

View File

@ -82,8 +82,9 @@ class TestMethods(SimpleTestCase):
class TestQuerying(TestCase): class TestQuerying(TestCase):
def setUp(self): @classmethod
self.objs = [ def setUpTestData(cls):
cls.objs = [
NullableUUIDModel.objects.create(field=uuid.uuid4()), NullableUUIDModel.objects.create(field=uuid.uuid4()),
NullableUUIDModel.objects.create(field='550e8400e29b41d4a716446655440000'), NullableUUIDModel.objects.create(field='550e8400e29b41d4a716446655440000'),
NullableUUIDModel.objects.create(field=None), NullableUUIDModel.objects.create(field=None),

View File

@ -832,8 +832,9 @@ class UniqueTest(TestCase):
""" """
unique/unique_together validation. unique/unique_together validation.
""" """
def setUp(self): @classmethod
self.writer = Writer.objects.create(name='Mike Royko') def setUpTestData(cls):
cls.writer = Writer.objects.create(name='Mike Royko')
def test_simple_unique(self): def test_simple_unique(self):
form = ProductForm({'slug': 'teddy-bear-blue'}) form = ProductForm({'slug': 'teddy-bear-blue'})
@ -1587,10 +1588,11 @@ class ModelFormBasicTests(TestCase):
class ModelMultipleChoiceFieldTests(TestCase): class ModelMultipleChoiceFieldTests(TestCase):
def setUp(self): @classmethod
self.c1 = Category.objects.create(name='Entertainment', slug='entertainment', url='entertainment') def setUpTestData(cls):
self.c2 = Category.objects.create(name="It's a test", slug='its-test', url='test') cls.c1 = Category.objects.create(name='Entertainment', slug='entertainment', url='entertainment')
self.c3 = Category.objects.create(name='Third', slug='third-test', url='third') 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): def test_model_multiple_choice_field(self):
f = forms.ModelMultipleChoiceField(Category.objects.all()) f = forms.ModelMultipleChoiceField(Category.objects.all())

View File

@ -81,9 +81,12 @@ class BandAdmin(ModelAdmin):
class ModelAdminTests(TestCase): 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): 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.site = AdminSite()
self.request = MockRequest() self.request = MockRequest()
self.request.user = self.MockAddUser() self.request.user = self.MockAddUser()

View File

@ -25,9 +25,10 @@ from .models import (
# relation such as introduced by one-to-one relations (through multi-table # relation such as introduced by one-to-one relations (through multi-table
# inheritance). # inheritance).
class NestedForeignKeysTests(TestCase): class NestedForeignKeysTests(TestCase):
def setUp(self): @classmethod
self.director = Person.objects.create(name='Terry Gilliam / Terry Jones') def setUpTestData(cls):
self.movie = Movie.objects.create(title='Monty Python and the Holy Grail', director=self.director) 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 # This test failed in #16715 because in some cases INNER JOIN was selected
# for the second foreign key relation instead of LEFT OUTER JOIN. # 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 # 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. # checks if promotion of join types works for deeper nesting too.
class DeeplyNestedForeignKeysTests(TestCase): class DeeplyNestedForeignKeysTests(TestCase):
def setUp(self): @classmethod
self.director = Person.objects.create(name='Terry Gilliam / Terry Jones') def setUpTestData(cls):
self.movie = Movie.objects.create(title='Monty Python and the Holy Grail', director=self.director) 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): def test_inheritance(self):
Event.objects.create() Event.objects.create()

View File

@ -9,14 +9,15 @@ from .models import Article
class OrLookupsTests(TestCase): class OrLookupsTests(TestCase):
def setUp(self): @classmethod
self.a1 = Article.objects.create( def setUpTestData(cls):
cls.a1 = Article.objects.create(
headline='Hello', pub_date=datetime(2005, 11, 27) headline='Hello', pub_date=datetime(2005, 11, 27)
).pk ).pk
self.a2 = Article.objects.create( cls.a2 = Article.objects.create(
headline='Goodbye', pub_date=datetime(2005, 11, 28) headline='Goodbye', pub_date=datetime(2005, 11, 28)
).pk ).pk
self.a3 = Article.objects.create( cls.a3 = Article.objects.create(
headline='Hello and goodbye', pub_date=datetime(2005, 11, 29) headline='Hello and goodbye', pub_date=datetime(2005, 11, 29)
).pk ).pk

View File

@ -309,7 +309,8 @@ class ModelPaginationTests(TestCase):
""" """
Test pagination with Django model instances Test pagination with Django model instances
""" """
def setUp(self): @classmethod
def setUpTestData(cls):
# Prepare a list of objects for pagination. # Prepare a list of objects for pagination.
for x in range(1, 10): for x in range(1, 10):
a = Article(headline='Article %s' % x, pub_date=datetime(2005, 7, 29)) a = Article(headline='Article %s' % x, pub_date=datetime(2005, 7, 29))

View File

@ -138,14 +138,15 @@ class TestSaveLoad(PostgreSQLTestCase):
class TestQuerying(PostgreSQLTestCase): class TestQuerying(PostgreSQLTestCase):
def setUp(self): @classmethod
self.objs = [ def setUpTestData(cls):
NullableIntegerArrayModel.objects.create(field=[1]), cls.objs = NullableIntegerArrayModel.objects.bulk_create([
NullableIntegerArrayModel.objects.create(field=[2]), NullableIntegerArrayModel(field=[1]),
NullableIntegerArrayModel.objects.create(field=[2, 3]), NullableIntegerArrayModel(field=[2]),
NullableIntegerArrayModel.objects.create(field=[20, 30, 40]), NullableIntegerArrayModel(field=[2, 3]),
NullableIntegerArrayModel.objects.create(field=None), NullableIntegerArrayModel(field=[20, 30, 40]),
] NullableIntegerArrayModel(field=None),
])
def test_exact(self): def test_exact(self):
self.assertSequenceEqual( self.assertSequenceEqual(
@ -368,16 +369,17 @@ class TestQuerying(PostgreSQLTestCase):
class TestDateTimeExactQuerying(PostgreSQLTestCase): class TestDateTimeExactQuerying(PostgreSQLTestCase):
def setUp(self): @classmethod
def setUpTestData(cls):
now = timezone.now() now = timezone.now()
self.datetimes = [now] cls.datetimes = [now]
self.dates = [now.date()] cls.dates = [now.date()]
self.times = [now.time()] cls.times = [now.time()]
self.objs = [ cls.objs = [
DateTimeArrayModel.objects.create( DateTimeArrayModel.objects.create(
datetimes=self.datetimes, datetimes=cls.datetimes,
dates=self.dates, dates=cls.dates,
times=self.times, times=cls.times,
) )
] ]
@ -402,17 +404,18 @@ class TestDateTimeExactQuerying(PostgreSQLTestCase):
class TestOtherTypesExactQuerying(PostgreSQLTestCase): class TestOtherTypesExactQuerying(PostgreSQLTestCase):
def setUp(self): @classmethod
self.ips = ['192.168.0.1', '::1'] def setUpTestData(cls):
self.uuids = [uuid.uuid4()] cls.ips = ['192.168.0.1', '::1']
self.decimals = [decimal.Decimal(1.25), 1.75] cls.uuids = [uuid.uuid4()]
self.tags = [Tag(1), Tag(2), Tag(3)] cls.decimals = [decimal.Decimal(1.25), 1.75]
self.objs = [ cls.tags = [Tag(1), Tag(2), Tag(3)]
cls.objs = [
OtherTypesArrayModel.objects.create( OtherTypesArrayModel.objects.create(
ips=self.ips, ips=cls.ips,
uuids=self.uuids, uuids=cls.uuids,
decimals=self.decimals, decimals=cls.decimals,
tags=self.tags, tags=cls.tags,
) )
] ]

View File

@ -66,14 +66,15 @@ class SimpleTests(PostgreSQLTestCase):
class TestQuerying(PostgreSQLTestCase): class TestQuerying(PostgreSQLTestCase):
def setUp(self): @classmethod
self.objs = [ def setUpTestData(cls):
HStoreModel.objects.create(field={'a': 'b'}), cls.objs = HStoreModel.objects.bulk_create([
HStoreModel.objects.create(field={'a': 'b', 'c': 'd'}), HStoreModel(field={'a': 'b'}),
HStoreModel.objects.create(field={'c': 'd'}), HStoreModel(field={'a': 'b', 'c': 'd'}),
HStoreModel.objects.create(field={}), HStoreModel(field={'c': 'd'}),
HStoreModel.objects.create(field=None), HStoreModel(field={}),
] HStoreModel(field=None),
])
def test_exact(self): def test_exact(self):
self.assertSequenceEqual( self.assertSequenceEqual(

View File

@ -10,11 +10,12 @@ class UnaccentTest(PostgreSQLTestCase):
Model = CharFieldModel Model = CharFieldModel
def setUp(self): @classmethod
self.Model.objects.bulk_create([ def setUpTestData(cls):
self.Model(field="àéÖ"), cls.Model.objects.bulk_create([
self.Model(field="aeO"), cls.Model(field="àéÖ"),
self.Model(field="aeo"), cls.Model(field="aeO"),
cls.Model(field="aeo"),
]) ])
def test_unaccent(self): def test_unaccent(self):

View File

@ -5,9 +5,10 @@ from .models import Person
class PropertyTests(TestCase): class PropertyTests(TestCase):
def setUp(self): @classmethod
self.a = Person(first_name='John', last_name='Lennon') def setUpTestData(cls):
self.a.save() cls.a = Person(first_name='John', last_name='Lennon')
cls.a.save()
def test_getter(self): def test_getter(self):
self.assertEqual(self.a.full_name, 'John Lennon') self.assertEqual(self.a.full_name, 'John Lennon')

View File

@ -9,7 +9,8 @@ from .models import Container, Event, Group, Happening, M2MModel
class PickleabilityTestCase(TestCase): class PickleabilityTestCase(TestCase):
def setUp(self): @classmethod
def setUpTestData(cls):
Happening.objects.create() # make sure the defaults are working (#20158) Happening.objects.create() # make sure the defaults are working (#20158)
def assert_pickles(self, qs): def assert_pickles(self, qs):

View File

@ -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) @override_settings(APPEND_SLASH=False, ROOT_URLCONF='redirects_tests.urls', SITE_ID=1)
class RedirectTests(TestCase): class RedirectTests(TestCase):
def setUp(self): @classmethod
self.site = Site.objects.get(pk=settings.SITE_ID) def setUpTestData(cls):
cls.site = Site.objects.get(pk=settings.SITE_ID)
def test_model(self): def test_model(self):
r1 = Redirect.objects.create(site=self.site, old_path='/initial', new_path='/new_target') 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) @override_settings(SITE_ID=1)
class OverriddenRedirectMiddlewareTests(TestCase): class OverriddenRedirectMiddlewareTests(TestCase):
def setUp(self): @classmethod
self.site = Site.objects.get(pk=settings.SITE_ID) def setUpTestData(cls):
cls.site = Site.objects.get(pk=settings.SITE_ID)
def test_response_gone_class(self): def test_response_gone_class(self):
Redirect.objects.create(site=self.site, old_path='/initial/', new_path='') Redirect.objects.create(site=self.site, old_path='/initial/', new_path='')

View File

@ -6,7 +6,8 @@ from .models import Choice, Poll, User
class ReverseLookupTests(TestCase): class ReverseLookupTests(TestCase):
def setUp(self): @classmethod
def setUpTestData(cls):
john = User.objects.create(name="John Doe") john = User.objects.create(name="John Doe")
jim = User.objects.create(name="Jim Bo") jim = User.objects.create(name="Jim Bo")
first_poll = Poll.objects.create( first_poll = Poll.objects.create(

View File

@ -10,7 +10,8 @@ from .models import (
class ReverseSelectRelatedTestCase(TestCase): class ReverseSelectRelatedTestCase(TestCase):
def setUp(self): @classmethod
def setUpTestData(cls):
user = User.objects.create(username="test") user = User.objects.create(username="test")
UserProfile.objects.create(user=user, state="KS", city="Lawrence") UserProfile.objects.create(user=user, state="KS", city="Lawrence")
results = UserStatResult.objects.create(results='first results') results = UserStatResult.objects.create(results='first results')

View File

@ -13,12 +13,15 @@ class SitemapTestsBase(TestCase):
sites_installed = apps.is_installed('django.contrib.sites') sites_installed = apps.is_installed('django.contrib.sites')
domain = 'example.com' if sites_installed else 'testserver' 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): def setUp(self):
self.base_url = '%s://%s' % (self.protocol, self.domain) self.base_url = '%s://%s' % (self.protocol, self.domain)
cache.clear() cache.clear()
# Create an object for sitemap content.
TestModel.objects.create(name='Test Object')
self.i18n_model = I18nTestModel.objects.create(name='Test Object')
@classmethod @classmethod
def setUpClass(cls): def setUpClass(cls):

View File

@ -10,7 +10,8 @@ from .models import CustomArticle, ExclusiveArticle, SyndicatedArticle
class SitesFrameworkTestCase(TestCase): 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.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") Site.objects.create(id=settings.SITE_ID + 1, domain="example2.com", name="example2.com")

View File

@ -20,13 +20,14 @@ from django.test.utils import captured_stdout
class SitesFrameworkTests(TestCase): class SitesFrameworkTests(TestCase):
multi_db = True multi_db = True
def setUp(self): @classmethod
self.site = Site( def setUpTestData(cls):
cls.site = Site(
id=settings.SITE_ID, id=settings.SITE_ID,
domain="example.com", domain="example.com",
name="example.com", name="example.com",
) )
self.site.save() cls.site.save()
def tearDown(self): def tearDown(self):
Site.objects.clear_cache() Site.objects.clear_cache()
@ -241,11 +242,14 @@ class JustOtherRouter:
class CreateDefaultSiteTests(TestCase): class CreateDefaultSiteTests(TestCase):
multi_db = True multi_db = True
def setUp(self): @classmethod
self.app_config = apps.get_app_config('sites') def setUpTestData(cls):
# Delete the site created as part of the default migration process. # Delete the site created as part of the default migration process.
Site.objects.all().delete() Site.objects.all().delete()
def setUp(self):
self.app_config = apps.get_app_config('sites')
def test_basic(self): def test_basic(self):
""" """
#15346, #15573 - create_default_site() creates an example site only if #15346, #15573 - create_default_site() creates an example site only if

View File

@ -185,9 +185,10 @@ class AssertNumQueriesUponConnectionTests(TransactionTestCase):
class AssertQuerysetEqualTests(TestCase): class AssertQuerysetEqualTests(TestCase):
def setUp(self): @classmethod
self.p1 = Person.objects.create(name='p1') def setUpTestData(cls):
self.p2 = Person.objects.create(name='p2') cls.p1 = Person.objects.create(name='p1')
cls.p2 = Person.objects.create(name='p2')
def test_ordered(self): def test_ordered(self):
self.assertQuerysetEqual( self.assertQuerysetEqual(
@ -255,8 +256,9 @@ class AssertQuerysetEqualTests(TestCase):
@override_settings(ROOT_URLCONF='test_utils.urls') @override_settings(ROOT_URLCONF='test_utils.urls')
class CaptureQueriesContextManagerTests(TestCase): class CaptureQueriesContextManagerTests(TestCase):
def setUp(self): @classmethod
self.person_pk = str(Person.objects.create(name='test').pk) def setUpTestData(cls):
cls.person_pk = str(Person.objects.create(name='test').pk)
def test_simple(self): def test_simple(self):
with CaptureQueriesContext(connection) as captured_queries: with CaptureQueriesContext(connection) as captured_queries:

View File

@ -6,12 +6,13 @@ from .models import A, B, Bar, D, DataPoint, Foo, RelatedPoint
class SimpleTest(TestCase): class SimpleTest(TestCase):
def setUp(self): @classmethod
self.a1 = A.objects.create() def setUpTestData(cls):
self.a2 = A.objects.create() cls.a1 = A.objects.create()
cls.a2 = A.objects.create()
for x in range(20): for x in range(20):
B.objects.create(a=self.a1) B.objects.create(a=cls.a1)
D.objects.create(a=self.a1) D.objects.create(a=cls.a1)
def test_nonempty_update(self): def test_nonempty_update(self):
""" """
@ -62,11 +63,12 @@ class SimpleTest(TestCase):
class AdvancedTests(TestCase): class AdvancedTests(TestCase):
def setUp(self): @classmethod
self.d0 = DataPoint.objects.create(name="d0", value="apple") def setUpTestData(cls):
self.d2 = DataPoint.objects.create(name="d2", value="banana") cls.d0 = DataPoint.objects.create(name="d0", value="apple")
self.d3 = DataPoint.objects.create(name="d3", value="banana") cls.d2 = DataPoint.objects.create(name="d2", value="banana")
self.r1 = RelatedPoint.objects.create(name="r1", data=self.d3) cls.d3 = DataPoint.objects.create(name="d3", value="banana")
cls.r1 = RelatedPoint.objects.create(name="r1", data=cls.d3)
def test_update(self): def test_update(self):
""" """

View File

@ -83,8 +83,9 @@ class ArticleForm(forms.ModelForm):
class ModelFormsTests(TestCase): class ModelFormsTests(TestCase):
def setUp(self): @classmethod
self.author = Author.objects.create(name='Joseph Kocherhans') def setUpTestData(cls):
cls.author = Author.objects.create(name='Joseph Kocherhans')
def test_partial_validation(self): def test_partial_validation(self):
# Make sure the "commit=False and set field values later" idiom still # Make sure the "commit=False and set field values later" idiom still