如何在pytest-django中统计模型对象数量?测试返回0的问题排查
问题原因与解决方案
核心原因:pytest运行测试时会使用独立的测试数据库,这个数据库默认是空的,和你在
python manage.py shell中使用的开发数据库完全分离,所以测试里查询不到现有数据。解决方案1:手动在测试中创建数据
修改测试代码,在断言前生成需要的测试对象:import pytest from .models import Organization @pytest.mark.django_db def test_organization(): # 创建10个测试用Organization对象(替换为你的模型实际字段) for i in range(10): Organization.objects.create(name=f"测试组织{i}") assert Organization.objects.count() == 10解决方案2:使用Django Fixture加载预定义数据
- 先从开发数据库导出数据到fixture文件:
python manage.py dumpdata myapp.Organization --indent 2 > myapp/fixtures/organizations.json - 在测试中加载fixture数据:
import pytest from django.core.management import call_command from .models import Organization @pytest.fixture def load_org_data(): call_command("loaddata", "organizations.json") @pytest.mark.django_db def test_organization(load_org_data): assert Organization.objects.count() == 10
- 先从开发数据库导出数据到fixture文件:
注意事项:禁止让测试直接使用开发数据库,这会破坏测试隔离性,导致结果不稳定,还可能污染开发数据。
内容的提问来源于stack exchange,提问作者jjk
相关产品推荐
相关产品推荐

