在修改Django设置进行单元测试时如何结合Django TestCase使用fixture?

问题描述 投票:0回答:1

在 Django 项目中,我想覆盖单元测试的设置。从 Django 文档来看,推荐的方法似乎是使用

TestCase
并使用
modify_settings
override_settings
等方法。这是给出的例子:

from django.test import TestCase


class MiddlewareTestCase(TestCase):
    def test_cache_middleware(self):
        with self.modify_settings(
            MIDDLEWARE={
                "append": "django.middleware.cache.FetchFromCacheMiddleware",
                "prepend": "django.middleware.cache.UpdateCacheMiddleware",
                "remove": [
                    "django.contrib.sessions.middleware.SessionMiddleware",
                    "django.contrib.auth.middleware.AuthenticationMiddleware",
                    "django.contrib.messages.middleware.MessageMiddleware",
                ],
            }
        ):
            response = self.client.get("/")
            # ...

使用 Django

TestCase
(和 override_setting)时,使用
@pytest.fixture
注释的测试装置不再被识别。

这是重现我的问题的最小示例。

from django.test import TestCase, override_settings
from rest_framework.test import APIClient

@pytest.fixture
def my_client():
    return APIClient()


@pytest.mark.usefixtures("my_client")
class TestLogin(TestCase):
    def test_jwt_expiration(self):
        simple_jwt_settings = settings.SIMPLE_JWT
        # Force a very short lifetime for the access token
        simple_jwt_settings['ACCESS_TOKEN_LIFETIME'] = datetime.timedelta(milliseconds=1)
        with override_settings(SIMPLE_JWT=simple_jwt_settings):
            response = self.my_client.get("/login")
            assert response.status_code == 200

            # ...
            sleep(2/1000)
            # ... test that the access token expired for further calls

调用

self.my_client
时,出现错误:
AttributeError: 'TestLogin' object has no attribute 'my_client'

我已经找到了这个线程如何将 pytest 装置与 django TestCase 一起使用,但它没有给出在 Django 上下文中显式使用

pytest.fixture
的解决方案
TestCase

知道如何访问

my_client
内的
TestLogin
吗?

python django unit-testing settings fixtures
1个回答
0
投票

在 Django TestCase 中,您通常使用在每个测试之前执行的 setUp 方法来创建您需要的“装置”。

在您的情况下,您的测试类 TestLogin(TestCase):

class TestLogin(TestCase):
    def setUp(self):
        self.my_clent = APIClient()
    def test_jwt_expiration(self):
        simple_jwt_settings = settings.SIMPLE_JWT
        # Force a very short lifetime for the access token
        simple_jwt_settings['ACCESS_TOKEN_LIFETIME'] = datetime.timedelta(milliseconds=1)
        with override_settings(SIMPLE_JWT=simple_jwt_settings):
            response = self.my_client.get("/login")
            assert response.status_code == 200

            # ...
            sleep(2/1000)
            # ... test that the access token expired for further calls

根据其他需求,您可能会查找如何使用为所有测试用例运行一次的

setUpClass
setUpTestData

本文对此进行了详细介绍:https://medium.com/an-engineer-a-reader-a-guy/django-test-fixture-setup-setupclass-and-setuptestdata-72b6d944cdef

© www.soinside.com 2019 - 2024. All rights reserved.