Django单元测试:AttributeError:'WSGIRequest'对象没有属性'user'

时间:2019-01-14 14:32:53

标签: django-testing

运行测试时,我输出以下错误:

user = self.request.user AttributeError:“ WSGIRequest”对象没有属性“ user”

我尝试从MIDDLEWARE切换到MIDDLEWARE_CLASSES,反之亦然。目前,我正在运行Django 2.1。

此外,我尝试过切换中间件的位置,但没有帮助。

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/")

错误输出

user = self.request.user AttributeError:“ WSGIRequest”对象没有属性“ user”

1 个答案:

答案 0 :(得分:0)

在第一个测试test_anonymous中,您实际上并没有设置用户。根据文档https://docs.djangoproject.com/en/2.1/topics/testing/advanced/#the-request-factory,如果使用RequestFactory,并且必须显式设置用户,则不会执行中间件。因此,如果要再次测试AnonymousUser,则应设置request.user = AnonymousUser()。如果您不这样做,则请求对象将没有request属性,从而导致错误。