[英]How to apply migrations in django, pytest, postgres
How to auto-apply migrations to test database?如何自动将迁移应用到测试数据库?
Error错误
django.db.utils.ProgrammingError: relation "users" does not exist
E LINE 1: ...ers"."phone_confirmed", "users"."last_login" FROM "users" WH...
pytest.ini pytest.ini
[pytest]
DJANGO_SETTINGS_MODULE = ma_saas.settings
addopts = --migrations
database_fixture.py database_fixture.py
import pytest
from django.db import connections
import psycopg2
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
def run_sql(sql):
conn = psycopg2.connect(database='postgres')
conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cur = conn.cursor()
cur.execute(sql)
conn.close()
@pytest.yield_fixture(scope='session')
def django_db_setup():
from django.conf import settings
settings.DATABASES['default']['NAME'] = 'test_db'
run_sql('DROP DATABASE IF EXISTS test_db')
run_sql('CREATE DATABASE test_db')
yield
for connection in connections.all():
connection.close()
run_sql('DROP DATABASE test_db')
I think it is better to create a database and apply its migrations in the database_fixture better.我认为最好创建一个数据库并将其迁移应用到 database_fixture 中。
It was not so obvious.这不是那么明显。 But we should use django_db_blocker
to run commands.但是我们应该使用django_db_blocker
来运行命令。
from django.core.management import call_command
@pytest.yield_fixture(scope='session') # or @pytest.fixture(scope='session')
def django_db_setup(django_db_blocker):
from django.conf import settings
test_database_name = 'test_db'
settings.DATABASES['default']['NAME'] = test_db
run_sql(f'DROP DATABASE IF EXISTS {test_db}')
run_sql(f'CREATE DATABASE {test_db}')
with django_db_blocker.unblock():
call_command('migrate', '--noinput')
yield
for connection in connections.all():
connection.close()
run_sql(f'DROP DATABASE {test_db}')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.