tests: refactor multitenant conftest (#57019)

This commit is contained in:
Benjamin Dauvergne 2021-10-01 15:37:13 +02:00
parent c1820e1f64
commit 7817af0ded
1 changed files with 36 additions and 26 deletions

View File

@ -1,26 +1,22 @@
import json
import os
import shutil
import tempfile
import django_webtest
import pytest
@pytest.fixture(scope='function')
def tenants(transactional_db, request, settings):
@pytest.fixture
def make_tenant(tmp_path, transactional_db, settings, request):
import json
from hobo.multitenant.models import Tenant
base = tempfile.mkdtemp('combo-tenant-base')
settings.TENANT_BASE = base
base = tmp_path / 'combo-tenant-base'
base.mkdir()
settings.TENANT_BASE = str(base)
@pytest.mark.django_db
def make_tenant(name):
tenant_dir = os.path.join(base, name)
os.mkdir(tenant_dir)
with open(os.path.join(tenant_dir, 'unsecure'), 'w') as fd:
tenant_dir = base / name
tenant_dir.mkdir()
with (tenant_dir / 'unsecure').open(mode='w') as fd:
fd.write('1')
with open(os.path.join(tenant_dir, 'settings.json'), 'w') as fd:
with (tenant_dir / 'settings.json').open(mode='w') as fd:
json.dump(
{
'HOBO_TEST_VARIABLE': name,
@ -29,7 +25,7 @@ def tenants(transactional_db, request, settings):
},
fd,
)
with open(os.path.join(tenant_dir, 'hobo.json'), 'w') as fd:
with (tenant_dir / 'hobo.json').open(mode='w') as fd:
json.dump(
{
'variables': {
@ -94,26 +90,40 @@ def tenants(transactional_db, request, settings):
)
t = Tenant(domain_url=name, schema_name=name.replace('-', '_').replace('.', '_'))
t.create_schema()
def drop_tenant():
from django.db import connection
from hobo.multitenant.middleware import TenantMiddleware, TenantNotFound
connection.set_schema_to_public()
try:
TenantMiddleware.get_tenant_by_hostname(t.domain_url)
except TenantNotFound:
pass
else:
t.delete(True)
request.addfinalizer(drop_tenant)
return t
tenants = [make_tenant('tenant1.example.net'), make_tenant('tenant2.example.net')]
return make_tenant
def fin():
from django.db import connection
from hobo.multitenant.middleware import TenantMiddleware
@pytest.fixture
def tenants(make_tenant):
return [make_tenant('tenant1.example.net'), make_tenant('tenant2.example.net')]
connection.set_schema_to_public()
for t in TenantMiddleware.get_tenants():
t.delete(True)
shutil.rmtree(base)
request.addfinalizer(fin)
return tenants
@pytest.fixture
def tenant(make_tenant):
return make_tenant('tenant.example.net')
@pytest.fixture
def app(request):
import django_webtest
wtm = django_webtest.WebTestMixin()
wtm._patch_settings()
yield django_webtest.DjangoTestApp()