1
0
mirror of https://github.com/django/django.git synced 2024-12-22 09:05:43 +00:00

Used addCleanup() in tests where appropriate.

This commit is contained in:
Mariusz Felisiak 2023-12-31 10:01:31 +01:00 committed by GitHub
parent 81ccf92f15
commit d88ec42bd0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
37 changed files with 121 additions and 240 deletions

View File

@ -8,9 +8,7 @@ from django.test.utils import extend_sys_path
class EggLoadingTest(SimpleTestCase): class EggLoadingTest(SimpleTestCase):
def setUp(self): def setUp(self):
self.egg_dir = "%s/eggs" % os.path.dirname(__file__) self.egg_dir = "%s/eggs" % os.path.dirname(__file__)
self.addCleanup(apps.clear_cache)
def tearDown(self):
apps.clear_cache()
def test_egg1(self): def test_egg1(self):
"""Models module can be loaded from an app in an egg""" """Models module can be loaded from an app in an egg"""

View File

@ -32,9 +32,7 @@ class ASGITest(SimpleTestCase):
def setUp(self): def setUp(self):
request_started.disconnect(close_old_connections) request_started.disconnect(close_old_connections)
self.addCleanup(request_started.connect, close_old_connections)
def tearDown(self):
request_started.connect(close_old_connections)
async def test_get_asgi_application(self): async def test_get_asgi_application(self):
""" """

View File

@ -95,19 +95,16 @@ class BaseModelBackendTest:
backend = "django.contrib.auth.backends.ModelBackend" backend = "django.contrib.auth.backends.ModelBackend"
def setUp(self): def setUp(self):
self.patched_settings = modify_settings( # The custom_perms test messes with ContentTypes, which will be cached.
# Flush the cache to ensure there are no side effects.
self.addCleanup(ContentType.objects.clear_cache)
patched_settings = modify_settings(
AUTHENTICATION_BACKENDS={"append": self.backend}, AUTHENTICATION_BACKENDS={"append": self.backend},
) )
self.patched_settings.enable() patched_settings.enable()
self.addCleanup(patched_settings.disable)
self.create_users() self.create_users()
def tearDown(self):
self.patched_settings.disable()
# The custom_perms test messes with ContentTypes, which will
# be cached; flush the cache to ensure there are no side effects
# Refs #14975, #14925
ContentType.objects.clear_cache()
def test_has_perm(self): def test_has_perm(self):
user = self.UserModel._default_manager.get(pk=self.user.pk) user = self.UserModel._default_manager.get(pk=self.user.pk)
self.assertIs(user.has_perm("auth.test"), False) self.assertIs(user.has_perm("auth.test"), False)
@ -615,9 +612,9 @@ class PermissionDeniedBackendTest(TestCase):
def setUp(self): def setUp(self):
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)
self.addCleanup(
def tearDown(self): signals.user_login_failed.disconnect, self.user_login_failed_listener
signals.user_login_failed.disconnect(self.user_login_failed_listener) )
def user_login_failed_listener(self, sender, credentials, **kwargs): def user_login_failed_listener(self, sender, credentials, **kwargs):
self.user_login_failed.append(credentials) self.user_login_failed.append(credentials)

View File

@ -163,11 +163,9 @@ class ChangepasswordManagementCommandTestCase(TestCase):
def setUp(self): def setUp(self):
self.stdout = StringIO() self.stdout = StringIO()
self.addCleanup(self.stdout.close)
self.stderr = StringIO() self.stderr = StringIO()
self.addCleanup(self.stderr.close)
def tearDown(self):
self.stdout.close()
self.stderr.close()
@mock.patch.object(getpass, "getpass", return_value="password") @mock.patch.object(getpass, "getpass", return_value="password")
def test_get_pass(self, mock_get_pass): def test_get_pass(self, mock_get_pass):

View File

@ -519,9 +519,7 @@ class TestCreateSuperUserSignals(TestCase):
def setUp(self): def setUp(self):
self.signals_count = 0 self.signals_count = 0
post_save.connect(self.post_save_listener, sender=User) post_save.connect(self.post_save_listener, sender=User)
self.addCleanup(post_save.disconnect, self.post_save_listener, sender=User)
def tearDown(self):
post_save.disconnect(self.post_save_listener, sender=User)
def test_create_user(self): def test_create_user(self):
User.objects.create_user("JohnDoe") User.objects.create_user("JohnDoe")

View File

@ -21,14 +21,12 @@ class RemoteUserTest(TestCase):
known_user2 = "knownuser2" known_user2 = "knownuser2"
def setUp(self): def setUp(self):
self.patched_settings = modify_settings( patched_settings = modify_settings(
AUTHENTICATION_BACKENDS={"append": self.backend}, AUTHENTICATION_BACKENDS={"append": self.backend},
MIDDLEWARE={"append": self.middleware}, MIDDLEWARE={"append": self.middleware},
) )
self.patched_settings.enable() patched_settings.enable()
self.addCleanup(patched_settings.disable)
def tearDown(self):
self.patched_settings.disable()
def test_no_remote_user(self): def test_no_remote_user(self):
"""Users are not created when remote user is not specified.""" """Users are not created when remote user is not specified."""

View File

@ -30,14 +30,13 @@ class SignalTestCase(TestCase):
self.logged_out = [] self.logged_out = []
self.login_failed = [] self.login_failed = []
signals.user_logged_in.connect(self.listener_login) signals.user_logged_in.connect(self.listener_login)
self.addCleanup(signals.user_logged_in.disconnect, self.listener_login)
signals.user_logged_out.connect(self.listener_logout) signals.user_logged_out.connect(self.listener_logout)
self.addCleanup(signals.user_logged_out.disconnect, self.listener_logout)
signals.user_login_failed.connect(self.listener_login_failed) signals.user_login_failed.connect(self.listener_login_failed)
self.addCleanup(
def tearDown(self): signals.user_login_failed.disconnect, self.listener_login_failed
"""Disconnect the listeners""" )
signals.user_logged_in.disconnect(self.listener_login)
signals.user_logged_out.disconnect(self.listener_logout)
signals.user_login_failed.disconnect(self.listener_login_failed)
def test_login(self): def test_login(self):
# Only a successful login will trigger the success signal. # Only a successful login will trigger the success signal.

13
tests/cache/tests.py vendored
View File

@ -1155,11 +1155,7 @@ class DBCacheTests(BaseCacheTests, TransactionTestCase):
# The super calls needs to happen first for the settings override. # The super calls needs to happen first for the settings override.
super().setUp() super().setUp()
self.create_table() self.create_table()
self.addCleanup(self.drop_table)
def tearDown(self):
# The super call needs to happen first because it uses the database.
super().tearDown()
self.drop_table()
def create_table(self): def create_table(self):
management.call_command("createcachetable", verbosity=0) management.call_command("createcachetable", verbosity=0)
@ -2509,12 +2505,9 @@ class CacheMiddlewareTest(SimpleTestCase):
def setUp(self): def setUp(self):
self.default_cache = caches["default"] self.default_cache = caches["default"]
self.addCleanup(self.default_cache.clear)
self.other_cache = caches["other"] self.other_cache = caches["other"]
self.addCleanup(self.other_cache.clear)
def tearDown(self):
self.default_cache.clear()
self.other_cache.clear()
super().tearDown()
def test_constructor(self): def test_constructor(self):
""" """

View File

@ -12,9 +12,7 @@ from .models import Author, ConcreteModel, FooWithUrl, ProxyModel
class ContentTypesTests(TestCase): class ContentTypesTests(TestCase):
def setUp(self): def setUp(self):
ContentType.objects.clear_cache() ContentType.objects.clear_cache()
self.addCleanup(ContentType.objects.clear_cache)
def tearDown(self):
ContentType.objects.clear_cache()
def test_lookup_cache(self): def test_lookup_cache(self):
""" """

View File

@ -29,11 +29,10 @@ class ContentTypeOperationsTests(TransactionTestCase):
models.signals.post_migrate.connect( models.signals.post_migrate.connect(
self.assertOperationsInjected, sender=app_config self.assertOperationsInjected, sender=app_config
) )
self.addCleanup(
def tearDown(self): models.signals.post_migrate.disconnect,
app_config = apps.get_app_config("contenttypes_tests") self.assertOperationsInjected,
models.signals.post_migrate.disconnect( sender=app_config,
self.assertOperationsInjected, sender=app_config
) )
def assertOperationsInjected(self, plan, **kwargs): def assertOperationsInjected(self, plan, **kwargs):

View File

