Switched TestCase to SimpleTestCase where possible in Django's tests.

This commit is contained in:
Tim Graham 2018-11-26 14:05:02 -05:00
parent f091ea3515
commit 193c109327
37 changed files with 130 additions and 134 deletions

View File

@ -4,11 +4,11 @@ from django.contrib.admindocs.utils import (
docutils_is_available, parse_docstring, parse_rst, trim_docstring, docutils_is_available, parse_docstring, parse_rst, trim_docstring,
) )
from .tests import AdminDocsTestCase from .tests import AdminDocsSimpleTestCase
@unittest.skipUnless(docutils_is_available, "no docutils installed.") @unittest.skipUnless(docutils_is_available, "no docutils installed.")
class TestUtils(AdminDocsTestCase): class TestUtils(AdminDocsSimpleTestCase):
""" """
This __doc__ output is required for testing. I copied this example from This __doc__ output is required for testing. I copied this example from
`admindocs` documentation. (TITLE) `admindocs` documentation. (TITLE)

View File

@ -1,5 +1,7 @@
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.test import TestCase, modify_settings, override_settings from django.test import (
SimpleTestCase, TestCase, modify_settings, override_settings,
)
class TestDataMixin: class TestDataMixin:
@ -9,6 +11,12 @@ class TestDataMixin:
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')
@override_settings(ROOT_URLCONF='admin_docs.urls')
@modify_settings(INSTALLED_APPS={'append': 'django.contrib.admindocs'})
class AdminDocsSimpleTestCase(SimpleTestCase):
pass
@override_settings(ROOT_URLCONF='admin_docs.urls') @override_settings(ROOT_URLCONF='admin_docs.urls')
@modify_settings(INSTALLED_APPS={'append': 'django.contrib.admindocs'}) @modify_settings(INSTALLED_APPS={'append': 'django.contrib.admindocs'})
class AdminDocsTestCase(TestCase): class AdminDocsTestCase(TestCase):

View File

@ -7,7 +7,7 @@ from django.contrib.auth.mixins import (
from django.contrib.auth.models import AnonymousUser from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import PermissionDenied from django.core.exceptions import PermissionDenied
from django.http import HttpResponse from django.http import HttpResponse
from django.test import RequestFactory, TestCase from django.test import RequestFactory, SimpleTestCase, TestCase
from django.views.generic import View from django.views.generic import View
@ -111,7 +111,7 @@ class AccessMixinTests(TestCase):
view(request) view(request)
class UserPassesTestTests(TestCase): class UserPassesTestTests(SimpleTestCase):
factory = RequestFactory() factory = RequestFactory()

View File

@ -156,7 +156,7 @@ class UserManagerTestCase(TestCase):
self.assertIn(char, allowed_chars) self.assertIn(char, allowed_chars)
class AbstractBaseUserTests(TestCase): class AbstractBaseUserTests(SimpleTestCase):
def test_has_usable_password(self): def test_has_usable_password(self):
""" """

View File

@ -11,7 +11,7 @@ from django.contrib.auth.password_validation import (
) )
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.db import models from django.db import models
from django.test import TestCase, override_settings from django.test import SimpleTestCase, TestCase, override_settings
from django.test.utils import isolate_apps from django.test.utils import isolate_apps
from django.utils.html import conditional_escape from django.utils.html import conditional_escape
@ -22,7 +22,7 @@ from django.utils.html import conditional_escape
'min_length': 12, 'min_length': 12,
}}, }},
]) ])
class PasswordValidationTest(TestCase): class PasswordValidationTest(SimpleTestCase):
def test_get_default_password_validators(self): def test_get_default_password_validators(self):
validators = get_default_password_validators() validators = get_default_password_validators()
self.assertEqual(len(validators), 2) self.assertEqual(len(validators), 2)
@ -95,7 +95,7 @@ class PasswordValidationTest(TestCase):
self.assertEqual(password_validators_help_text_html(), '') self.assertEqual(password_validators_help_text_html(), '')
class MinimumLengthValidatorTest(TestCase): class MinimumLengthValidatorTest(SimpleTestCase):
def test_validate(self): def test_validate(self):
expected_error = "This password is too short. It must contain at least %d characters." expected_error = "This password is too short. It must contain at least %d characters."
self.assertIsNone(MinimumLengthValidator().validate('12345678')) self.assertIsNone(MinimumLengthValidator().validate('12345678'))
@ -182,7 +182,7 @@ class UserAttributeSimilarityValidatorTest(TestCase):
) )
class CommonPasswordValidatorTest(TestCase): class CommonPasswordValidatorTest(SimpleTestCase):
def test_validate(self): def test_validate(self):
expected_error = "This password is too common." expected_error = "This password is too common."
self.assertIsNone(CommonPasswordValidator().validate('a-safe-password')) self.assertIsNone(CommonPasswordValidator().validate('a-safe-password'))
@ -214,7 +214,7 @@ class CommonPasswordValidatorTest(TestCase):
) )
class NumericPasswordValidatorTest(TestCase): class NumericPasswordValidatorTest(SimpleTestCase):
def test_validate(self): def test_validate(self):
expected_error = "This password is entirely numeric." expected_error = "This password is entirely numeric."
self.assertIsNone(NumericPasswordValidator().validate('a-safe-password')) self.assertIsNone(NumericPasswordValidator().validate('a-safe-password'))
@ -231,7 +231,7 @@ class NumericPasswordValidatorTest(TestCase):
) )
class UsernameValidatorsTests(TestCase): class UsernameValidatorsTests(SimpleTestCase):
def test_unicode_validator(self): def test_unicode_validator(self):
valid_usernames = ['joe', 'René', 'ᴮᴵᴳᴮᴵᴿᴰ', 'أحمد'] valid_usernames = ['joe', 'René', 'ᴮᴵᴳᴮᴵᴿᴰ', 'أحمد']
invalid_usernames = [ invalid_usernames = [

View File

@ -1,8 +1,8 @@
from django.db import connection from django.db import connection
from django.test import TestCase from django.test import SimpleTestCase
class TestDatabaseFeatures(TestCase): class TestDatabaseFeatures(SimpleTestCase):
def test_nonexistent_feature(self): def test_nonexistent_feature(self):
self.assertFalse(hasattr(connection.features, 'nonexistent')) self.assertFalse(hasattr(connection.features, 'nonexistent'))

View File

@ -1785,7 +1785,7 @@ class CacheHEADTest(SimpleTestCase):
('es', 'Spanish'), ('es', 'Spanish'),
], ],
) )
class CacheI18nTest(TestCase): class CacheI18nTest(SimpleTestCase):
def setUp(self): def setUp(self):
self.path = '/cache/test/' self.path = '/cache/test/'

