0

In a Django project, I want to override a setting for a unit test. From the Django documentation, it seems the recommended way seems to use a TestCase and using methods like modify_settings or override_settings. This is the example given:

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("/")
            # ...

When using Django TestCase (and override_setting) my test fixtures that are annotated using @pytest.fixture are no longer recognized.

This is a minimal example that reproduce my issue.

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

When calling self.my_client, I get the error: AttributeError: 'TestLogin' object has no attribute 'my_client'

I've already found this thread How to use pytest fixtures with django TestCase, but it doesn't give a solution to use a pytest.fixture explicitly in the context of a Django TestCase.

Any idea how to access my_client inside the TestLogin ?

skuallpa
  • 1,147
  • 3
  • 13
  • 28

0 Answers0