首页 > 解决方案 > 在 django 2.2 中的此测试中不允许对“缓存”进行数据库查询

问题描述

我正在将项目从 django 1.11 迁移到 django 2.2。我们有基于数据库的缓存,可以在不同的数据库上运行(不是默认的)。运行测试时,我们收到以下错误:

AssertionError: Database queries to 'cache' are not allowed in this test. Add 'cache' to users.tests.UserLogTestCase.databases to ensure proper test isolation and silence this failure.

将“缓存”数据库添加到 TestCase 的数据库变量可以解决问题(或将其设置为“ __all__”),问题是这必须在每个测试中完成。

有没有其他(更全球性的)方法来解决这个问题?

标签: djangodjango-2.2

解决方案


我刚刚遇到了这个问题。在我的环境中,我很久以前就放弃并从一个公共类继承所有测试用例,MyTestCase. 我使用 mixins 添加功能:

class MyTestCase(django.test.TestCase, ViewTestMixin, AssertResponseStatusMixin, CustomAssertions):

    pass


class MyAPITestCase(rest_framework.test.APITestCase, ViewTestMixin, AssertResponseStatusMixin, CustomAssertions, RedisClearMixin):

    pass

我将databases变量添加到这些基类以全局应用。


推荐阅读