Skip to content

Instantly share code, notes, and snippets.

@mka142
Last active July 19, 2022 19:57
Show Gist options
  • Save mka142/3d45b0adbf082451091848c9c13403ac to your computer and use it in GitHub Desktop.
Save mka142/3d45b0adbf082451091848c9c13403ac to your computer and use it in GitHub Desktop.
Django test with custom models
#https://code.djangoproject.com/ticket/7835
# __init__.py
from django.apps import AppConfig, apps
def setup_test_app(package, label=None):
"""
Setup a Django test app for the provided package to allow test models
tables to be created if the containing app has migrations.
This function should be called from app.tests __init__ module and pass
along __package__.
"""
app_config = AppConfig.create(package)
app_config.apps = apps
if label is None:
containing_app_config = apps.get_containing_app_config(package)
label = f'{containing_app_config.label}_tests'
if label in apps.app_configs:
raise ValueError(f"There's already an app registered with the '{label}' label.')
app_config.label = label
apps.app_configs[app_config.label] = app_config
app_config.import_models()
apps.clear_cache()
# my test app utils/tests/
setup_test_app("utils.tests", "utils_tests")
'''
Which when called from app/tests/__init__.py as setup_test_app(__package__) will
create an app_tests appconfig entry and auto-discover the models automatically.
Since the *.tests modules should only be loaded on test discovery the app and
its models will only be available during tests. Keep in mind that if your test
models reference models from an application with migrations you'll also need to
manually create migrations for these tests models but once that's done you should
be good to go.
It does feel less magic and convention based than Ashley's solution as it prevents
conflicts between models and allows multiple test apps per app from any test package structure. Thoughts?
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment