我在设置pytest时遇到问题。我正在使用和django-tenant模式来处理我的多租户数据库。
这个想法是,在应用迁移之前,我需要创建一个Tenant。这是我的自定义跑步者:
from django.test.runner import DiscoverRunner
from django.core.management import call_command
class TenantMixin(object):
"""Mixin for test runners."""
def setup_databases(self, **kwargs):
"""Create a tenant after db setup."""
old_names, mirrors = super(TenantMixin, self).setup_databases(
**kwargs)
call_command(
"create_tenant",
domain_url="base-tenant.test.com",
schema_name="test_{}".format(settings.CLIENT_NAME),
tenant_name="Test Tenant",
interactive=False,
test_database=True,
test_flush=True,
)
return old_names, mirrors
class CustomRunner(TenantMixin, DiscoverRunner):
"""Custom runner."""
pass
我的conftest.py:
import pytest
from tandoori_test.runner import CustomRunner
@pytest.fixture(scope='session', autouse=True)
@pytest.mark.django_db(transaction=True)
def tandoori_setup(request):
runner = CustomRunner()
runner.setup_test_environment()
runner.setup_databases()
我得到的回溯是:
conftest.py:23: in tandoori_setup
runner.setup_databases()
tandoori_test/runner.py:20: in setup_databases
**kwargs)
../../.virtualenvs/nbo/local/lib/python2.7/site-packages/django/test/runner.py:109: in setup_databases
return setup_databases(self.verbosity, self.interactive, **kwargs)
../../.virtualenvs/nbo/local/lib/python2.7/site-packages/django/test/runner.py:299: in setup_databases
serialize=connection.settings_dict.get("TEST", {}).get("SERIALIZE", True),
../../.virtualenvs/nbo/local/lib/python2.7/site-packages/django/db/backends/creation.py:362: in create_test_db
self._create_test_db(verbosity, autoclobber)
../../.virtualenvs/nbo/local/lib/python2.7/site-packages/django/db/backends/creation.py:455: in _create_test_db
with self._nodb_connection.cursor() as cursor:
../../.virtualenvs/nbo/local/lib/python2.7/site-packages/django/db/backends/__init__.py:167: in cursor
cursor = utils.CursorWrapper(self._cursor(), self)
E Failed: Database access not allowed, use the "django_db" mark to enable it.
有什么办法让它发挥作用吗?
我用了一种不同的方法。其思想来源于:https://github.com/pytest-dev/pytest-django/issues/33
import pytest
@pytest.fixture(autouse=True, scope='session')
def post_db_setup(_django_db_setup, _django_cursor_wrapper):
with _django_cursor_wrapper:
create_tenant_for_test()
在create_tenant_for_test()
中,您应该检查租户是否存在,如果不存在,请创建一个租户。这将允许重用数据库。