Last active
April 23, 2022 04:38
-
-
Save jeroenbrouwer/61b419e7232710e95c3e9454c7c78863 to your computer and use it in GitHub Desktop.
Setting up django-tenant-schemas with a "fake" pytest tenant
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 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) |
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
Would be cautious to re-add
connection.set_tenant(tenant_pytest)
after the yield. I just flushed my public database :-)