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

随声附和 提交于 2020-02-05 03:31:30

问题


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'


回答1:


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.



来源:https://stackoverflow.com/questions/54183451/django-unit-testing-attributeerror-wsgirequest-object-has-no-attribute-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!