Django 测试使用 Postgres 扩展而无需迁移

问题描述 投票:0回答:1

我有一个现有项目,我想开始实施测试步骤。历史上发生过相当多的数据迁移,我不想花精力让它们在测试设置中运行。所以我禁用了“迁移”:

DATABASES['default']['TEST'] = {
    'MIGRATE': False,
}

但是这个 Postgres DB 使用了一些扩展

    class Meta:
        verbose_name = 'PriceBook Cache'
        verbose_name_plural = 'PriceBook Caches'
        indexes = [
            GinIndex(
                name="pricebookcache_gin_trgm_idx",
                fields=['itemid', 'itemdescription', 'manufacturerpartnumber', 'vendor_id'],
                opclasses=['gin_trgm_ops', 'gin_trgm_ops', 'gin_trgm_ops', 'gin_trgm_ops']
            ),
        ]

运行测试时出现错误

psycopg2.errors.UndefinedObject: operator class "gin_trgm_ops" does not exist for access method "gin"

我看过这里https://docs.djangoproject.com/en/4.1/ref/databases/#migration-operation-for-adding-extensions,其中明确表示通过迁移完成,但我已禁用它。

另一种方法是使用模板数据库,但我真的不想这样做,因为这将使用 docker 容器在 gitlab 中自动运行,并且我不想在项目存储库之外维护另一个固定装置。

那么有没有一种方法可以在不运行迁移的情况下初始化数据库,或者是否可以使其运行完全不同的迁移以进行测试?

django
1个回答
0
投票

受到这个答案的启发。我定义了一个自定义测试运行器。然后重写

setup_databases
方法来手动启用扩展,在我的例子中是 trigram。

class CustomDiscoverRunner(DiscoverRunner):
    def setup_databases(self, **kwargs):
        """Enable postgres trigram extension for tests

        info:
            We use `MIGRATE: False` for faster test db creation,
            but this causes the migration that enables the trigram
            extension to not run. Manually enable that extension here.
        """
        databases = super().setup_databases(**kwargs)
        # I'm naively getting the first DB since we only have one
        # But you could loop through and find the exact DB you wish to use
        with databases[0][0].connection.cursor() as cursor:
            cursor.execute("CREATE EXTENSION IF NOT EXISTS pg_trgm;")

        return databases
© www.soinside.com 2019 - 2024. All rights reserved.