问题: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 theallow_database_queries
class attribute toTrue
on your test class.
解决方法:
设置TestCase class属性 allow_database_queries=True
尝试使用上述方法,问题没有被解决。查询资料,早期SimpleTestCase依赖allow_database_queries,后续逐步淡化和舍弃。而我使用Django版本较高(4.2.1),不支持该字段
查询资料,添加 databases = '__all__' 后,Solve It !
参考资料: