1

I'm having trouble making pytest work with my setup. I'm using and django-tenant-schemas to handle my multi-tenant db.

The idea is that I need to create a Tenant before migrations are applied. Here's my custom runner:

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

And my 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()

The traceback I get is:

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.

Any ideas how to make this work?

bpipat
  • 3,700
  • 4
  • 20
  • 22

1 Answers1

1


I'm using a different approach. the idea is taken from: 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()

In create_tenant_for_test() you should check if your tenant exists, if not, create one. This will allow --reuse-db.

Bennyn
  • 103
  • 8
  • Looks good, thanks. I ended up updating to Django 1.8 which enabled --keepdb without pytest – bpipat Feb 16 '16 at 13:32