Skip to content

Commit

Permalink
Add test runner that uses tempfile
Browse files Browse the repository at this point in the history
  • Loading branch information
dyve committed Jun 29, 2023
1 parent 8e0d4d0 commit f2e284f
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## 23.6 (in development)

- Remove support for Python 3.7 (EOL) (#388).
- Add option to store test media in temp folder (#140).

## 23.5 (2023-06-02)

Expand Down
2 changes: 2 additions & 0 deletions docs/test.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
35 changes: 35 additions & 0 deletions src/django_marina/test/runners.py
Original file line number Diff line number Diff line change
@@ -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."""

0 comments on commit f2e284f

Please sign in to comment.