Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Test Case Error 'WSGIRequest' object has no attribute 'session'

I'm trying to write some tests for my django app and it's throwing up an error:

File "/Users/croberts/.virtualenvs/litem/lib/python3.4/site-packages/django/contrib/auth/__init__.py", line 101, in login
    if SESSION_KEY in request.session:
AttributeError: 'WSGIRequest' object has no attribute 'session'

Here's my code that I am trying to run:

class SimpleTest(TestCase):
    def setUp(self):
        self.request_factory = RequestFactory()

    def test_signup(self):
        request = self.request_factory.post("/signup/", {
            "email": "[email protected]", 
            "password": "password", 
            "password-confirm": "password", 
            "firm": "big law firm"})
        response = signup_user(request)
        user = User.objects.get(email="[email protected]")
        self.assertEqual(user.username, "[email protected]")
        self.assertEqual(user.firm, "big law firm")
        self.assertEqual(response.status_code, 302) #if it's successful it redirects.

Here's my middleware's:

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    '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',
]

and my installed apps:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'patents',
]
like image 625
Chase Roberts Avatar asked Feb 26 '16 19:02

Chase Roberts


1 Answers

Try using the test client instead of the request factory. This has the advantage of testing your URL config as well.

class SimpleTest(TestCase):
    def test_signup(self):
        response = self.client.post("/signup/", {
            "email": "[email protected]", 
            "password": "password", 
            "password-confirm": "password", 
            "firm": "big law firm"})
        user = User.objects.get(email="[email protected]")
        self.assertEqual(user.username, "[email protected]")
        self.assertEqual(user.firm, "big law firm")
        self.assertEqual(response.status_code, 302) #if it's successful it redirects.
like image 50
Alasdair Avatar answered Sep 21 '22 23:09

Alasdair