pytest-django: Register a database type after creation of test databases

Viewed 138

I have a django model field that registers a database type:

class FieldMeta(type):
    def __init__(cls, name, bases, clsdict):
        super().__init__(name, bases, clsdict)
        cls.register_type()

    def register_type(cls):
        db_type = cls().db_type(connection)
        cursor = connection.cursor()
        try:
            cursor.execute(
                "CREATE TYPE foo AS (first integer, second integer);"
            )
            _logger.warn("creating type")
        except ProgrammingError:
            pass

        cls.python_type = register_composite(
            db_type, connection.cursor().cursor, globally=True
        ).type
        _logger.warn("registering composite")

        def adapt_composite(composite):
            return AsIs(...get sql...)

        register_adapter(Foo, adapt_composite)

class FooField(models.Field, metaclass=FieldMeta):
    def db_type(self, connection):
        return "foo"

This works fine in these situations:

  • Database already knows about type foo
  • Database does not know about type foo

The problem is that pytest-django seems to run these init methods before creating the test database, meaning that the test database does not have the required type. I can fix this on individual tests by calling FooField.register_type() in the setUpClass method of the test, but this is not ideal, since it should always be present.

I tried overriding the django_db_setup fixture to look like this:

@pytest.fixture(scope="session")
def django_db_setup(
    request,
    django_test_environment: None,
    django_db_blocker,
    django_db_use_migrations: bool,
    django_db_keepdb: bool,
    django_db_createdb: bool,
    django_db_modify_db_settings: None,
) -> None:
    """Top level fixture to ensure test databases are available"""
    from django.test.utils import setup_databases, teardown_databases

    setup_databases_args = {}

    if django_db_keepdb and not django_db_createdb:
        setup_databases_args["keepdb"] = True

    with django_db_blocker.unblock():
        db_cfg = setup_databases(
            verbosity=request.config.option.verbose,
            interactive=False,
            **setup_databases_args
        )
        FooField.register_type() # <----------------------------

    def teardown_database() -> None:
        with django_db_blocker.unblock():
            try:
                teardown_databases(db_cfg, verbosity=request.config.option.verbose)
            except Exception as exc:
                request.node.warn(
                    pytest.PytestWarning(
                        "Error when trying to teardown test databases: %r" % exc
                    )
                )

    if not django_db_keepdb:
        request.addfinalizer(teardown_database)

But this had no effect. I also tried putting a breakpoint in instead of this line (it was never called), and putting a breakpoint in before the with django_db_blocker.unblock(): (which was called, so conftest.py is definitely being called).

In summary, the question is how to get pytest-django to run this method after the test database is created?

0 Answers
Related