View File

@ -1,7 +1,7 @@
from unittest import mock from unittest import mock
from django.db import connections, models from django.db import connections, models
from django.test import TestCase from django.test import SimpleTestCase
from django.test.utils import isolate_apps, override_settings from django.test.utils import isolate_apps, override_settings
@ -15,8 +15,7 @@ class TestRouter:
@override_settings(DATABASE_ROUTERS=[TestRouter()]) @override_settings(DATABASE_ROUTERS=[TestRouter()])
@isolate_apps('check_framework') @isolate_apps('check_framework')
class TestMultiDBChecks(TestCase): class TestMultiDBChecks(SimpleTestCase):
multi_db = True
def _patch_check_field_on(self, db): def _patch_check_field_on(self, db):
return mock.patch.object(connections[db].validation, 'check_field') return mock.patch.object(connections[db].validation, 'check_field')

View File

@ -4,7 +4,7 @@ from datetime import date, datetime
from django.core.exceptions import FieldError from django.core.exceptions import FieldError
from django.db import connection, models from django.db import connection, models
from django.test import TestCase, override_settings from django.test import SimpleTestCase, TestCase, override_settings
from django.test.utils import register_lookup from django.test.utils import register_lookup
from django.utils import timezone from django.utils import timezone
@ -513,7 +513,7 @@ class TrackCallsYearTransform(YearTransform):
return super().get_transform(lookup_name) return super().get_transform(lookup_name)
class LookupTransformCallOrderTests(TestCase): class LookupTransformCallOrderTests(SimpleTestCase):
def test_call_order(self): def test_call_order(self):
with register_lookup(models.DateField, TrackCallsYearTransform): with register_lookup(models.DateField, TrackCallsYearTransform):
# junk lookup - tries lookup, then transform, then fails # junk lookup - tries lookup, then transform, then fails
@ -540,7 +540,7 @@ class LookupTransformCallOrderTests(TestCase):
['lookup']) ['lookup'])
class CustomisedMethodsTests(TestCase): class CustomisedMethodsTests(SimpleTestCase):
def test_overridden_get_lookup(self): def test_overridden_get_lookup(self):
q = CustomModel.objects.filter(field__lookupfunc_monkeys=3) q = CustomModel.objects.filter(field__lookupfunc_monkeys=3)

View File