@ -460,9 +460,7 @@ class YearLteTests(TestCase):
def setUp(self): def setUp(self):
models.DateField.register_lookup(YearTransform) models.DateField.register_lookup(YearTransform)
self.addCleanup(models.DateField._unregister_lookup, YearTransform)
def tearDown(self):
models.DateField._unregister_lookup(YearTransform)
@unittest.skipUnless( @unittest.skipUnless(
connection.vendor == "postgresql", "PostgreSQL specific SQL used" connection.vendor == "postgresql", "PostgreSQL specific SQL used"

View File

@ -322,12 +322,13 @@ class DeferDeletionSignalsTests(TestCase):
self.post_delete_senders = [] self.post_delete_senders = []
for sender in self.senders: for sender in self.senders:
models.signals.pre_delete.connect(self.pre_delete_receiver, sender) models.signals.pre_delete.connect(self.pre_delete_receiver, sender)
self.addCleanup(
models.signals.pre_delete.disconnect, self.pre_delete_receiver, sender
)
models.signals.post_delete.connect(self.post_delete_receiver, sender) models.signals.post_delete.connect(self.post_delete_receiver, sender)
self.addCleanup(
def tearDown(self): models.signals.post_delete.disconnect, self.post_delete_receiver, sender
for sender in self.senders: )
models.signals.pre_delete.disconnect(self.pre_delete_receiver, sender)
models.signals.post_delete.disconnect(self.post_delete_receiver, sender)
def pre_delete_receiver(self, sender, **kwargs): def pre_delete_receiver(self, sender, **kwargs):
self.pre_delete_senders.append(sender) self.pre_delete_senders.append(sender)

View File

@ -51,11 +51,9 @@ class DeleteLockingTest(TransactionTestCase):
# Create a second connection to the default database # Create a second connection to the default database
self.conn2 = connection.copy() self.conn2 = connection.copy()
self.conn2.set_autocommit(False) self.conn2.set_autocommit(False)
def tearDown(self):
# Close down the second connection. # Close down the second connection.
self.conn2.rollback() self.addCleanup(self.conn2.close)
self.conn2.close() self.addCleanup(self.conn2.rollback)
def test_concurrent_delete(self): def test_concurrent_delete(self):
"""Concurrent deletes don't collide and lock the database (#9479).""" """Concurrent deletes don't collide and lock the database (#9479)."""

View File

@ -71,16 +71,10 @@ class FileStorageTests(SimpleTestCase):
def setUp(self): def setUp(self):
self.temp_dir = tempfile.mkdtemp() self.temp_dir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, self.temp_dir)
self.storage = self.storage_class( self.storage = self.storage_class(
location=self.temp_dir, base_url="/test_media_url/" location=self.temp_dir, base_url="/test_media_url/"
) )
# Set up a second temporary directory which is ensured to have a mixed
# case name.
self.temp_dir2 = tempfile.mkdtemp(suffix="aBc")
def tearDown(self):
shutil.rmtree(self.temp_dir)
shutil.rmtree(self.temp_dir2)
def test_empty_location(self): def test_empty_location(self):
""" """
@ -414,14 +408,16 @@ class FileStorageTests(SimpleTestCase):
"""The storage backend should preserve case of filenames.""" """The storage backend should preserve case of filenames."""
# Create a storage backend associated with the mixed case name # Create a storage backend associated with the mixed case name
# directory. # directory.
other_temp_storage = self.storage_class(location=self.temp_dir2) temp_dir2 = tempfile.mkdtemp(suffix="aBc")
self.addCleanup(shutil.rmtree, temp_dir2)
other_temp_storage = self.storage_class(location=temp_dir2)
# Ask that storage backend to store a file with a mixed case filename. # Ask that storage backend to store a file with a mixed case filename.
mixed_case = "CaSe_SeNsItIvE" mixed_case = "CaSe_SeNsItIvE"
file = other_temp_storage.open(mixed_case, "w") file = other_temp_storage.open(mixed_case, "w")
file.write("storage contents") file.write("storage contents")
file.close() file.close()
self.assertEqual( self.assertEqual(
os.path.join(self.temp_dir2, mixed_case), os.path.join(temp_dir2, mixed_case),
other_temp_storage.path(mixed_case), other_temp_storage.path(mixed_case),
) )
other_temp_storage.delete(mixed_case) other_temp_storage.delete(mixed_case)
@ -917,9 +913,7 @@ class FieldCallableFileStorageTests(SimpleTestCase):
self.temp_storage_location = tempfile.mkdtemp( self.temp_storage_location = tempfile.mkdtemp(
suffix="filefield_callable_storage" suffix="filefield_callable_storage"
) )
self.addCleanup(shutil.rmtree, self.temp_storage_location)
def tearDown(self):
shutil.rmtree(self.temp_storage_location)
def test_callable_base_class_error_raises(self): def test_callable_base_class_error_raises(self):
class NotStorage: class NotStorage:
@ -993,12 +987,10 @@ class SlowFile(ContentFile):
class FileSaveRaceConditionTest(SimpleTestCase): class FileSaveRaceConditionTest(SimpleTestCase):
def setUp(self): def setUp(self):
self.storage_dir = tempfile.mkdtemp() self.storage_dir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, self.storage_dir)
self.storage = FileSystemStorage(self.storage_dir) self.storage = FileSystemStorage(self.storage_dir)
self.thread = threading.Thread(target=self.save_file, args=["conflict"]) self.thread = threading.Thread(target=self.save_file, args=["conflict"])
def tearDown(self):
shutil.rmtree(self.storage_dir)
def save_file(self, name): def save_file(self, name):
name = self.storage.save(name, SlowFile(b"Data")) name = self.storage.save(name, SlowFile(b"Data"))
@ -1017,12 +1009,10 @@ class FileSaveRaceConditionTest(SimpleTestCase):
class FileStoragePermissions(unittest.TestCase): class FileStoragePermissions(unittest.TestCase):
def setUp(self): def setUp(self):
self.umask = 0o027 self.umask = 0o027
self.old_umask = os.umask(self.umask) old_umask = os.umask(self.umask)
self.addCleanup(os.umask, old_umask)
self.storage_dir = tempfile.mkdtemp() self.storage_dir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, self.storage_dir)
def tearDown(self):
shutil.rmtree(self.storage_dir)
os.umask(self.old_umask)
@override_settings(FILE_UPLOAD_PERMISSIONS=0o654) @override_settings(FILE_UPLOAD_PERMISSIONS=0o654)
def test_file_upload_permissions(self): def test_file_upload_permissions(self):
@ -1059,11 +1049,9 @@ class FileStoragePermissions(unittest.TestCase):
class FileStoragePathParsing(SimpleTestCase): class FileStoragePathParsing(SimpleTestCase):
def setUp(self): def setUp(self):
self.storage_dir = tempfile.mkdtemp() self.storage_dir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, self.storage_dir)
self.storage = FileSystemStorage(self.storage_dir) self.storage = FileSystemStorage(self.storage_dir)
def tearDown(self):
shutil.rmtree(self.storage_dir)
def test_directory_with_dot(self): def test_directory_with_dot(self):
"""Regression test for #9610. """Regression test for #9610.
@ -1095,11 +1083,9 @@ class FileStoragePathParsing(SimpleTestCase):
class ContentFileStorageTestCase(unittest.TestCase): class ContentFileStorageTestCase(unittest.TestCase):
def setUp(self): def setUp(self):
self.storage_dir = tempfile.mkdtemp() storage_dir = tempfile.mkdtemp()
self.storage = FileSystemStorage(self.storage_dir) self.addCleanup(shutil.rmtree, storage_dir)
self.storage = FileSystemStorage(storage_dir)
def tearDown(self):
shutil.rmtree(self.storage_dir)
def test_content_saving(self): def test_content_saving(self):
""" """
@ -1120,11 +1106,9 @@ class FileLikeObjectTestCase(LiveServerTestCase):
def setUp(self): def setUp(self):
self.temp_dir = tempfile.mkdtemp() self.temp_dir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, self.temp_dir)
self.storage = FileSystemStorage(location=self.temp_dir) self.storage = FileSystemStorage(location=self.temp_dir)
def tearDown(self):
shutil.rmtree(self.temp_dir)
def test_urllib_request_urlopen(self): def test_urllib_request_urlopen(self):
""" """
Test the File storage API with a file-like object coming from Test the File storage API with a file-like object coming from

