Skip to content

Instantly share code, notes, and snippets.

@rj76
Created December 24, 2018 08:55
Show Gist options
  • Save rj76/c33ee201428be26b9c78a78473b5b169 to your computer and use it in GitHub Desktop.
Save rj76/c33ee201428be26b9c78a78473b5b169 to your computer and use it in GitHub Desktop.
django-tenant-schemas & django rest framework with pytest
# core mixins
from tenant_schemas.test.client import TenantClient
from rest_framework.test import APIClient
class My24ApiClient(TenantClient, APIClient):
pass
# core fixtures.py
from tenant_schemas.utils import get_public_schema_name, tenant_context
# a member model is my main model that links to a tenant
def get_or_create(companycode):
try:
member = member_models.Member.objects.get(companycode=companycode)
member.tenant = member.tenants.all()[0]
member.settings = None
member.check_settings()
except member_models.Member.DoesNotExist:
member = member_factories.MemberFactory.create(companycode=companycode)
member.check_settings()
member.create_tenants()
call_command('migrate_schemas',
schema_name=get_public_schema_name(),
interactive=False,
verbosity=0,
executor='parallel')
member.tenant = member.tenants.all()[0]
return member
# I'm using max 3 tenants in my tests, so I'm setting them up once
# when test session starts
@pytest.fixture(scope='session')
def django_db_setup(django_db_setup, django_db_blocker):
with django_db_blocker.unblock():
get_or_create('companycode1')
get_or_create('companycode2')
get_or_create('companycode3')
# member / tenant 1
@pytest.fixture
def member1():
return get_or_create('companycode1')
# client bound to tenant 1
@pytest.fixture
def client1(member1):
return mixins.My24ApiClient(member1.tenant)
# a user that can login in tenant 1
@pytest.fixture
def planninguser1(member1):
with tenant_context(member1.tenant):
user = company_factories.PlanningUserFactory()
return user
# example of usage in a test
@pytest.mark.django_db
class TestPlanninguserViewsetAPI:
def test_planninguser_list(self, member1, client1, planninguser1):
with tenant_context(member1.tenant):
factories.PlanningUserFactory()
client1.force_login(planninguser1)
response = client1.get(reverse('planninguser-list'))
assert response.status_code == status.HTTP_200_OK
assert response.data['count'] == 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment