I am setting up the test platform for a multi-tenant system.
For each written test, I want to create a test for each tenant and wrap the entire test run to change the database connexion and some thread local variable before the test without breaking the database teardown where it flushes.
During my trial-and-error process, I've resorted to climbing higher and higher in the pytest hook chain: I started with pytest_generate_tests
to create a test for each tenant with an associated fixture, but the teardown failed, I've ended up at the following idea:
def pytest_runtestloop(session):
for tenant in range(settings.TENANTS.keys()):
with set_current_tenant(tenant):
with environ({'DJANGO_CONFIGURATION': f'Test{tenant.capitalize()}Config'}):
session.config.pluginmanager.getplugin("main").pytest_runtestloop(session)
return True
Although this does not work (since django-configurations
loads the settings during the earlier pytest_load_initial_conftests
phase), this example should give an idea of what I am trying to achieve.
The big roadblock: The default
database connection needs to point to the current tenant's database before any fixtures are loaded and after flush
is ran.
I have disabled pytest-django
's default session fixture mechanism and plan on using a external database for tests :
@pytest.fixture(scope='session')
def django_db_setup():
pass
I could have a wrapper python script that calls pytest
multiple times with the right config, but I would lose a lot of nice tooling.