From 10bb277da268ca35d175773d262c1b322b5059be Mon Sep 17 00:00:00 2001 From: Michael Herrmann Date: Fri, 6 Oct 2023 11:26:20 +0200 Subject: [PATCH] Improve temp dir handling in tests Specifically, on Windows, TestCaseThatUploadsFiles currently shows errors on interpreter exit. These are caused by TemporaryDirectory.cleanup() not being able to delete files because they are still open in python.exe. Now at least, the errors appear during tearDown(). --- winget/tests/util.py | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/winget/tests/util.py b/winget/tests/util.py index f8bdadb..9f87f05 100644 --- a/winget/tests/util.py +++ b/winget/tests/util.py @@ -9,15 +9,19 @@ from tenants.models import Tenant When a test case uploads files, they by default get placed into media/. This folder (out of the box) is not cleaned up after the test case is run. TestCaseThatUploadsFiles fixes this. It makes sure that files are uploaded into -a temporary directory. This directory is cleaned up when the Python interpreter -exits. This is achieved by keeping a global reference to the TemporaryDirectory -instance. Once this instance goes out of scope, Python guarantees that the -temporary directory (and its contents) are removed. +a temporary directory. This directory is cleaned up at the end of each test. """ -_MEDIA_ROOT = TemporaryDirectory() -@override_settings(MEDIA_ROOT=_MEDIA_ROOT.name) class TestCaseThatUploadsFiles(TestCase): - pass + def setUp(self): + super().setUp() + self.media_root = TemporaryDirectory() + media_root_path = self.media_root.name + self.settings_override = override_settings(MEDIA_ROOT=media_root_path) + self.settings_override.enable() + def tearDown(self): + super().tearDown() + self.settings_override.disable() + self.media_root.cleanup() class MultiUploadInMemoryFile(SimpleUploadedFile): """