pytest-dev/pytest-django

Postgres extensions not enabled in test DB when running pytest --no-migrations

Closed this issue · 0 comments

When running tests with pytest --no-migration, postgres extensions required by model indexes are not automatically enabled in the test database. This causes migration to fail when models contain indexes that depend on postgres extensions like pg_trgm.

to reproduce it's enough to run pytest --no-migrations
and have a model like

from django.db import models
from django.contrib.postgres.indexes import GinIndex
from django.contrib.postgres.operations import OpClass
from django.db.models.functions import Lower

class User(models.Model):
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    email = models.EmailField(unique=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        indexes = [
            GinIndex(
                OpClass(
                    Lower("first_name"),
                    name="gin_trgm_ops",
                ),
                OpClass(
                    Lower("last_name"),
                    name="gin_trgm_ops",
                ),
                name="user_name_trgm_idx",
            ),
        ]

this will produce

    def _execute(self, sql, params, *ignored_wrapper_args):
        self.db.validate_no_broken_transaction()
        with self.db.wrap_database_errors:
            if params is None:
                # params default might be backend specific.
>               return self.cursor.execute(sql)
E               django.db.utils.ProgrammingError: operator class "gin_trgm_ops" does not exist for access method "gin"

The easy fix and the most expected by user is for create_test_db to copy existing and enabled extensions
I am willing to contribute if maintainer agree on the fix