diff --git a/CHANGELOG.md b/CHANGELOG.md index 1f39bf5..355889e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ - Switch to just and uv for package management (#572). - Add support for Python 3.13 (#572, #577). - Drop support for Python 3.8 (EOL) (#571, #577). +- Add option to store test media in temp folder (#140). ## 24.2 (2024-04-16) diff --git a/docs/test.rst b/docs/test.rst index c6dac7d..e868d82 100644 --- a/docs/test.rst +++ b/docs/test.rst @@ -9,3 +9,5 @@ The `test` module offers extra functions for unit tests. .. autoclass:: django_marina.test.test_cases.ExtendedTestCase :members: + +.. autoclass:: django_marina.test.runners.TempMediaDiscoverRunner diff --git a/src/django_marina/test/runners.py b/src/django_marina/test/runners.py new file mode 100644 index 0000000..fd34367 --- /dev/null +++ b/src/django_marina/test/runners.py @@ -0,0 +1,35 @@ +import shutil +import tempfile + +from django.conf import settings +from django.test.runner import DiscoverRunner + + +class TempMediaMixin: + """ + Mixin to create MEDIA_ROOT in temporary directory and tear down when complete. + + Source: https://www.caktusgroup.com/blog/2013/06/26/media-root-and-django-tests/ + """ + + def setup_test_environment(self): + """Create temp directory and update MEDIA_ROOT and default storage.""" + super().setup_test_environment() + settings._original_media_root = settings.MEDIA_ROOT + settings._original_file_storage = settings.DEFAULT_FILE_STORAGE + self._temp_media = tempfile.mkdtemp() + settings.MEDIA_ROOT = self._temp_media + settings.DEFAULT_FILE_STORAGE = "django.core.files.storage.FileSystemStorage" + + def teardown_test_environment(self): + """Delete temp storage.""" + super().teardown_test_environment() + shutil.rmtree(self._temp_media, ignore_errors=True) + settings.MEDIA_ROOT = settings._original_media_root + del settings._original_media_root + settings.DEFAULT_FILE_STORAGE = settings._original_file_storage + del settings._original_file_storage + + +class TempMediaDiscoverRunner(TempMediaMixin, DiscoverRunner): + """Default Django DiscoverRunner, modified to write media files to a temp folder."""