Skip to content

Instantly share code, notes, and snippets.

@jeroenbrouwer
Last active April 23, 2022 04:38
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jeroenbrouwer/61b419e7232710e95c3e9454c7c78863 to your computer and use it in GitHub Desktop.
Save jeroenbrouwer/61b419e7232710e95c3e9454c7c78863 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)
@dperetti
Copy link

Would be cautious to re-add connection.set_tenant(tenant_pytest) after the yield. I just flushed my public database :-)

@jeroenbrouwer
Copy link
Author

Good point! I'll add it in.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment