Skip to content

Instantly share code, notes, and snippets.

@wangonya
Forked from jeroenbrouwer/conftest.py
Created June 26, 2021 05:10
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 wangonya/28ac89d52aa55718700323d4002a6210 to your computer and use it in GitHub Desktop.
Save wangonya/28ac89d52aa55718700323d4002a6210 to your computer and use it in GitHub Desktop.
Setting up django-tenant-schemas with a "fake" pytest tenant
from django.core.management import call_command
from django.db import connection
from tenant_schemas.utils import get_public_schema_name, get_tenant_model
import pytest
TenantModel = get_tenant_model()
def get_or_create_tenant(*, schema_name, migrate=True):
try:
tenant = TenantModel.objects.get(schema_name=schema_name)
except TenantModel.DoesNotExist:
tenant = TenantModel(schema_name=schema_name)
tenant.save(verbosity=0)
if migrate:
call_command('migrate_schemas',
schema_name=schema_name,
interactive=False,
verbosity=0)
return tenant
@pytest.yield_fixture(scope='session', autouse=True)
def django_db_setup(django_db_blocker):
"""
This function overrides the _django_db_setup fixture and creates a test tenant called pytest.
Then it returns the usual _django_db_setup fixture.
For more information see:
https://github.com/pytest-dev/pytest-django/issues/105#issuecomment-61474664
"""
with django_db_blocker.unblock():
# Minimum required setup for the project to run under django-tenant-schemas.
tenant_public = get_or_create_tenant(schema_name=get_public_schema_name())
tenant_pytest = get_or_create_tenant(schema_name='pytest')
# Tenant is pytest now!
connection.set_tenant(tenant_pytest)
# At this point the DB setup for the tests is complete
yield
# Making sure the current tenant is pytest again, it might have changed during the tests
connection.set_tenant(tenant_pytest)
# Finally we flush all data from the pytest tenant and set the connection back to public, like nothing happened!
call_command('flush',
interactive=False,
verbosity=0)
connection.set_tenant(tenant_public)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment