Skip to content

Commit

Permalink
Used addCleanup() in tests where appropriate.
Browse files Browse the repository at this point in the history
  • Loading branch information
felixxm authored Dec 31, 2023
1 parent 81ccf92 commit d88ec42
Show file tree
Hide file tree
Showing 37 changed files with 121 additions and 240 deletions.
4 changes: 1 addition & 3 deletions tests/app_loading/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@
class EggLoadingTest(SimpleTestCase):
def setUp(self):
self.egg_dir = "%s/eggs" % os.path.dirname(__file__)

def tearDown(self):
apps.clear_cache()
self.addCleanup(apps.clear_cache)

def test_egg1(self):
"""Models module can be loaded from an app in an egg"""
Expand Down
4 changes: 1 addition & 3 deletions tests/asgi/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,7 @@ class ASGITest(SimpleTestCase):

def setUp(self):
request_started.disconnect(close_old_connections)

def tearDown(self):
request_started.connect(close_old_connections)
self.addCleanup(request_started.connect, close_old_connections)

async def test_get_asgi_application(self):
"""
Expand Down
21 changes: 9 additions & 12 deletions tests/auth_tests/test_auth_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,19 +95,16 @@ class BaseModelBackendTest:
backend = "django.contrib.auth.backends.ModelBackend"

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},
)
self.patched_settings.enable()
patched_settings.enable()
self.addCleanup(patched_settings.disable)
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):
user = self.UserModel._default_manager.get(pk=self.user.pk)
self.assertIs(user.has_perm("auth.test"), False)
Expand Down Expand Up @@ -615,9 +612,9 @@ def setUpTestData(cls):
def setUp(self):
self.user_login_failed = []
signals.user_login_failed.connect(self.user_login_failed_listener)

def tearDown(self):
signals.user_login_failed.disconnect(self.user_login_failed_listener)
self.addCleanup(
signals.user_login_failed.disconnect, self.user_login_failed_listener
)

def user_login_failed_listener(self, sender, credentials, **kwargs):
self.user_login_failed.append(credentials)
Expand Down
6 changes: 2 additions & 4 deletions tests/auth_tests/test_management.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,11 +163,9 @@ def setUpTestData(cls):

def setUp(self):
self.stdout = StringIO()
self.addCleanup(self.stdout.close)
self.stderr = StringIO()

def tearDown(self):
self.stdout.close()
self.stderr.close()
self.addCleanup(self.stderr.close)

@mock.patch.object(getpass, "getpass", return_value="password")
def test_get_pass(self, mock_get_pass):
Expand Down
4 changes: 1 addition & 3 deletions tests/auth_tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -519,9 +519,7 @@ def post_save_listener(self, *args, **kwargs):
def setUp(self):
self.signals_count = 0
post_save.connect(self.post_save_listener, sender=User)

def tearDown(self):
post_save.disconnect(self.post_save_listener, sender=User)
self.addCleanup(post_save.disconnect, self.post_save_listener, sender=User)

def test_create_user(self):
User.objects.create_user("JohnDoe")
Expand Down
8 changes: 3 additions & 5 deletions tests/auth_tests/test_remote_user.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,12 @@ class RemoteUserTest(TestCase):
known_user2 = "knownuser2"

def setUp(self):
self.patched_settings = modify_settings(
patched_settings = modify_settings(
AUTHENTICATION_BACKENDS={"append": self.backend},
MIDDLEWARE={"append": self.middleware},
)
self.patched_settings.enable()

def tearDown(self):
self.patched_settings.disable()
patched_settings.enable()
self.addCleanup(patched_settings.disable)

def test_no_remote_user(self):
"""Users are not created when remote user is not specified."""
Expand Down
11 changes: 5 additions & 6 deletions tests/auth_tests/test_signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,13 @@ def setUp(self):
self.logged_out = []
self.login_failed = []
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)
self.addCleanup(signals.user_logged_out.disconnect, self.listener_logout)
signals.user_login_failed.connect(self.listener_login_failed)

def tearDown(self):
"""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)
self.addCleanup(
signals.user_login_failed.disconnect, self.listener_login_failed
)

