使用Pytest时如何强制Django自动化测试使用Test数据库?
强制Django自动化测试使用指定Test数据库的解决方案
方案一:利用Django原生配置指定测试数据库
Django内置支持针对测试场景配置数据库,无需额外编写复杂代码。
方法1:修改settings.py,让测试默认复用已配置的test数据库
在default数据库配置中添加TEST节点,直接指定使用已定义的test数据库别名:
DATABASES = { "default": { "ENGINE": "django.db.backends.mysql", "NAME": ENV.MYSQL_DSN.path.lstrip("/"), "USER": ENV.MYSQL_DSN.user, "PASSWORD": ENV.MYSQL_DSN.password, "HOST": ENV.MYSQL_DSN.host, "PORT": ENV.MYSQL_DSN.port, # 新增:让测试环境复用test数据库的配置 "TEST": { "MIRROR": "test" } }, 'test': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test_db', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432', } }
配置完成后,Django运行测试时会自动切换到test数据库。
方法2:命令行直接指定测试数据库
运行测试时通过参数强制指定使用test数据库:
- 原生Django测试命令:
python manage.py test --database=test
- 使用pytest-django时:
DJANGO_DATABASE=test pytest
也可以在pytest.ini中全局配置:
[pytest] django_db_database = test
方案二:用pytest fixture动态覆盖数据库配置
如果需要在测试代码中动态切换,修改django_db_setup fixture(需放在conftest.py中):
import pytest from django.conf import settings from django.db import connections @pytest.fixture(scope='session') def django_db_setup(): # 将默认数据库替换为test的配置 test_config = settings.DATABASES['test'].copy() settings.DATABASES['default'] = test_config # 强制刷新数据库连接 connections['default'].close() del connections['default'] yield
前提:需提前手动创建好test_db这个PostgreSQL数据库。
方案三:自动化创建PostgreSQL测试数据库
如果需要自动完成测试库的创建/销毁,可扩展fixture逻辑:
import pytest import psycopg2 from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT from django.conf import settings from django.db import connections @pytest.fixture(scope='session') def django_db_setup(): # 连接PostgreSQL默认库,创建测试库 conn = psycopg2.connect( dbname='postgres', user='username', password='password', host='localhost', port='5432' ) conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cur = conn.cursor() # 避免重复创建报错 cur.execute("SELECT 1 FROM pg_database WHERE datname = 'test_db'") if not cur.fetchone(): cur.execute("CREATE DATABASE test_db") cur.close() conn.close() # 切换到测试库作为默认数据库 test_config = settings.DATABASES['test'].copy() settings.DATABASES['default'] = test_config connections['default'].close() del connections['default'] yield # 可选:测试结束后删除数据库 conn = psycopg2.connect( dbname='postgres', user='username', password='password', host='localhost', port='5432' ) conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cur = conn.cursor() cur.execute("DROP DATABASE IF EXISTS test_db") cur.close() conn.close()
注意:配置的PostgreSQL用户需要具备创建、删除数据库的权限。
关键注意事项
- 确保PostgreSQL服务处于运行状态,配置的账号密码正确。
- 使用pytest时需安装
pytest-django插件:pip install pytest-django。 - 测试数据库必须独立于生产数据库,避免数据污染。
内容的提问来源于stack exchange,提问作者HardWorker
相关产品推荐
相关产品推荐

