使用pytest-django和多租户数据库的自定义测试运行器

时间:2015-11-13 09:55:55

标签: django multi-tenant pytest test-runner pytest-django

我无法使用我的设置进行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.

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

1 个答案:

答案 0 :(得分: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。