【问题标题】:how to set up postgres database with pytest-django?如何使用 pytest-django 设置 postgres 数据库?
【发布时间】:2017-01-30 15:55:22
【问题描述】:

我希望 pytest-django 在创建测试数据库时安装 Postgres 扩展。我一直在使用 conftest.py 试图让它工作,但我被卡住了。

我的 conftest.py 位于项目的顶层(与 manage.py 相同的目录),并且包含:

from django.db import connection
import pytest_django
@pytest.fixture(scope='session')
def django_db_setup(*args, **kwargs):
    pytest_django.fixtures.django_db_setup(*args, **kwargs)
    cursor = connection.cursor()
    cursor.execute("create extension pg_trgm")

但是当我运行它时,我得到:

_pytest.vendored_packages.pluggy.PluginValidationError: unknown hook 'pytest_django' in plugin <module 'conftest' from '/path/to/my/conftest.py'>

【问题讨论】:

    标签: pytest-django


    【解决方案1】:

    您可以使用pre_migrate 信号。例如:

    from django.db.models.signals import pre_migrate
    from django.apps import apps
    
    def app_pre_migration(sender, app_config, **kwargs):
    
        cur = connection.cursor()
        cur.execute('CREATE EXTENSION IF NOT EXISTS pg_trgm;')
    
    pre_migrate.connect(app_pre_migration, sender=apps.get_app_config('app'))
    

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

      我一直在尝试完成同样的事情,并且成功了(conftest.py):

      @pytest.fixture(scope="session")
      def django_db_setup(django_db_setup, django_db_blocker):
          """Test session DB setup."""
          with django_db_blocker.unblock():
              with connection.cursor() as cursor:
                  cursor.execute("CREATE EXTENSION IF NOT EXISTS citext;")
      

      这里的关键是您必须使用与标准pytest-django 夹具相同的名称来命名您的自定义夹具,但还要包含默认夹具作为参数。这是运行标准夹具的方式,而不是导入和调用它。我还发现这失败了,除非我运行 django_db_blocker.unblock()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-23
        • 2011-12-29
        • 2021-12-29
        • 2014-05-28
        • 2022-11-26
        • 2015-03-23
        • 2011-12-31
        • 2021-02-18
        相关资源
        最近更新 更多