Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django unit testing: AttributeError: 'WSGIRequest' object has no attribute 'user'

When running the tests i get outputted following error:

user = self.request.user AttributeError: 'WSGIRequest' object has no attribute 'user'

I have tried switching from MIDDLEWARE to MIDDLEWARE_CLASSES and vice versa. Currently, I'm running Django 2.1.

Also, I have tried switching middleware positions and it didn't help.

settings.py

MIDDLEWARE = (
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.auth.middleware.SessionAuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",  # to serve static files
)

test_views.py

from django.test import (TestCase,
                     RequestFactory
                     )
from mixer.backend.django import mixer

from .. import views
from accounts.models import User


class TestHomeView(TestCase):
    def test_anonymous(self):
        req = RequestFactory().get("/")
        resp = views.HomeView.as_view()(req)
        self.assertEquals(resp.status_code, 200,
                          "Should be callable by anyone")

    def test_auth_user(self):
        req = RequestFactory().get("/")
        req.user = mixer.blend("accounts.User")
        resp = views.HomeView.as_view()(req)
        self.assertTrue("dashboard" in resp.url,
                        "Should redirect authenticated user to /dashboard/")

error output

user = self.request.user AttributeError: 'WSGIRequest' object has no attribute 'user'

like image 391
pyropy Avatar asked Jan 14 '19 14:01

pyropy


1 Answers

In the first test test_anonymous, you are not actually setting the user. As per documentation https://docs.djangoproject.com/en/2.1/topics/testing/advanced/#the-request-factory, the middleware are not executed if you use RequestFactory and you have to set the user explicitly. So if you want to test again AnonymousUser, you should set request.user = AnonymousUser(). If you don't do this, the request object will not have the user attribute, and thus the error.

like image 112
Fran Avatar answered Oct 30 '22 19:10

Fran