@ -1437,7 +1437,7 @@ class FieldTransformTests(TestCase):
) )
class ReprTests(TestCase): class ReprTests(SimpleTestCase):
def test_expressions(self): def test_expressions(self):
self.assertEqual( self.assertEqual(

View File

@ -2,7 +2,7 @@ import unittest
from django.core.checks import Error, Warning as DjangoWarning from django.core.checks import Error, Warning as DjangoWarning
from django.db import connection, models from django.db import connection, models
from django.test import SimpleTestCase, TestCase, skipIfDBFeature from django.test import SimpleTestCase, skipIfDBFeature
from django.test.utils import isolate_apps, override_settings from django.test.utils import isolate_apps, override_settings
from django.utils.functional import lazy from django.utils.functional import lazy
from django.utils.timezone import now from django.utils.timezone import now
@ -40,7 +40,7 @@ class AutoFieldTests(SimpleTestCase):
@isolate_apps('invalid_models_tests') @isolate_apps('invalid_models_tests')
class CharFieldTests(TestCase): class CharFieldTests(SimpleTestCase):
def test_valid_field(self): def test_valid_field(self):
class Model(models.Model): class Model(models.Model):
@ -312,7 +312,7 @@ class CharFieldTests(TestCase):
@isolate_apps('invalid_models_tests') @isolate_apps('invalid_models_tests')
class DateFieldTests(TestCase): class DateFieldTests(SimpleTestCase):
maxDiff = None maxDiff = None
def test_auto_now_and_auto_now_add_raise_error(self): def test_auto_now_and_auto_now_add_raise_error(self):
@ -375,7 +375,7 @@ class DateFieldTests(TestCase):
@isolate_apps('invalid_models_tests') @isolate_apps('invalid_models_tests')
class DateTimeFieldTests(TestCase): class DateTimeFieldTests(SimpleTestCase):
maxDiff = None maxDiff = None
def test_fix_default_value(self): def test_fix_default_value(self):
@ -638,7 +638,7 @@ class IntegerFieldTests(SimpleTestCase):
@isolate_apps('invalid_models_tests') @isolate_apps('invalid_models_tests')
class TimeFieldTests(TestCase): class TimeFieldTests(SimpleTestCase):
maxDiff = None maxDiff = None
def test_fix_default_value(self): def test_fix_default_value(self):
@ -680,7 +680,7 @@ class TimeFieldTests(TestCase):
@isolate_apps('invalid_models_tests') @isolate_apps('invalid_models_tests')
class TextFieldTests(TestCase): class TextFieldTests(SimpleTestCase):
@skipIfDBFeature('supports_index_on_text_field') @skipIfDBFeature('supports_index_on_text_field')
def test_max_length_warning(self): def test_max_length_warning(self):

View File

@ -1,6 +1,6 @@
from django.db import models from django.db import models
from django.template import Context, Template from django.template import Context, Template
from django.test import TestCase, override_settings from django.test import SimpleTestCase, TestCase, override_settings
from django.test.utils import isolate_apps from django.test.utils import isolate_apps
from .models import ( from .models import (
@ -160,7 +160,7 @@ class ManagersRegressionTests(TestCase):
@isolate_apps('managers_regress') @isolate_apps('managers_regress')
class TestManagerInheritance(TestCase): class TestManagerInheritance(SimpleTestCase):
def test_implicit_inheritance(self): def test_implicit_inheritance(self):
class CustomManager(models.Manager): class CustomManager(models.Manager):
pass pass

View File

@ -8,7 +8,7 @@ from django.db.migrations.graph import MigrationGraph
from django.db.migrations.recorder import MigrationRecorder from django.db.migrations.recorder import MigrationRecorder
from django.db.utils import DatabaseError from django.db.utils import DatabaseError
from django.test import ( from django.test import (
TestCase, modify_settings, override_settings, skipUnlessDBFeature, SimpleTestCase, modify_settings, override_settings, skipUnlessDBFeature,
) )
from .test_base import MigrationTestBase from .test_base import MigrationTestBase
@ -685,7 +685,7 @@ class FakeMigration:
return 'M<%s>' % self.name return 'M<%s>' % self.name
class ExecutorUnitTests(TestCase): class ExecutorUnitTests(SimpleTestCase):
"""(More) isolated unit tests for executor methods.""" """(More) isolated unit tests for executor methods."""
def test_minimize_rollbacks(self): def test_minimize_rollbacks(self):
""" """

View File

@ -15,7 +15,7 @@ class Nested:
pass pass
class BasicFieldTests(TestCase): class BasicFieldTests(SimpleTestCase):
def test_show_hidden_initial(self): def test_show_hidden_initial(self):
""" """

View File

@ -2849,7 +2849,7 @@ class CustomMetaclassTestCase(SimpleTestCase):
self.assertEqual(new_cls.base_fields, {}) self.assertEqual(new_cls.base_fields, {})
class StrictAssignmentTests(TestCase): class StrictAssignmentTests(SimpleTestCase):
""" """
Should a model do anything special with __setattr__() or descriptors which Should a model do anything special with __setattr__() or descriptors which
raise a ValidationError, a model form should catch the error (#24706). raise a ValidationError, a model form should catch the error (#24706).

View File

@ -5,12 +5,12 @@ from django.contrib.contenttypes.models import ContentType
from django.core.checks import Error from django.core.checks import Error
from django.core.exceptions import FieldDoesNotExist, FieldError from django.core.exceptions import FieldDoesNotExist, FieldError
from django.db import models from django.db import models
from django.test import TestCase from django.test import SimpleTestCase
from django.test.utils import isolate_apps from django.test.utils import isolate_apps
@isolate_apps('model_inheritance') @isolate_apps('model_inheritance')
class AbstractInheritanceTests(TestCase): class AbstractInheritanceTests(SimpleTestCase):
def test_single_parent(self): def test_single_parent(self):
class AbstractBase(models.Model): class AbstractBase(models.Model):
name = models.CharField(max_length=30) name = models.CharField(max_length=30)

View File

@ -1,11 +1,11 @@
import pickle import pickle
from django.db import DJANGO_VERSION_PICKLE_KEY, models from django.db import DJANGO_VERSION_PICKLE_KEY, models
from django.test import TestCase from django.test import SimpleTestCase
from django.utils.version import get_version from django.utils.version import get_version
class ModelPickleTestCase(TestCase): class ModelPickleTests(SimpleTestCase):
def test_missing_django_version_unpickling(self): def test_missing_django_version_unpickling(self):
""" """
#21430 -- Verifies a warning is raised for models that are #21430 -- Verifies a warning is raised for models that are

View File

@ -2091,7 +2091,7 @@ class NoRelationRouter:
@override_settings(DATABASE_ROUTERS=[NoRelationRouter()]) @override_settings(DATABASE_ROUTERS=[NoRelationRouter()])
class RelationAssignmentTests(TestCase): class RelationAssignmentTests(SimpleTestCase):
"""allow_relation() is called with unsaved model instances.""" """allow_relation() is called with unsaved model instances."""
multi_db = True multi_db = True
router_prevents_msg = 'the current database router prevents this relation' router_prevents_msg = 'the current database router prevents this relation'

View File

@ -1,7 +1,7 @@
from operator import attrgetter from operator import attrgetter
from django.db import models from django.db import models
from django.test import TestCase from django.test import SimpleTestCase, TestCase
from django.test.utils import isolate_apps from django.test.utils import isolate_apps
from .base_tests import BaseOrderWithRespectToTests from .base_tests import BaseOrderWithRespectToTests
@ -14,7 +14,7 @@ class OrderWithRespectToBaseTests(BaseOrderWithRespectToTests, TestCase):
Question = Question Question = Question
class OrderWithRespectToTests(TestCase): class OrderWithRespectToTests(SimpleTestCase):
@isolate_apps('order_with_respect_to') @isolate_apps('order_with_respect_to')
def test_duplicate_order_field(self): def test_duplicate_order_field(self):

View File

@ -3,7 +3,12 @@ import unittest
from forms_tests.widget_tests.base import WidgetTest from forms_tests.widget_tests.base import WidgetTest
from django.db import connection from django.db import connection
from django.test import TestCase, modify_settings from django.test import SimpleTestCase, TestCase, modify_settings
@unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific tests")
class PostgreSQLSimpleTestCase(SimpleTestCase):
pass
@unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific tests") @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific tests")
@ -14,5 +19,5 @@ class PostgreSQLTestCase(TestCase):
@unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific tests") @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific tests")
# To locate the widget's template. # To locate the widget's template.
@modify_settings(INSTALLED_APPS={'append': 'django.contrib.postgres'}) @modify_settings(INSTALLED_APPS={'append': 'django.contrib.postgres'})
class PostgreSQLWidgetTestCase(WidgetTest, PostgreSQLTestCase): class PostgreSQLWidgetTestCase(WidgetTest, PostgreSQLSimpleTestCase):
pass pass

View File

@ -12,7 +12,9 @@ from django.test import TransactionTestCase, modify_settings, override_settings
from django.test.utils import isolate_apps from django.test.utils import isolate_apps
from django.utils import timezone from django.utils import timezone
from . import PostgreSQLTestCase, PostgreSQLWidgetTestCase from . import (
PostgreSQLSimpleTestCase, PostgreSQLTestCase, PostgreSQLWidgetTestCase,
)
from .models import ( from .models import (
ArrayFieldSubclass, CharArrayModel, DateTimeArrayModel, IntegerArrayModel, ArrayFieldSubclass, CharArrayModel, DateTimeArrayModel, IntegerArrayModel,
NestedIntegerArrayModel, NullableIntegerArrayModel, OtherTypesArrayModel, NestedIntegerArrayModel, NullableIntegerArrayModel, OtherTypesArrayModel,
@ -440,7 +442,7 @@ class TestOtherTypesExactQuerying(PostgreSQLTestCase):
@isolate_apps('postgres_tests') @isolate_apps('postgres_tests')
class TestChecks(PostgreSQLTestCase): class TestChecks(PostgreSQLSimpleTestCase):
def test_field_checks(self): def test_field_checks(self):
class MyModel(PostgreSQLModel): class MyModel(PostgreSQLModel):
@ -589,7 +591,7 @@ class TestMigrations(TransactionTestCase):
self.assertNotIn(table_name, connection.introspection.table_names(cursor)) self.assertNotIn(table_name, connection.introspection.table_names(cursor))
class TestSerialization(PostgreSQLTestCase): class TestSerialization(PostgreSQLSimpleTestCase):
test_data = ( test_data = (
'[{"fields": {"field": "[\\"1\\", \\"2\\", null]"}, "model": "postgres_tests.integerarraymodel", "pk": null}]' '[{"fields": {"field": "[\\"1\\", \\"2\\", null]"}, "model": "postgres_tests.integerarraymodel", "pk": null}]'
) )
@ -604,7 +606,7 @@ class TestSerialization(PostgreSQLTestCase):
self.assertEqual(instance.field, [1, 2, None]) self.assertEqual(instance.field, [1, 2, None])
class TestValidation(PostgreSQLTestCase): class TestValidation(PostgreSQLSimpleTestCase):
def test_unbounded(self): def test_unbounded(self):
field = ArrayField(models.IntegerField()) field = ArrayField(models.IntegerField())
@ -664,7 +666,7 @@ class TestValidation(PostgreSQLTestCase):
self.assertEqual(exception.params, {'nth': 1, 'value': 0, 'limit_value': 1, 'show_value': 0}) self.assertEqual(exception.params, {'nth': 1, 'value': 0, 'limit_value': 1, 'show_value': 0})
class TestSimpleFormField(PostgreSQLTestCase): class TestSimpleFormField(PostgreSQLSimpleTestCase):
def test_valid(self): def test_valid(self):
field = SimpleArrayField(forms.CharField()) field = SimpleArrayField(forms.CharField())
@ -782,7 +784,7 @@ class TestSimpleFormField(PostgreSQLTestCase):
self.assertIs(field.has_changed([], ''), False) self.assertIs(field.has_changed([], ''), False)
class TestSplitFormField(PostgreSQLTestCase): class TestSplitFormField(PostgreSQLSimpleTestCase):
def test_valid(self): def test_valid(self):
class SplitForm(forms.Form): class SplitForm(forms.Form):

View File

@ -2,9 +2,9 @@ import json
from django.core import checks, exceptions, serializers from django.core import checks, exceptions, serializers
from django.forms import Form from django.forms import Form
from django.test.utils import isolate_apps, modify_settings from django.test.utils import isolate_apps
from . import PostgreSQLTestCase from . import PostgreSQLSimpleTestCase, PostgreSQLTestCase
from .models import HStoreModel, PostgreSQLModel from .models import HStoreModel, PostgreSQLModel
try: try:
@ -15,12 +15,7 @@ except ImportError:
pass pass
@modify_settings(INSTALLED_APPS={'append': 'django.contrib.postgres'}) class SimpleTests(PostgreSQLTestCase):
class HStoreTestCase(PostgreSQLTestCase):
pass
class SimpleTests(HStoreTestCase):
def test_save_load_success(self): def test_save_load_success(self):
value = {'a': 'b'} value = {'a': 'b'}
instance = HStoreModel(field=value) instance = HStoreModel(field=value)
@ -69,7 +64,7 @@ class SimpleTests(HStoreTestCase):
self.assertEqual(instance.array_field, expected_value) self.assertEqual(instance.array_field, expected_value)
class TestQuerying(HStoreTestCase): class TestQuerying(PostgreSQLTestCase):
def setUp(self): def setUp(self):
self.objs = [ self.objs = [
@ -191,7 +186,7 @@ class TestQuerying(HStoreTestCase):
@isolate_apps('postgres_tests') @isolate_apps('postgres_tests')
class TestChecks(PostgreSQLTestCase): class TestChecks(PostgreSQLSimpleTestCase):
def test_invalid_default(self): def test_invalid_default(self):
class MyModel(PostgreSQLModel): class MyModel(PostgreSQLModel):
@ -218,7 +213,7 @@ class TestChecks(PostgreSQLTestCase):
self.assertEqual(MyModel().check(), []) self.assertEqual(MyModel().check(), [])
class TestSerialization(HStoreTestCase): class TestSerialization(PostgreSQLSimpleTestCase):
test_data = json.dumps([{ test_data = json.dumps([{
'model': 'postgres_tests.hstoremodel', 'model': 'postgres_tests.hstoremodel',
'pk': None, 'pk': None,
@ -248,7 +243,7 @@ class TestSerialization(HStoreTestCase):
self.assertEqual(instance.field, new_instance.field) self.assertEqual(instance.field, new_instance.field)
class TestValidation(HStoreTestCase): class TestValidation(PostgreSQLSimpleTestCase):
def test_not_a_string(self): def test_not_a_string(self):
field = HStoreField() field = HStoreField()
@ -262,7 +257,7 @@ class TestValidation(HStoreTestCase):
self.assertEqual(field.clean({'a': None}, None), {'a': None}) self.assertEqual(field.clean({'a': None}, None), {'a': None})
class TestFormField(HStoreTestCase): class TestFormField(PostgreSQLSimpleTestCase):
def test_valid(self): def test_valid(self):
field = forms.HStoreField() field = forms.HStoreField()
@ -325,7 +320,7 @@ class TestFormField(HStoreTestCase):
self.assertTrue(form_w_hstore.has_changed()) self.assertTrue(form_w_hstore.has_changed())
class TestValidator(HStoreTestCase): class TestValidator(PostgreSQLSimpleTestCase):
def test_simple_valid(self): def test_simple_valid(self):
validator = KeysValidator(keys=['a', 'b']) validator = KeysValidator(keys=['a', 'b'])

View File

@ -11,7 +11,7 @@ from django.db.utils import NotSupportedError
from django.test import skipUnlessDBFeature from django.test import skipUnlessDBFeature
from django.test.utils import register_lookup from django.test.utils import register_lookup
from . import PostgreSQLTestCase from . import PostgreSQLSimpleTestCase, PostgreSQLTestCase
from .models import CharFieldModel, IntegerArrayModel from .models import CharFieldModel, IntegerArrayModel
@ -31,7 +31,7 @@ class IndexTestMixin:
@skipUnlessDBFeature('has_brin_index_support') @skipUnlessDBFeature('has_brin_index_support')
class BrinIndexTests(IndexTestMixin, PostgreSQLTestCase): class BrinIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase):
index_class = BrinIndex index_class = BrinIndex
def test_suffix(self): def test_suffix(self):
@ -54,7 +54,7 @@ class BrinIndexTests(IndexTestMixin, PostgreSQLTestCase):
BrinIndex(fields=['title'], name='test_title_brin', pages_per_range=0) BrinIndex(fields=['title'], name='test_title_brin', pages_per_range=0)
class BTreeIndexTests(IndexTestMixin, PostgreSQLTestCase): class BTreeIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase):
index_class = BTreeIndex index_class = BTreeIndex
def test_suffix(self): def test_suffix(self):
@ -68,7 +68,7 @@ class BTreeIndexTests(IndexTestMixin, PostgreSQLTestCase):
self.assertEqual(kwargs, {'fields': ['title'], 'name': 'test_title_btree', 'fillfactor': 80}) self.assertEqual(kwargs, {'fields': ['title'], 'name': 'test_title_btree', 'fillfactor': 80})
class GinIndexTests(IndexTestMixin, PostgreSQLTestCase): class GinIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase):
index_class = GinIndex index_class = GinIndex
def test_suffix(self): def test_suffix(self):
@ -92,7 +92,7 @@ class GinIndexTests(IndexTestMixin, PostgreSQLTestCase):
}) })
class GistIndexTests(IndexTestMixin, PostgreSQLTestCase): class GistIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase):
index_class = GistIndex index_class = GistIndex
def test_suffix(self): def test_suffix(self):
@ -111,7 +111,7 @@ class GistIndexTests(IndexTestMixin, PostgreSQLTestCase):
}) })
class HashIndexTests(IndexTestMixin, PostgreSQLTestCase): class HashIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase):
index_class = HashIndex index_class = HashIndex
def test_suffix(self): def test_suffix(self):
@ -125,7 +125,7 @@ class HashIndexTests(IndexTestMixin, PostgreSQLTestCase):
self.assertEqual(kwargs, {'fields': ['title'], 'name': 'test_title_hash', 'fillfactor': 80}) self.assertEqual(kwargs, {'fields': ['title'], 'name': 'test_title_hash', 'fillfactor': 80})
class SpGistIndexTests(IndexTestMixin, PostgreSQLTestCase): class SpGistIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase):
index_class = SpGistIndex index_class = SpGistIndex
def test_suffix(self): def test_suffix(self):

