[英]how to set up postgres database with pytest-django?
我希望 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'>
您可以使用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'))
我希望這可以幫助你。
我一直在嘗試完成同樣的事情,並conftest.py
正常工作(在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()
。
另一種解決方案是將擴展添加到 postgres 模板數據庫。 這意味着使用CREATE DATABASE
命令創建的所有測試數據庫都將具有指定的擴展名:
psql -d template1 -c 'CREATE EXTENSION IF NOT EXISTS pg_trgm;'
現在,每當 pytest 創建測試數據庫時,都會在運行遷移之前安裝pg_trgm
擴展。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.