Last active
March 1, 2021 12:44
-
-
Save fracaron/fdbf4fb31fef3e3e3362942fb41f9ae9 to your computer and use it in GitHub Desktop.
Base class for tests of abstract models.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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