运行测试时,我输出以下错误:
user = self.request.user AttributeError:“ WSGIRequest”对象没有属性“ user”
我尝试从MIDDLEWARE
切换到MIDDLEWARE_CLASSES
,反之亦然。目前,我正在运行Django 2.1。
此外,我尝试过切换中间件的位置,但没有帮助。
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
)
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”
答案 0 :(得分:0)
在第一个测试test_anonymous
中,您实际上并没有设置用户。根据文档https://docs.djangoproject.com/en/2.1/topics/testing/advanced/#the-request-factory,如果使用RequestFactory
,并且必须显式设置用户,则不会执行中间件。因此,如果要再次测试AnonymousUser
,则应设置request.user = AnonymousUser()
。如果您不这样做,则请求对象将没有request
属性,从而导致错误。