View File

@ -9,7 +9,7 @@ from django.forms import CharField, Form, widgets
from django.test.utils import isolate_apps from django.test.utils import isolate_apps
from django.utils.html import escape from django.utils.html import escape
from . import PostgreSQLTestCase from . import PostgreSQLSimpleTestCase, PostgreSQLTestCase
from .models import JSONModel, PostgreSQLModel from .models import JSONModel, PostgreSQLModel
try: try:
@ -301,7 +301,7 @@ class TestQuerying(PostgreSQLTestCase):
@isolate_apps('postgres_tests') @isolate_apps('postgres_tests')
class TestChecks(PostgreSQLTestCase): class TestChecks(PostgreSQLSimpleTestCase):
def test_invalid_default(self): def test_invalid_default(self):
class MyModel(PostgreSQLModel): class MyModel(PostgreSQLModel):
@ -336,7 +336,7 @@ class TestChecks(PostgreSQLTestCase):
self.assertEqual(model.check(), []) self.assertEqual(model.check(), [])
class TestSerialization(PostgreSQLTestCase): class TestSerialization(PostgreSQLSimpleTestCase):
test_data = ( test_data = (
'[{"fields": {"field": %s, "field_custom": null}, ' '[{"fields": {"field": %s, "field_custom": null}, '
'"model": "postgres_tests.jsonmodel", "pk": null}]' '"model": "postgres_tests.jsonmodel", "pk": null}]'
@ -362,7 +362,7 @@ class TestSerialization(PostgreSQLTestCase):
self.assertEqual(instance.field, value) self.assertEqual(instance.field, value)
class TestValidation(PostgreSQLTestCase): class TestValidation(PostgreSQLSimpleTestCase):
def test_not_serializable(self): def test_not_serializable(self):
field = JSONField() field = JSONField()
@ -378,7 +378,7 @@ class TestValidation(PostgreSQLTestCase):
self.assertEqual(field.clean(datetime.timedelta(days=1), None), datetime.timedelta(days=1)) self.assertEqual(field.clean(datetime.timedelta(days=1), None), datetime.timedelta(days=1))
class TestFormField(PostgreSQLTestCase): class TestFormField(PostgreSQLSimpleTestCase):
def test_valid(self): def test_valid(self):
field = forms.JSONField() field = forms.JSONField()

View File

@ -9,7 +9,7 @@ from django.test import ignore_warnings, override_settings
from django.utils import timezone from django.utils import timezone
from django.utils.deprecation import RemovedInDjango31Warning from django.utils.deprecation import RemovedInDjango31Warning
from . import PostgreSQLTestCase from . import PostgreSQLSimpleTestCase, PostgreSQLTestCase
from .models import RangeLookupsModel, RangesModel from .models import RangeLookupsModel, RangesModel
try: try:
@ -355,7 +355,7 @@ class TestQueryingWithRanges(PostgreSQLTestCase):
) )
class TestSerialization(PostgreSQLTestCase): class TestSerialization(PostgreSQLSimpleTestCase):
test_data = ( test_data = (
'[{"fields": {"ints": "{\\"upper\\": \\"10\\", \\"lower\\": \\"0\\", ' '[{"fields": {"ints": "{\\"upper\\": \\"10\\", \\"lower\\": \\"0\\", '
'\\"bounds\\": \\"[)\\"}", "decimals": "{\\"empty\\": true}", ' '\\"bounds\\": \\"[)\\"}", "decimals": "{\\"empty\\": true}", '
@ -405,7 +405,7 @@ class TestSerialization(PostgreSQLTestCase):
self.assertEqual(new_instance.ints, NumericRange(10, None)) self.assertEqual(new_instance.ints, NumericRange(10, None))
class TestValidators(PostgreSQLTestCase): class TestValidators(PostgreSQLSimpleTestCase):
def test_max(self): def test_max(self):
validator = RangeMaxValueValidator(5) validator = RangeMaxValueValidator(5)
@ -430,7 +430,7 @@ class TestValidators(PostgreSQLTestCase):
validator(NumericRange(None, 10)) # an unbound range validator(NumericRange(None, 10)) # an unbound range
class TestFormField(PostgreSQLTestCase): class TestFormField(PostgreSQLSimpleTestCase):
def test_valid_integer(self): def test_valid_integer(self):
field = pg_forms.IntegerRangeField() field = pg_forms.IntegerRangeField()
@ -708,7 +708,7 @@ class TestFormField(PostgreSQLTestCase):
self.assertIsInstance(form_field, pg_forms.DateTimeRangeField) self.assertIsInstance(form_field, pg_forms.DateTimeRangeField)
class TestWidget(PostgreSQLTestCase): class TestWidget(PostgreSQLSimpleTestCase):
def test_range_widget(self): def test_range_widget(self):
f = pg_forms.ranges.DateTimeRangeField() f = pg_forms.ranges.DateTimeRangeField()
self.assertHTMLEqual( self.assertHTMLEqual(

View File

@ -3,11 +3,11 @@ import shutil
import tempfile import tempfile
from django import conf from django import conf
from django.test import TestCase from django.test import SimpleTestCase
from django.test.utils import extend_sys_path from django.test.utils import extend_sys_path
class TestStartProjectSettings(TestCase): class TestStartProjectSettings(SimpleTestCase):
def setUp(self): def setUp(self):
self.temp_dir = tempfile.TemporaryDirectory() self.temp_dir = tempfile.TemporaryDirectory()
self.addCleanup(self.temp_dir.cleanup) self.addCleanup(self.temp_dir.cleanup)

View File

@ -8,13 +8,13 @@ from django.db.models.functions import Lower
from django.db.models.lookups import Exact, GreaterThan, IsNull, LessThan from django.db.models.lookups import Exact, GreaterThan, IsNull, LessThan
from django.db.models.sql.query import Query from django.db.models.sql.query import Query
from django.db.models.sql.where import OR from django.db.models.sql.where import OR
from django.test import TestCase from django.test import SimpleTestCase
from django.test.utils import register_lookup from django.test.utils import register_lookup
from .models import Author, Item, ObjectC, Ranking from .models import Author, Item, ObjectC, Ranking
class TestQuery(TestCase): class TestQuery(SimpleTestCase):
def test_simple_query(self): def test_simple_query(self):
query = Query(Author) query = Query(Author)
where = query.build_where(Q(num__gt=2)) where = query.build_where(Q(num__gt=2))

View File

@ -9,7 +9,7 @@ from django.db import DEFAULT_DB_ALIAS, connection
from django.db.models import Count, F, Q from django.db.models import Count, F, Q
from django.db.models.sql.constants import LOUTER from django.db.models.sql.constants import LOUTER
from django.db.models.sql.where import NothingNode, WhereNode from django.db.models.sql.where import NothingNode, WhereNode
from django.test import TestCase, skipUnlessDBFeature from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature
from django.test.utils import CaptureQueriesContext from django.test.utils import CaptureQueriesContext
from .models import ( from .models import (
@ -1959,14 +1959,11 @@ class RawQueriesTests(TestCase):
self.assertEqual(repr(qs), "<RawQuerySet: SELECT * FROM queries_note WHERE note = n1 and misc = foo>") self.assertEqual(repr(qs), "<RawQuerySet: SELECT * FROM queries_note WHERE note = n1 and misc = foo>")
class GeneratorExpressionTests(TestCase): class GeneratorExpressionTests(SimpleTestCase):
def test_ticket10432(self): def test_ticket10432(self):
# Using an empty generator expression as the rvalue for an "__in" # Using an empty generator expression as the rvalue for an "__in"
# lookup is legal. # lookup is legal.
self.assertQuerysetEqual( self.assertCountEqual(Note.objects.filter(pk__in=(x for x in ())), [])
Note.objects.filter(pk__in=(x for x in ())),
[]
)
class ComparisonTests(TestCase): class ComparisonTests(TestCase):
@ -2222,30 +2219,22 @@ class CloneTests(TestCase):
opts_class.__deepcopy__ = note_deepcopy opts_class.__deepcopy__ = note_deepcopy
class EmptyQuerySetTests(TestCase): class EmptyQuerySetTests(SimpleTestCase):
def test_emptyqueryset_values(self): def test_emptyqueryset_values(self):
# #14366 -- Calling .values() on an empty QuerySet and then cloning # #14366 -- Calling .values() on an empty QuerySet and then cloning
# that should not cause an error # that should not cause an error
self.assertQuerysetEqual( self.assertCountEqual(Number.objects.none().values('num').order_by('num'), [])
Number.objects.none().values('num').order_by('num'), []
)
def test_values_subquery(self): def test_values_subquery(self):
self.assertQuerysetEqual( self.assertCountEqual(Number.objects.filter(pk__in=Number.objects.none().values('pk')), [])
Number.objects.filter(pk__in=Number.objects.none().values("pk")), self.assertCountEqual(Number.objects.filter(pk__in=Number.objects.none().values_list('pk')), [])
[]
)
self.assertQuerysetEqual(
Number.objects.filter(pk__in=Number.objects.none().values_list("pk")),
[]
)
def test_ticket_19151(self): def test_ticket_19151(self):
# #19151 -- Calling .values() or .values_list() on an empty QuerySet # #19151 -- Calling .values() or .values_list() on an empty QuerySet
# should return an empty QuerySet and not cause an error. # should return an empty QuerySet and not cause an error.
q = Author.objects.none() q = Author.objects.none()
self.assertQuerysetEqual(q.values(), []) self.assertCountEqual(q.values(), [])
self.assertQuerysetEqual(q.values_list(), []) self.assertCountEqual(q.values_list(), [])
class ValuesQuerysetTests(TestCase): class ValuesQuerysetTests(TestCase):
@ -3013,7 +3002,7 @@ class ProxyQueryCleanupTest(TestCase):
self.assertEqual(qs.count(), 1) self.assertEqual(qs.count(), 1)
class WhereNodeTest(TestCase): class WhereNodeTest(SimpleTestCase):
class DummyNode: class DummyNode:
def as_sql(self, compiler, connection): def as_sql(self, compiler, connection):
return 'dummy', [] return 'dummy', []
@ -3078,7 +3067,7 @@ class WhereNodeTest(TestCase):
w.as_sql(compiler, connection) w.as_sql(compiler, connection)
class QuerySetExceptionTests(TestCase): class QuerySetExceptionTests(SimpleTestCase):
def test_iter_exceptions(self): def test_iter_exceptions(self):
qs = ExtraInfo.objects.only('author') qs = ExtraInfo.objects.only('author')
msg = "'ManyToOneRel' object has no attribute 'attname'" msg = "'ManyToOneRel' object has no attribute 'attname'"
@ -3531,7 +3520,7 @@ class Ticket20101Tests(TestCase):
self.assertIn(n, (qs1 | qs2)) self.assertIn(n, (qs1 | qs2))
class EmptyStringPromotionTests(TestCase): class EmptyStringPromotionTests(SimpleTestCase):
def test_empty_string_promotion(self): def test_empty_string_promotion(self):
qs = RelatedObject.objects.filter(single__name='') qs = RelatedObject.objects.filter(single__name='')
if connection.features.interprets_empty_strings_as_nulls: if connection.features.interprets_empty_strings_as_nulls:
@ -3570,7 +3559,7 @@ class DoubleInSubqueryTests(TestCase):
self.assertSequenceEqual(qs, [lfb1]) self.assertSequenceEqual(qs, [lfb1])
class Ticket18785Tests(TestCase): class Ticket18785Tests(SimpleTestCase):
def test_ticket_18785(self): def test_ticket_18785(self):
# Test join trimming from ticket18785 # Test join trimming from ticket18785
qs = Item.objects.exclude( qs = Item.objects.exclude(
@ -3858,7 +3847,7 @@ class TestTicket24279(TestCase):
self.assertQuerysetEqual(qs, []) self.assertQuerysetEqual(qs, [])
class TestInvalidValuesRelation(TestCase): class TestInvalidValuesRelation(SimpleTestCase):
def test_invalid_values(self): def test_invalid_values(self):
msg = "invalid literal for int() with base 10: 'abc'" msg = "invalid literal for int() with base 10: 'abc'"
with self.assertRaisesMessage(ValueError, msg): with self.assertRaisesMessage(ValueError, msg):

View File

@ -4,13 +4,13 @@ from django.apps.registry import Apps
from django.db import models from django.db import models
from django.db.models import signals from django.db.models import signals
from django.dispatch import receiver from django.dispatch import receiver
from django.test import TestCase from django.test import SimpleTestCase, TestCase
from django.test.utils import isolate_apps from django.test.utils import isolate_apps
from .models import Author, Book, Car, Person from .models import Author, Book, Car, Person
class BaseSignalTest(TestCase): class BaseSignalSetup:
def setUp(self): def setUp(self):
# Save up the number of connected signals so that we can check at the # Save up the number of connected signals so that we can check at the
# end that all the signals we register get properly unregistered (#9989) # end that all the signals we register get properly unregistered (#9989)
@ -32,7 +32,7 @@ class BaseSignalTest(TestCase):
self.assertEqual(self.pre_signals, post_signals) self.assertEqual(self.pre_signals, post_signals)
class SignalTests(BaseSignalTest): class SignalTests(BaseSignalSetup, TestCase):
def test_model_pre_init_and_post_init(self): def test_model_pre_init_and_post_init(self):
data = [] data = []
@ -281,7 +281,7 @@ class SignalTests(BaseSignalTest):
ref.assert_not_called() ref.assert_not_called()
class LazyModelRefTest(BaseSignalTest): class LazyModelRefTests(BaseSignalSetup, SimpleTestCase):
def setUp(self): def setUp(self):
super().setUp() super().setUp()
self.received = [] self.received = []

View File

@ -3,7 +3,7 @@ from argparse import ArgumentParser
from contextlib import contextmanager from contextlib import contextmanager
from unittest import TestSuite, TextTestRunner, defaultTestLoader from unittest import TestSuite, TextTestRunner, defaultTestLoader
from django.test import TestCase from django.test import SimpleTestCase
from django.test.runner import DiscoverRunner from django.test.runner import DiscoverRunner
from django.test.utils import captured_stdout from django.test.utils import captured_stdout
@ -20,7 +20,7 @@ def change_cwd(directory):
os.chdir(old_cwd) os.chdir(old_cwd)
class DiscoverRunnerTest(TestCase): class DiscoverRunnerTests(SimpleTestCase):
def test_init_debug_mode(self): def test_init_debug_mode(self):
runner = DiscoverRunner() runner = DiscoverRunner()

View File

@ -581,7 +581,7 @@ class ForcedTimeZoneDatabaseTests(TransactionTestCase):
@skipUnlessDBFeature('supports_timezones') @skipUnlessDBFeature('supports_timezones')
@override_settings(TIME_ZONE='Africa/Nairobi', USE_TZ=True) @override_settings(TIME_ZONE='Africa/Nairobi', USE_TZ=True)
class UnsupportedTimeZoneDatabaseTests(TestCase): class UnsupportedTimeZoneDatabaseTests(SimpleTestCase):
def test_time_zone_parameter_not_supported_if_database_supports_timezone(self): def test_time_zone_parameter_not_supported_if_database_supports_timezone(self):
connections.databases['tz'] = connections.databases['default'].copy() connections.databases['tz'] = connections.databases['default'].copy()

View File

@ -1,12 +1,11 @@
import datetime import datetime
import unittest
from django.test import TestCase from django.test import SimpleTestCase
from django.utils import feedgenerator from django.utils import feedgenerator
from django.utils.timezone import get_fixed_timezone, utc from django.utils.timezone import get_fixed_timezone, utc
class FeedgeneratorTest(unittest.TestCase): class FeedgeneratorTests(SimpleTestCase):
""" """
Tests for the low-level syndication feed framework. Tests for the low-level syndication feed framework.
""" """
@ -131,10 +130,6 @@ class FeedgeneratorTest(unittest.TestCase):
feed_content = feed.writeString('utf-8') feed_content = feed.writeString('utf-8')
self.assertIn('href="/link/" rel="alternate"', feed_content) self.assertIn('href="/link/" rel="alternate"', feed_content)
class FeedgeneratorDBTest(TestCase):
# setting the timezone requires a database query on PostgreSQL.
def test_latest_post_date_returns_utc_time(self): def test_latest_post_date_returns_utc_time(self):
for use_tz in (True, False): for use_tz in (True, False):
with self.settings(USE_TZ=use_tz): with self.settings(USE_TZ=use_tz):

View File

@ -4,7 +4,7 @@ import unittest
from importlib import import_module from importlib import import_module
from zipimport import zipimporter from zipimport import zipimporter
from django.test import SimpleTestCase, TestCase, modify_settings from django.test import SimpleTestCase, modify_settings
from django.test.utils import extend_sys_path from django.test.utils import extend_sys_path
from django.utils.module_loading import ( from django.utils.module_loading import (
autodiscover_modules, import_string, module_has_submodule, autodiscover_modules, import_string, module_has_submodule,
@ -119,7 +119,7 @@ class EggLoader(unittest.TestCase):
import_module('egg_module.sub1.sub2.no_such_module') import_module('egg_module.sub1.sub2.no_such_module')
class ModuleImportTestCase(TestCase): class ModuleImportTests(SimpleTestCase):
def test_import_string(self): def test_import_string(self):
cls = import_string('django.utils.module_loading.import_string') cls = import_string('django.utils.module_loading.import_string')
self.assertEqual(cls, import_string) self.assertEqual(cls, import_string)

View File

@ -1,8 +1,7 @@
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.test import TestCase
class ValidationTestCase(TestCase): class ValidationAssertions:
def assertFailsValidation(self, clean, failed_fields, **kwargs): def assertFailsValidation(self, clean, failed_fields, **kwargs):
with self.assertRaises(ValidationError) as cm: with self.assertRaises(ValidationError) as cm:
clean(**kwargs) clean(**kwargs)

View File

@ -1,8 +1,10 @@
from . import ValidationTestCase from django.test import SimpleTestCase
from . import ValidationAssertions
from .models import CustomMessagesModel from .models import CustomMessagesModel
class CustomMessagesTest(ValidationTestCase): class CustomMessagesTests(ValidationAssertions, SimpleTestCase):
def test_custom_simple_validator_message(self): def test_custom_simple_validator_message(self):
cmm = CustomMessagesModel(number=12) cmm = CustomMessagesModel(number=12)
self.assertFieldFailsValidationWithMessage(cmm.full_clean, 'number', ['AAARGH']) self.assertFieldFailsValidationWithMessage(cmm.full_clean, 'number', ['AAARGH'])

View File

@ -1,8 +1,10 @@
from . import ValidationTestCase from django.test import SimpleTestCase
from . import ValidationAssertions
from .models import ModelToValidate from .models import ModelToValidate
class TestModelsWithValidators(ValidationTestCase): class TestModelsWithValidators(ValidationAssertions, SimpleTestCase):
def test_custom_validator_passes_for_correct_value(self): def test_custom_validator_passes_for_correct_value(self):
mtv = ModelToValidate(number=10, name='Some Name', f_with_custom_validator=42, mtv = ModelToValidate(number=10, name='Some Name', f_with_custom_validator=42,
f_with_iterable_of_validators=42) f_with_iterable_of_validators=42)

View File

@ -3,14 +3,14 @@ from django.core.exceptions import NON_FIELD_ERRORS
from django.test import TestCase from django.test import TestCase
from django.utils.functional import lazy from django.utils.functional import lazy
from . import ValidationTestCase from . import ValidationAssertions
from .models import ( from .models import (
Article, Author, GenericIPAddressTestModel, GenericIPAddrUnpackUniqueTest, Article, Author, GenericIPAddressTestModel, GenericIPAddrUnpackUniqueTest,
ModelToValidate, ModelToValidate,
) )
class BaseModelValidationTests(ValidationTestCase): class BaseModelValidationTests(ValidationAssertions, TestCase):
def test_missing_required_field_raises_error(self): def test_missing_required_field_raises_error(self):
mtv = ModelToValidate(f_with_custom_validator=42) mtv = ModelToValidate(f_with_custom_validator=42)
@ -126,7 +126,7 @@ class ModelFormsTests(TestCase):
self.assertEqual(list(form.errors), ['pub_date']) self.assertEqual(list(form.errors), ['pub_date'])
class GenericIPAddressFieldTests(ValidationTestCase): class GenericIPAddressFieldTests(ValidationAssertions, TestCase):
def test_correct_generic_ip_passes(self): def test_correct_generic_ip_passes(self):
giptm = GenericIPAddressTestModel(generic_ip="1.2.3.4") giptm = GenericIPAddressTestModel(generic_ip="1.2.3.4")