def test_login(self):
# Only a successful login will trigger the success signal.
Expand Down
13 changes: 3 additions & 10 deletions tests/cache/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -1155,11 +1155,7 @@ def setUp(self):
# The super calls needs to happen first for the settings override.
super().setUp()
self.create_table()

def tearDown(self):
# The super call needs to happen first because it uses the database.
super().tearDown()
self.drop_table()
self.addCleanup(self.drop_table)

def create_table(self):
management.call_command("createcachetable", verbosity=0)
Expand Down Expand Up @@ -2509,12 +2505,9 @@ class CacheMiddlewareTest(SimpleTestCase):

def setUp(self):
self.default_cache = caches["default"]
self.addCleanup(self.default_cache.clear)
self.other_cache = caches["other"]

def tearDown(self):
self.default_cache.clear()
self.other_cache.clear()
super().tearDown()
self.addCleanup(self.other_cache.clear)

def test_constructor(self):
"""
Expand Down
4 changes: 1 addition & 3 deletions tests/contenttypes_tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@
class ContentTypesTests(TestCase):
def setUp(self):
ContentType.objects.clear_cache()

def tearDown(self):
ContentType.objects.clear_cache()
self.addCleanup(ContentType.objects.clear_cache)

def test_lookup_cache(self):
"""
Expand Down
9 changes: 4 additions & 5 deletions tests/contenttypes_tests/test_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,10 @@ def setUp(self):
models.signals.post_migrate.connect(
self.assertOperationsInjected, sender=app_config
)

def tearDown(self):
app_config = apps.get_app_config("contenttypes_tests")
models.signals.post_migrate.disconnect(
self.assertOperationsInjected, sender=app_config
self.addCleanup(
models.signals.post_migrate.disconnect,
self.assertOperationsInjected,
sender=app_config,
)

def assertOperationsInjected(self, plan, **kwargs):
Expand Down
4 changes: 1 addition & 3 deletions tests/custom_lookups/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -460,9 +460,7 @@ def setUpTestData(cls):

def setUp(self):
models.DateField.register_lookup(YearTransform)

def tearDown(self):
models.DateField._unregister_lookup(YearTransform)
self.addCleanup(models.DateField._unregister_lookup, YearTransform)

@unittest.skipUnless(
connection.vendor == "postgresql", "PostgreSQL specific SQL used"
Expand Down
11 changes: 6 additions & 5 deletions tests/defer_regress/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -322,12 +322,13 @@ def setUp(self):
self.post_delete_senders = []
for sender in self.senders:
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)

def tearDown(self):
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)
self.addCleanup(
models.signals.post_delete.disconnect, self.post_delete_receiver, sender
)

def pre_delete_receiver(self, sender, **kwargs):
self.pre_delete_senders.append(sender)
Expand Down
6 changes: 2 additions & 4 deletions tests/delete_regress/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,9 @@ def setUp(self):
# Create a second connection to the default database
self.conn2 = connection.copy()
self.conn2.set_autocommit(False)

def tearDown(self):
# Close down the second connection.
self.conn2.rollback()
self.conn2.close()
self.addCleanup(self.conn2.close)
self.addCleanup(self.conn2.rollback)

def test_concurrent_delete(self):
"""Concurrent deletes don't collide and lock the database (#9479)."""
Expand Down
46 changes: 15 additions & 31 deletions tests/file_storage/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,16 +71,10 @@ class FileStorageTests(SimpleTestCase):