View File

@ -12,9 +12,7 @@ class LocalizedTimeTests(SimpleTestCase):
# nl/formats.py has customized TIME_INPUT_FORMATS: # nl/formats.py has customized TIME_INPUT_FORMATS:
# ['%H:%M:%S', '%H.%M:%S', '%H.%M', '%H:%M'] # ['%H:%M:%S', '%H.%M:%S', '%H.%M', '%H:%M']
activate("nl") activate("nl")
self.addCleanup(deactivate)
def tearDown(self):
deactivate()
def test_timeField(self): def test_timeField(self):
"TimeFields can parse dates in the default format" "TimeFields can parse dates in the default format"
@ -323,9 +321,7 @@ class SimpleTimeFormatTests(SimpleTestCase):
class LocalizedDateTests(SimpleTestCase): class LocalizedDateTests(SimpleTestCase):
def setUp(self): def setUp(self):
activate("de") activate("de")
self.addCleanup(deactivate)
def tearDown(self):
deactivate()
def test_dateField(self): def test_dateField(self):
"DateFields can parse dates in the default format" "DateFields can parse dates in the default format"
@ -637,9 +633,7 @@ class SimpleDateFormatTests(SimpleTestCase):
class LocalizedDateTimeTests(SimpleTestCase): class LocalizedDateTimeTests(SimpleTestCase):
def setUp(self): def setUp(self):
activate("de") activate("de")
self.addCleanup(deactivate)
def tearDown(self):
deactivate()
def test_dateTimeField(self): def test_dateTimeField(self):
"DateTimeFields can parse dates in the default format" "DateTimeFields can parse dates in the default format"

View File

@ -64,12 +64,7 @@ class FuncTestMixin:
vendor_impl = "as_" + connection.vendor vendor_impl = "as_" + connection.vendor
__getattribute__original = Func.__getattribute__ __getattribute__original = Func.__getattribute__
self.func_patcher = mock.patch.object( func_patcher = mock.patch.object(Func, "__getattribute__", __getattribute__)
Func, "__getattribute__", __getattribute__ func_patcher.start()
) self.addCleanup(func_patcher.stop)
self.func_patcher.start()
super().setUp() super().setUp()
def tearDown(self):
super().tearDown()
self.func_patcher.stop()

View File

@ -16,9 +16,7 @@ class HandlerTests(SimpleTestCase):
def setUp(self): def setUp(self):
request_started.disconnect(close_old_connections) request_started.disconnect(close_old_connections)
self.addCleanup(request_started.connect, close_old_connections)
def tearDown(self):
request_started.connect(close_old_connections)
def test_middleware_initialized(self): def test_middleware_initialized(self):
handler = WSGIHandler() handler = WSGIHandler()
@ -150,11 +148,9 @@ class SignalsTests(SimpleTestCase):
self.signals = [] self.signals = []
self.signaled_environ = None self.signaled_environ = None
request_started.connect(self.register_started) request_started.connect(self.register_started)
self.addCleanup(request_started.disconnect, self.register_started)
request_finished.connect(self.register_finished) request_finished.connect(self.register_finished)
self.addCleanup(request_finished.disconnect, self.register_finished)
def tearDown(self):
request_started.disconnect(self.register_started)
request_finished.disconnect(self.register_finished)
def register_started(self, **kwargs): def register_started(self, **kwargs):
self.signals.append("started") self.signals.append("started")

View File

@ -762,9 +762,7 @@ class FileCloseTests(SimpleTestCase):
# Disable the request_finished signal during this test # Disable the request_finished signal during this test
# to avoid interfering with the database connection. # to avoid interfering with the database connection.
request_finished.disconnect(close_old_connections) request_finished.disconnect(close_old_connections)
self.addCleanup(request_finished.connect, close_old_connections)
def tearDown(self):
request_finished.connect(close_old_connections)
def test_response(self): def test_response(self):
filename = os.path.join(os.path.dirname(__file__), "abc.txt") filename = os.path.join(os.path.dirname(__file__), "abc.txt")

View File

@ -52,10 +52,8 @@ class URLTestCaseBase(SimpleTestCase):
def setUp(self): def setUp(self):
# Make sure the cache is empty before we are doing our tests. # Make sure the cache is empty before we are doing our tests.
clear_url_caches() clear_url_caches()
def tearDown(self):
# Make sure we will leave an empty cache for other testcases. # Make sure we will leave an empty cache for other testcases.
clear_url_caches() self.addCleanup(clear_url_caches)
class URLPrefixTests(URLTestCaseBase): class URLPrefixTests(URLTestCaseBase):

View File

@ -1756,10 +1756,7 @@ class ResolutionOrderI18NTests(SimpleTestCase):
def setUp(self): def setUp(self):
super().setUp() super().setUp()
activate("de") activate("de")
self.addCleanup(deactivate)
def tearDown(self):
deactivate()
super().tearDown()
def assertGettext(self, msgid, msgstr): def assertGettext(self, msgid, msgstr):
result = gettext(msgid) result = gettext(msgid)

View File

@ -579,20 +579,18 @@ args=(sys.stdout,)
[formatter_simple] [formatter_simple]
format=%(message)s format=%(message)s
""" """
self.temp_file = NamedTemporaryFile() temp_file = NamedTemporaryFile()
self.temp_file.write(logging_conf.encode()) temp_file.write(logging_conf.encode())
self.temp_file.flush() temp_file.flush()
self.addCleanup(temp_file.close)
self.write_settings( self.write_settings(
"settings.py", "settings.py",
sdict={ sdict={
"LOGGING_CONFIG": '"logging.config.fileConfig"', "LOGGING_CONFIG": '"logging.config.fileConfig"',
"LOGGING": 'r"%s"' % self.temp_file.name, "LOGGING": 'r"%s"' % temp_file.name,
}, },
) )
def tearDown(self):
self.temp_file.close()
def test_custom_logging(self): def test_custom_logging(self):
out, err = self.run_manage(["check"]) out, err = self.run_manage(["check"])
self.assertNoOutput(err) self.assertNoOutput(err)

View File

@ -1173,11 +1173,9 @@ class BaseEmailBackendTests(HeadersCheckMixin):
email_backend = None email_backend = None
def setUp(self): def setUp(self):
self.settings_override = override_settings(EMAIL_BACKEND=self.email_backend) settings_override = override_settings(EMAIL_BACKEND=self.email_backend)
self.settings_override.enable() settings_override.enable()
self.addCleanup(settings_override.disable)
def tearDown(self):
self.settings_override.disable()
def assertStartsWith(self, first, second): def assertStartsWith(self, first, second):
if not first.startswith(second): if not first.startswith(second):
@ -1575,12 +1573,9 @@ class FileBackendTests(BaseEmailBackendTests, SimpleTestCase):
super().setUp() super().setUp()
self.tmp_dir = self.mkdtemp() self.tmp_dir = self.mkdtemp()
self.addCleanup(shutil.rmtree, self.tmp_dir) self.addCleanup(shutil.rmtree, self.tmp_dir)
self._settings_override = override_settings(EMAIL_FILE_PATH=self.tmp_dir) _settings_override = override_settings(EMAIL_FILE_PATH=self.tmp_dir)
self._settings_override.enable() _settings_override.enable()
self.addCleanup(_settings_override.disable)
def tearDown(self):
self._settings_override.disable()
super().tearDown()
def mkdtemp(self): def mkdtemp(self):
return tempfile.mkdtemp() return tempfile.mkdtemp()
@ -1754,10 +1749,7 @@ class SMTPBackendTests(BaseEmailBackendTests, SMTPBackendTestsBase):
def setUp(self): def setUp(self):
super().setUp() super().setUp()
self.smtp_handler.flush_mailbox() self.smtp_handler.flush_mailbox()
self.addCleanup(self.smtp_handler.flush_mailbox)
def tearDown(self):
self.smtp_handler.flush_mailbox()
super().tearDown()
def flush_mailbox(self): def flush_mailbox(self):
self.smtp_handler.flush_mailbox() self.smtp_handler.flush_mailbox()

View File

