并行运行测试时的 Django 缓存隔离

Ant*_*des 12 django django-testing

当我并行运行测试时,我会遇到随机失败,因为一个测试干扰了另一测试的缓存。

我可以解决这个问题

@override_settings(
    CACHES={
        "default": {
            "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
            "LOCATION": "[random_string]",
        }
    },
)
Run Code Online (Sandbox Code Playgroud)

实际上,为了使其更小,我创建了一个@isolate_cache装饰器,它是override_settings.

但我仍然需要去装饰大量的测试用例。这很容易出错,因为正如我所说,失败是随机的。我可能会运行测试套件 100 次而没有错误,并认为一切正常,但我仍然可能忘记装饰测试用例,并且在某些时候它会随机失败。

我还考虑过创建自己的TestCase子类并仅将其用于我的所有测试用例。这提出了一个类似的问题:在某些时候有人会出于django.test.TestCase习惯继承,并且它可能不会在很长一段时间内失败。此外,我的一些测试继承自rest_framework.test.APITestCase(或其他类),因此没有单个测试用例子类。

有什么方法可以告诉 Django 在缓存的隔离部分中一劳永逸地运行每个测试用例吗?

aar*_*ron 10

您不需要“缓存的隔离部分”,只需在测试之间清除缓存即可。

这里有一些方法。

1. 子类TestCase

问题提到这是不希望的,但我仍然应该提到这种正确的方式。

from django.core.cache import cache
from django.test import TestCase


class CacheClearTestCase(TestCase):

    def tearDown(self):
        # super().tearDown()
        cache.clear()
Run Code Online (Sandbox Code Playgroud)

2. 补丁TestCase.tearDown

假设子类重写了tearDowncall super().tearDown(),你可以这样做。

在manage.py之前添加以下内容execute_from_command_line(sys.argv)

if sys.argv[1] == 'test':
    from django.test import TestCase
    from django.core.cache import cache
    TestCase.tearDown = cache.clear
Run Code Online (Sandbox Code Playgroud)

3. 子类TestSuite

TestSuite您可以在每次测试后通过子类化以覆盖_removeTestAtIndex并设置DiscoverRunner.test_suite为该子类来清除缓存。

在manage.py之前添加以下内容execute_from_command_line(sys.argv)

if sys.argv[1] == 'test':
    from unittest import TestSuite
    from django.core.cache import cache
    from django.test.runner import DiscoverRunner

    class CacheClearTestSuite(TestSuite):
        def _removeTestAtIndex(self, index):
            super()._removeTestAtIndex(index)
            cache.clear()

    DiscoverRunner.test_suite = CacheClearTestSuite
Run Code Online (Sandbox Code Playgroud)

为什么不需要缓存的隔离部分

需要明确的是,这不是并行运行测试引起的问题。

来自https://docs.djangoproject.com/en/4.0/ref/django-admin/#cmdoption-test-parallel

--parallel [N]

在单独的并行进程中运行测试。

来自https://docs.djangoproject.com/en/4.0/topics/cache/#local-memory-caching-1

请注意,每个进程都有自己的私有缓存实例,这意味着不可能进行跨进程缓存。