def setUp(self):
self.temp_dir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, self.temp_dir)
self.storage = self.storage_class(
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):
"""
Expand Down Expand Up @@ -414,14 +408,16 @@ def test_file_storage_preserves_filename_case(self):
"""The storage backend should preserve case of filenames."""
# Create a storage backend associated with the mixed case name
# 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.
mixed_case = "CaSe_SeNsItIvE"
file = other_temp_storage.open(mixed_case, "w")
file.write("storage contents")
file.close()
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.delete(mixed_case)
Expand Down Expand Up @@ -917,9 +913,7 @@ def setUp(self):
self.temp_storage_location = tempfile.mkdtemp(
suffix="filefield_callable_storage"
)

def tearDown(self):
shutil.rmtree(self.temp_storage_location)
self.addCleanup(shutil.rmtree, self.temp_storage_location)

def test_callable_base_class_error_raises(self):
class NotStorage:
Expand Down Expand Up @@ -993,12 +987,10 @@ def chunks(self):
class FileSaveRaceConditionTest(SimpleTestCase):
def setUp(self):
self.storage_dir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, self.storage_dir)
self.storage = FileSystemStorage(self.storage_dir)
self.thread = threading.Thread(target=self.save_file, args=["conflict"])

def tearDown(self):
shutil.rmtree(self.storage_dir)

def save_file(self, name):
name = self.storage.save(name, SlowFile(b"Data"))

Expand All @@ -1017,12 +1009,10 @@ def test_race_condition(self):
class FileStoragePermissions(unittest.TestCase):
def setUp(self):
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()

def tearDown(self):
shutil.rmtree(self.storage_dir)
os.umask(self.old_umask)
self.addCleanup(shutil.rmtree, self.storage_dir)

@override_settings(FILE_UPLOAD_PERMISSIONS=0o654)
def test_file_upload_permissions(self):
Expand Down Expand Up @@ -1059,11 +1049,9 @@ def test_file_upload_directory_default_permissions(self):
class FileStoragePathParsing(SimpleTestCase):
def setUp(self):
self.storage_dir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, self.storage_dir)
self.storage = FileSystemStorage(self.storage_dir)

def tearDown(self):
shutil.rmtree(self.storage_dir)

def test_directory_with_dot(self):
"""Regression test for #9610.
Expand Down Expand Up @@ -1095,11 +1083,9 @@ def test_first_character_dot(self):

class ContentFileStorageTestCase(unittest.TestCase):
def setUp(self):
self.storage_dir = tempfile.mkdtemp()
self.storage = FileSystemStorage(self.storage_dir)

def tearDown(self):
shutil.rmtree(self.storage_dir)
storage_dir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, storage_dir)
self.storage = FileSystemStorage(storage_dir)

def test_content_saving(self):
"""
Expand All @@ -1120,11 +1106,9 @@ class FileLikeObjectTestCase(LiveServerTestCase):

def setUp(self):
self.temp_dir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, self.temp_dir)
self.storage = FileSystemStorage(location=self.temp_dir)

def tearDown(self):
shutil.rmtree(self.temp_dir)

def test_urllib_request_urlopen(self):
"""
Test the File storage API with a file-like object coming from
Expand Down
12 changes: 3 additions & 9 deletions tests/forms_tests/tests/test_input_formats.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@ def setUp(self):
# nl/formats.py has customized TIME_INPUT_FORMATS:
# ['%H:%M:%S', '%H.%M:%S', '%H.%M', '%H:%M']
activate("nl")

def tearDown(self):
deactivate()
self.addCleanup(deactivate)

def test_timeField(self):
"TimeFields can parse dates in the default format"
Expand Down Expand Up @@ -323,9 +321,7 @@ def test_localized_timeField_with_inputformat(self):
class LocalizedDateTests(SimpleTestCase):
def setUp(self):
activate("de")

def tearDown(self):
deactivate()
self.addCleanup(deactivate)

def test_dateField(self):
"DateFields can parse dates in the default format"
Expand Down Expand Up @@ -637,9 +633,7 @@ def test_localized_dateField_with_inputformat(self):
class LocalizedDateTimeTests(SimpleTestCase):
def setUp(self):
activate("de")

def tearDown(self):
deactivate()
self.addCleanup(deactivate)

def test_dateTimeField(self):
"DateTimeFields can parse dates in the default format"
Expand Down
11 changes: 3 additions & 8 deletions tests/gis_tests/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,7 @@ def __getattribute__(self, name):

vendor_impl = "as_" + connection.vendor
__getattribute__original = Func.__getattribute__
self.func_patcher = mock.patch.object(
Func, "__getattribute__", __getattribute__
)
self.func_patcher.start()
func_patcher = mock.patch.object(Func, "__getattribute__", __getattribute__)
func_patcher.start()
self.addCleanup(func_patcher.stop)
super().setUp()

def tearDown(self):
super().tearDown()
self.func_patcher.stop()
Loading

0 comments on commit d88ec42

Please sign in to comment.