sintonia/api/libretime_api/tests/runner.py

33 lines
1.0 KiB
Python
Raw Normal View History

2022-04-01 17:29:11 +02:00
from typing import List, Type
from django.db.models import Model
2020-01-30 14:47:36 +01:00
from django.test.runner import DiscoverRunner
class ManagedModelTestRunner(DiscoverRunner):
"""
Test runner that automatically makes all unmanaged models in your Django
project managed for the duration of the test run, so that one doesn't need
to execute the SQL manually to create them.
"""
2021-05-27 16:23:02 +02:00
2022-04-01 17:29:11 +02:00
unmanaged_models: List[Type[Model]] = []
2020-01-30 14:47:36 +01:00
def setup_test_environment(self, *args, **kwargs):
2022-06-26 16:09:09 +02:00
# pylint: disable=import-outside-toplevel
2020-01-30 14:47:36 +01:00
from django.apps import apps
2021-05-27 16:23:02 +02:00
2022-04-01 17:29:11 +02:00
for model in apps.get_models():
if not model._meta.managed:
model._meta.managed = True
self.unmanaged_models.append(model)
super().setup_test_environment(*args, **kwargs)
2020-01-30 14:47:36 +01:00
def teardown_test_environment(self, *args, **kwargs):
super().teardown_test_environment(*args, **kwargs)
2022-04-01 17:29:11 +02:00
2020-01-30 14:47:36 +01:00
# reset unmanaged models
2022-04-01 17:29:11 +02:00
for model in self.unmanaged_models:
model._meta.managed = False