必须安装pytest-django并配置DJANGO_SETTINGS_MODULE,测试文件需以test_开头或_test.py结尾,使用client等fixture而非手动实例化,数据库操作依赖django_db标记。

怎样让 pytest 正确识别并运行 Django 测试用例?
pytest 默认不理解 Django 的测试上下文,直接运行 pytest 会报 django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured。根本原因是没加载 Django 配置。
- 必须在项目根目录(含
manage.py)下运行命令,且需确保pytest-django已安装:pip install pytest-django - 在项目根目录创建
pytest.ini,内容必须包含:[tool:pytest] DJANGO_SETTINGS_MODULE = myproject.settings python_files = test_*.py python_classes = Test* python_functions = test_*
-
myproject.settings要替换成你真实的 settings 模块路径;若用开发/测试专用配置(如myproject.settings.test),这里就得写全 - 不要依赖
manage.py test的行为——pytest 启动时不会自动调用django.setup(),全靠pytest-django插件和配置驱动
如何避免测试数据库残留或迁移失败?
Django 测试默认使用内存 SQLite(:memory:),但一旦你在 settings.test.py 里显式配置了 PostgreSQL 或 MySQL,就容易卡在迁移或权限上。
- pytest-django 默认为每个测试 session 创建全新数据库(哪怕用 PostgreSQL),但前提是:用户有
CREATEDB权限(PostgreSQL)或对应库的CREATE权限(MySQL) - 若权限受限,强制回退到 SQLite:在
pytest.ini加一行addopts = --ds=myproject.settings.test,并在settings.test.py中设DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}} - 切勿在测试中手动调用
call_command('migrate')—— pytest-django 会在 setup 阶段自动同步模型,重复 migrate 会导致Relation "xxx" already exists错误
怎么写一个能真实触发视图逻辑的 API 测试?
用 TestCase 写的测试能跑通,但迁移到 pytest 后常发现 self.client.get() 返回 404 或 500,不是路由问题,而是 client 初始化方式不对。
将测试、lint、构建和文档流程编码为命名的Python会话,以便人类和代理每次运行相同的workflow。
- 必须用
pytest-django提供的clientfixture,不是自己实例化Client():def test_api_list_view(client): response = client.get('/api/items/') assert response.status_code == 200 assert len(response.json()) == 0 - 若需登录态,用
userfixture(需先在 conftest.py 声明)或手动登录:from django.contrib.auth.models import User def test_authenticated_view(client): user = User.objects.create_user('test', 't@test.com', 'pass') client.force_login(user) response = client.get('/dashboard/') assert response.status_code == 200 - 注意:URL 必须是完整路径(如
/api/items/),不能省略结尾斜杠(如果 URLconf 开启了APPEND_SLASH=True)
为什么 model 层测试总提示 'Table xxx doesn't exist'?
这通常发生在你用了 TransactionTestCase 或手动操作数据库事务之后,pytest-django 的数据库重置机制被干扰。
- 默认所有测试继承自
TestCase(即 pytest 的django_dbfixture 行为),它用事务 rollback 实现快速隔离;但如果你在测试中调用了transaction.atomic()或执行了ALTER TABLE类 DDL,rollback 失效,后续测试就会看到“表不存在” - 解决方案只有两个:
- 改用
@pytest.mark.django_db(transaction=True)显式声明该测试需要真实事务提交(性能慢,慎用) - 彻底避免在测试中执行 DDL 或跨事务 DB 操作;model 层测试应只做
Model.objects.create()、.save()、.delete()这类 ORM 操作
- 改用
- 另一个常见诱因:在
conftest.py里写了全局django_db_setuphook 并错误清空了表结构——除非你明确要做 schema-level 初始化,否则别碰这个 hook
Django + pytest 的坑基本都藏在配置加载时机、数据库生命周期和 client 初始化这三个地方,改错一个点,其他测试可能连锁失效。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










