Skip to content
Create a gist now

Instantly share code, notes, and snippets.

@myaser /
Last active Dec 29, 2015


a TestCase subclass to help you test your abstract django models


1- subclass your django abstract models

2- write your test case like this:

class MyTestCase(AbstractModelTestCase):
    self.models = [MyAbstractModelSubClass, .....]
    # your tests goes here ...

3- if you didn't provide self.models attribute it will search the current app for models in the path myapp.tests.models.*

from django.db import connection
from django.test import TestCase
from import no_style
from importlib import import_module
def sync_models(model_list):
Create the database tables for given models. used for testing abstract models
tables = connection.introspection.table_names()
seen_models = connection.introspection.installed_models(tables)
created_models = set()
pending_references = {}
cursor = connection.cursor()
for model in model_list:
# Create the model's database table, if it doesn't already exist.
sql, references = connection.creation.sql_create_model(model, no_style(), seen_models)
for refto, refs in references.items():
pending_references.setdefault(refto, []).extend(refs)
if refto in seen_models:
sql.extend(connection.creation.sql_for_pending_references(refto, no_style(), pending_references))
sql.extend(connection.creation.sql_for_pending_references(model, no_style(), pending_references))
for statement in sql:
def get_test_models(package):
models_module = import_module('.tests.models', package)
return [getattr(models_module, _dir) for _dir in dir(models_module)
if _dir.startswith('Test')]
return []
class AbstractModelTestCase(TestCase):
def setUp(self):
if not self.models:
self.models = get_test_models(self.__module__.partition('.tests')[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.