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.
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' object has no attribute 'user'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With