@ -32,7 +32,7 @@ class BaseTests:
} }
def setUp(self): def setUp(self):
self.settings_override = override_settings( settings_override = override_settings(
TEMPLATES=[ TEMPLATES=[
{ {
"BACKEND": "django.template.backends.django.DjangoTemplates", "BACKEND": "django.template.backends.django.DjangoTemplates",
@ -52,10 +52,8 @@ class BaseTests:
% (self.storage_class.__module__, self.storage_class.__name__), % (self.storage_class.__module__, self.storage_class.__name__),
SESSION_SERIALIZER="django.contrib.sessions.serializers.JSONSerializer", SESSION_SERIALIZER="django.contrib.sessions.serializers.JSONSerializer",
) )
self.settings_override.enable() settings_override.enable()
self.addCleanup(settings_override.disable)
def tearDown(self):
self.settings_override.disable()
def get_request(self): def get_request(self):
return HttpRequest() return HttpRequest()

View File

@ -55,20 +55,13 @@ class ImageFieldTestMixin(SerializeMixin):
if os.path.exists(temp_storage_dir): if os.path.exists(temp_storage_dir):
shutil.rmtree(temp_storage_dir) shutil.rmtree(temp_storage_dir)
os.mkdir(temp_storage_dir) os.mkdir(temp_storage_dir)
self.addCleanup(shutil.rmtree, temp_storage_dir)
file_path1 = os.path.join(os.path.dirname(__file__), "4x8.png") file_path1 = os.path.join(os.path.dirname(__file__), "4x8.png")
self.file1 = self.File(open(file_path1, "rb"), name="4x8.png") self.file1 = self.File(open(file_path1, "rb"), name="4x8.png")
self.addCleanup(self.file1.close)
file_path2 = os.path.join(os.path.dirname(__file__), "8x4.png") file_path2 = os.path.join(os.path.dirname(__file__), "8x4.png")
self.file2 = self.File(open(file_path2, "rb"), name="8x4.png") self.file2 = self.File(open(file_path2, "rb"), name="8x4.png")
self.addCleanup(self.file2.close)
def tearDown(self):
"""
Removes temp directory and all its contents.
"""
self.file1.close()
self.file2.close()
shutil.rmtree(temp_storage_dir)
def check_dimensions(self, instance, width, height, field_name="mugshot"): def check_dimensions(self, instance, width, height, field_name="mugshot"):
""" """

View File

@ -49,12 +49,10 @@ class SessionTestsMixin:
def setUp(self): def setUp(self):
self.session = self.backend() self.session = self.backend()
def tearDown(self):
# NB: be careful to delete any sessions created; stale sessions fill up # NB: be careful to delete any sessions created; stale sessions fill up
# the /tmp (with some backends) and eventually overwhelm it after lots # the /tmp (with some backends) and eventually overwhelm it after lots
# of runs (think buildbots) # of runs (think buildbots)
self.session.delete() self.addCleanup(self.session.delete)
def test_new_session(self): def test_new_session(self):
self.assertIs(self.session.modified, False) self.assertIs(self.session.modified, False)
@ -532,6 +530,7 @@ class FileSessionTests(SessionTestsMixin, SimpleTestCase):
# Do file session tests in an isolated directory, and kill it after we're done. # Do file session tests in an isolated directory, and kill it after we're done.
self.original_session_file_path = settings.SESSION_FILE_PATH self.original_session_file_path = settings.SESSION_FILE_PATH
self.temp_session_store = settings.SESSION_FILE_PATH = self.mkdtemp() self.temp_session_store = settings.SESSION_FILE_PATH = self.mkdtemp()
self.addCleanup(shutil.rmtree, self.temp_session_store)
# Reset the file session backend's internal caches # Reset the file session backend's internal caches
if hasattr(self.backend, "_storage_path"): if hasattr(self.backend, "_storage_path"):
del self.backend._storage_path del self.backend._storage_path
@ -540,7 +539,6 @@ class FileSessionTests(SessionTestsMixin, SimpleTestCase):
def tearDown(self): def tearDown(self):
super().tearDown() super().tearDown()
settings.SESSION_FILE_PATH = self.original_session_file_path settings.SESSION_FILE_PATH = self.original_session_file_path
shutil.rmtree(self.temp_session_store)
def mkdtemp(self): def mkdtemp(self):
return tempfile.mkdtemp() return tempfile.mkdtemp()

View File

@ -156,9 +156,7 @@ class SettingsTests(SimpleTestCase):
def setUp(self): def setUp(self):
self.testvalue = None self.testvalue = None
signals.setting_changed.connect(self.signal_callback) signals.setting_changed.connect(self.signal_callback)
self.addCleanup(signals.setting_changed.disconnect, self.signal_callback)
def tearDown(self):
signals.setting_changed.disconnect(self.signal_callback)
def signal_callback(self, sender, setting, value, **kwargs): def signal_callback(self, sender, setting, value, **kwargs):
if setting == "TEST": if setting == "TEST":

View File

@ -27,9 +27,7 @@ class SitesFrameworkTests(TestCase):
def setUp(self): def setUp(self):
Site.objects.clear_cache() Site.objects.clear_cache()
self.addCleanup(Site.objects.clear_cache)
def tearDown(self):
Site.objects.clear_cache()
def test_site_manager(self): def test_site_manager(self):
# Make sure that get_current() does not return a deleted Site object. # Make sure that get_current() does not return a deleted Site object.

View File

@ -71,16 +71,13 @@ class CollectionTestCase(BaseStaticFilesMixin, SimpleTestCase):
temp_dir = self.mkdtemp() temp_dir = self.mkdtemp()
# Override the STATIC_ROOT for all tests from setUp to tearDown # Override the STATIC_ROOT for all tests from setUp to tearDown
# rather than as a context manager # rather than as a context manager
self.patched_settings = self.settings(STATIC_ROOT=temp_dir) patched_settings = self.settings(STATIC_ROOT=temp_dir)
self.patched_settings.enable() patched_settings.enable()
if self.run_collectstatic_in_setUp: if self.run_collectstatic_in_setUp:
self.run_collectstatic() self.run_collectstatic()
# Same comment as in runtests.teardown. # Same comment as in runtests.teardown.
self.addCleanup(shutil.rmtree, temp_dir) self.addCleanup(shutil.rmtree, temp_dir)
self.addCleanup(patched_settings.disable)
def tearDown(self):
self.patched_settings.disable()
super().tearDown()
def mkdtemp(self): def mkdtemp(self):
return tempfile.mkdtemp() return tempfile.mkdtemp()

View File

@ -468,18 +468,14 @@ class TestCollectionFilesOverride(CollectionTestCase):
os.utime(self.testfile_path, (self.orig_atime - 1, self.orig_mtime - 1)) os.utime(self.testfile_path, (self.orig_atime - 1, self.orig_mtime - 1))
self.settings_with_test_app = self.modify_settings( settings_with_test_app = self.modify_settings(
INSTALLED_APPS={"prepend": "staticfiles_test_app"}, INSTALLED_APPS={"prepend": "staticfiles_test_app"},
) )
with extend_sys_path(self.temp_dir): with extend_sys_path(self.temp_dir):
self.settings_with_test_app.enable() settings_with_test_app.enable()
self.addCleanup(settings_with_test_app.disable)
super().setUp() super().setUp()
def tearDown(self):
super().tearDown()
self.settings_with_test_app.disable()
def test_ordering_override(self): def test_ordering_override(self):
""" """
Test if collectstatic takes files in proper order Test if collectstatic takes files in proper order

View File

@ -417,16 +417,15 @@ class TestCollectionManifestStorage(TestHashedFiles, CollectionTestCase):
with open(self._clear_filename, "w") as f: with open(self._clear_filename, "w") as f:
f.write("to be deleted in one test") f.write("to be deleted in one test")
self.patched_settings = self.settings( patched_settings = self.settings(
STATICFILES_DIRS=settings.STATICFILES_DIRS + [temp_dir], STATICFILES_DIRS=settings.STATICFILES_DIRS + [temp_dir],
) )
self.patched_settings.enable() patched_settings.enable()
self.addCleanup(patched_settings.disable)
self.addCleanup(shutil.rmtree, temp_dir) self.addCleanup(shutil.rmtree, temp_dir)
self._manifest_strict = storage.staticfiles_storage.manifest_strict self._manifest_strict = storage.staticfiles_storage.manifest_strict
def tearDown(self): def tearDown(self):
self.patched_settings.disable()
if os.path.exists(self._clear_filename): if os.path.exists(self._clear_filename):
os.unlink(self._clear_filename) os.unlink(self._clear_filename)
@ -702,13 +701,13 @@ class CustomManifestStorage(storage.ManifestStaticFilesStorage):
class TestCustomManifestStorage(SimpleTestCase): class TestCustomManifestStorage(SimpleTestCase):
def setUp(self): def setUp(self):
self.manifest_path = Path(tempfile.mkdtemp()) manifest_path = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.manifest_path) self.addCleanup(shutil.rmtree, manifest_path)
self.staticfiles_storage = CustomManifestStorage( self.staticfiles_storage = CustomManifestStorage(
manifest_location=self.manifest_path, manifest_location=manifest_path,
) )
self.manifest_file = self.manifest_path / self.staticfiles_storage.manifest_name self.manifest_file = manifest_path / self.staticfiles_storage.manifest_name
# Manifest without paths. # Manifest without paths.
self.manifest = {"version": self.staticfiles_storage.manifest_version} self.manifest = {"version": self.staticfiles_storage.manifest_version}
with self.manifest_file.open("w") as manifest_file: with self.manifest_file.open("w") as manifest_file:
@ -762,13 +761,10 @@ class TestStaticFilePermissions(CollectionTestCase):
def setUp(self): def setUp(self):
self.umask = 0o027 self.umask = 0o027
self.old_umask = os.umask(self.umask) old_umask = os.umask(self.umask)
self.addCleanup(os.umask, old_umask)
super().setUp() super().setUp()
def tearDown(self):
os.umask(self.old_umask)
super().tearDown()
# Don't run collectstatic command in this test class. # Don't run collectstatic command in this test class.
def run_collectstatic(self, **kwargs): def run_collectstatic(self, **kwargs):
pass pass

View File

@ -19,6 +19,4 @@ class MultipleLocaleActivationTestCase(SimpleTestCase):
def setUp(self): def setUp(self):
self._old_language = get_language() self._old_language = get_language()
self.addCleanup(activate, self._old_language)
def tearDown(self):
activate(self._old_language)

View File

@ -259,12 +259,10 @@ class AtomicWithoutAutocommitTests(AtomicTests):
def setUp(self): def setUp(self):
transaction.set_autocommit(False) transaction.set_autocommit(False)
self.addCleanup(transaction.set_autocommit, True)
def tearDown(self):
# The tests access the database after exercising 'atomic', initiating # The tests access the database after exercising 'atomic', initiating
# a transaction ; a rollback is required before restoring autocommit. # a transaction ; a rollback is required before restoring autocommit.
transaction.rollback() self.addCleanup(transaction.rollback)
transaction.set_autocommit(True)
@skipUnlessDBFeature("uses_savepoints") @skipUnlessDBFeature("uses_savepoints")
@ -512,10 +510,8 @@ class NonAutocommitTests(TransactionTestCase):
def setUp(self): def setUp(self):
transaction.set_autocommit(False) transaction.set_autocommit(False)
self.addCleanup(transaction.set_autocommit, True)
def tearDown(self): self.addCleanup(transaction.rollback)
transaction.rollback()
transaction.set_autocommit(True)
def test_orm_query_after_error_and_rollback(self): def test_orm_query_after_error_and_rollback(self):
""" """

View File

@ -26,11 +26,9 @@ except ImportError:
class TestArchive(unittest.TestCase): class TestArchive(unittest.TestCase):
def setUp(self): def setUp(self):
self.testdir = os.path.join(os.path.dirname(__file__), "archives") self.testdir = os.path.join(os.path.dirname(__file__), "archives")
self.old_cwd = os.getcwd() old_cwd = os.getcwd()
os.chdir(self.testdir) os.chdir(self.testdir)
self.addCleanup(os.chdir, old_cwd)
def tearDown(self):
os.chdir(self.old_cwd)
def test_extract_function(self): def test_extract_function(self):
with os.scandir(self.testdir) as entries: with os.scandir(self.testdir) as entries:

View File

@ -315,14 +315,12 @@ class TestCommonRoots(SimpleTestCase):
class TestSysPathDirectories(SimpleTestCase): class TestSysPathDirectories(SimpleTestCase):
def setUp(self): def setUp(self):
self._directory = tempfile.TemporaryDirectory() _directory = tempfile.TemporaryDirectory()
self.directory = Path(self._directory.name).resolve(strict=True).absolute() self.addCleanup(_directory.cleanup)
self.directory = Path(_directory.name).resolve(strict=True).absolute()
self.file = self.directory / "test" self.file = self.directory / "test"
self.file.touch() self.file.touch()
def tearDown(self):
self._directory.cleanup()
def test_sys_paths_with_directories(self): def test_sys_paths_with_directories(self):
with extend_sys_path(str(self.file)): with extend_sys_path(str(self.file)):
paths = list(autoreload.sys_path_directories()) paths = list(autoreload.sys_path_directories())
@ -542,15 +540,13 @@ class ReloaderTests(SimpleTestCase):
RELOADER_CLS = None RELOADER_CLS = None
def setUp(self): def setUp(self):
self._tempdir = tempfile.TemporaryDirectory() _tempdir = tempfile.TemporaryDirectory()
self.tempdir = Path(self._tempdir.name).resolve(strict=True).absolute() self.tempdir = Path(_tempdir.name).resolve(strict=True).absolute()
self.existing_file = self.ensure_file(self.tempdir / "test.py") self.existing_file = self.ensure_file(self.tempdir / "test.py")
self.nonexistent_file = (self.tempdir / "does_not_exist.py").absolute() self.nonexistent_file = (self.tempdir / "does_not_exist.py").absolute()
self.reloader = self.RELOADER_CLS() self.reloader = self.RELOADER_CLS()
self.addCleanup(self.reloader.stop)
def tearDown(self): self.addCleanup(_tempdir.cleanup)
self._tempdir.cleanup()
self.reloader.stop()
def ensure_file(self, path): def ensure_file(self, path):
path.parent.mkdir(exist_ok=True, parents=True) path.parent.mkdir(exist_ok=True, parents=True)

View File

@ -10,11 +10,9 @@ from django.utils.timezone import get_default_timezone, get_fixed_timezone, make
@override_settings(TIME_ZONE="Europe/Copenhagen") @override_settings(TIME_ZONE="Europe/Copenhagen")
class DateFormatTests(SimpleTestCase): class DateFormatTests(SimpleTestCase):
def setUp(self): def setUp(self):
self._orig_lang = translation.get_language() _orig_lang = translation.get_language()
translation.activate("en-us") translation.activate("en-us")
self.addCleanup(translation.activate, _orig_lang)
def tearDown(self):
translation.activate(self._orig_lang)
def test_date(self): def test_date(self):
d = date(2009, 5, 16) d = date(2009, 5, 16)

View File

@ -1904,9 +1904,7 @@ class CustomExceptionReporterFilter(SafeExceptionReporterFilter):
class CustomExceptionReporterFilterTests(SimpleTestCase): class CustomExceptionReporterFilterTests(SimpleTestCase):
def setUp(self): def setUp(self):
get_default_exception_reporter_filter.cache_clear() get_default_exception_reporter_filter.cache_clear()
self.addCleanup(get_default_exception_reporter_filter.cache_clear)
def tearDown(self):
get_default_exception_reporter_filter.cache_clear()
def test_setting_allows_custom_subclass(self): def test_setting_allows_custom_subclass(self):
self.assertIsInstance( self.assertIsInstance(

View File

@ -14,9 +14,7 @@ class WSGITest(SimpleTestCase):
def setUp(self): def setUp(self):
request_started.disconnect(close_old_connections) request_started.disconnect(close_old_connections)
self.addCleanup(request_started.connect, close_old_connections)
def tearDown(self):
request_started.connect(close_old_connections)
def test_get_wsgi_application(self): def test_get_wsgi_application(self):
""" """