Search code examples
djangodjango-testing

django tests: client request is an empty string instead of an WSGIRequest object


I am working on a django project for which I created an app that is used in other projects. The app and the project have their own repository and folder.

I want to write tests that are specific to the app of that form:

from django.test import TestCase
from django.urls import reverse

class SignUpTest(TestCase):

    def test_my_signup_get2(self):
        response = self.client.get(reverse('signup'))
        self.assertEqual(response.status_code, 200)

When I run such tests from the folder of my app, the request object generated is an empty string, which will cause the test to fail. Within the logic of the project, the request.user is being accessed, which does not exist on a string.

When i run the exact same tests from the project folder where this app is used, the request object is a WSGIRequest object and the test succeeds, as the request.user is present.

How can I make sure that the request is always a WSGIRequest?


Solution

  • It was a simple issue in settings.py. I hadn't added the same context processors in the app I was testing and the project that was using the app: context_processors.request was missing.

    TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "OPTIONS": {
            "context_processors": [
                # Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
                # list if you haven't customized them:
                # ...
                "django.template.context_processors.request", # <= this was missing
                # ... 
            ],
        },
    }
    

    ]