Skip to content

Instantly share code, notes, and snippets.

@fracaron
Last active March 1, 2021 12:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fracaron/fdbf4fb31fef3e3e3362942fb41f9ae9 to your computer and use it in GitHub Desktop.
Save fracaron/fdbf4fb31fef3e3e3362942fb41f9ae9 to your computer and use it in GitHub Desktop.
Base class for tests of abstract models.
from typing import Type
from django.db import connection, models
from django.test import TestCase
from django.test.utils import isolate_apps
@isolate_apps(__name__)
class AbstractModelMixinTestCase(TestCase):
"""
Base class for tests of abstract models.
To use, specify the Abstract Class in the "abstract_model_class" class variable.
A model derived from the abstract class will be made available in self.model
An implementation of setUp() and tearDown() are included in this Mixin.
If you have to use setUp() and tearDown(), you must include parent implementation with super.
Example:
class SoftDeleteAbstractModelTestCase(AbstractModelMixinTestCase):
abstract_model_class = AbstractSoftDeleteModel
def setUp(self):
super().setUp()
...
def tearDown(self):
super().tearDown()
...
"""
abstract_model_class: Type[models.Model]
@classmethod
def setUpClass(cls):
class TestModel(cls.abstract_model_class):
class Meta:
app_label = __name__
cls.model = TestModel
# Create the schema for our test model.
with connection.schema_editor() as schema_editor:
schema_editor.create_model(cls.model)
super(AbstractModelMixinTestCase, cls).setUpClass()
@classmethod
def tearDownClass(cls):
# Delete the schema for the test model.
super(AbstractModelMixinTestCase, cls).tearDownClass()
with connection.schema_editor() as schema_editor:
schema_editor.delete_model(cls.model)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment