1

我无法使 pytest 与我的设置一起工作。我正在使用和django-tenant-schemas来处理我的多租户数据库。

这个想法是我需要在应用迁移之前创建一个租户。这是我的自定义跑步者:

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.

任何想法如何使这项工作?

4

1 回答 1

1


我正在使用不同的方法。这个想法来自: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()您应该检查您的租户是否存在,如果不存在,请创建一个。这将允许 --reuse-db。

于 2016-02-15T07:03:27.160 回答