django数据库单元测试报错:django.test.testcases.DatabaseOperationForbidden:

在Django4.2.1版本中,由于SimpleTestCase默认不允许数据库查询以保持测试数据的一致性,导致ORM操作的单元测试失败。官方建议通过设置allow_database_queries=True来允许查询,但该属性在新版本已被废弃。解决方法是为测试类添加databases=__all__,确保了正确的测试隔离。
摘要由CSDN通过智能技术生成

问题:django工程内,编写UT对ORM操作方法进行测试。但运行报错:

django.test.testcases.DatabaseOperationForbidden: Database queries to 'db_name' are not allowed in this test. Add 'db_name' to xxx.tests.test_xxx.XXXTest.databases to ensure proper test isolation and silence this failure.

问题原因:

Django SimpleTestCase中,为保证db数据一致性,默认禁止db查询操作。因为单测运行是非事务状态

官方解释:

SimpleTestCase disallows database queries by default. This helps to avoid executing write queries which will affect other tests since each SimpleTestCase test isn’t run in a transaction. If you aren’t concerned about this problem, you can disable this behavior by setting the allow_database_queries class attribute to True on your test class.

解决方法:

设置TestCase class属性 allow_database_queries=True


尝试使用上述方法,问题没有被解决。查询资料,早期SimpleTestCase依赖allow_database_queries,后续逐步淡化和舍弃。而我使用Django版本较高(4.2.1),不支持该字段

查询资料,添加 databases = '__all__' 后,Solve It !

参考资料:

Assertion error while testing Django views - Stack Overflow

Database fixtures are run when they shouldn't be for SimpleTestCase unit tests · Issue #472 · pytest-dev/pytest-django · GitHub

Testing tools | Django documentation | Django

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值