jeudi 18 juillet 2019

Django test returns an AnonymousUser instance instead of the new user

Important info: Django ver 2.2.2, session and auth middleware activated, Custom User model is standart AbstractUser with added custom fields, nothing else is changed in AbstractUser.

I am trying to implement a Django Test for my view, there's a view definition:

from django.shortcuts import render, redirect

from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User, Group
from django.contrib.auth import login, logout, authenticate

from .models import CustomUser


def listreport(request):
    curuser = request.user
    print(curuser)
    return render(request, 'fettwa/inmin/listreport.html')

The test code is this (I think I got the intendation wrong while copypasting here):

from django.test import TestCase, Client
from fettwa import models, forms, views
from fettwa.models import CustomUser
from django.contrib import auth
from django.contrib.auth.models import User, Group

class Auth_Test(TestCase):
     def test_client(self):
        self.user = CustomUser.objects.create_user(username='test_client', password='pass', role=0)
        user = Client().login(username='test_client', password='pass')
        print(self.user.password)
        print(self.user.username)
        if user:
             print("Client-like user successfully created and login")
        Client().get('/listreport')

All that code gives me this output (AnonymousUser in view can be seen):

Creating test database for alias 'default'...
System check identified no issues (0 silenced).
Client-like user successfully created and login
AnonymousUser
<HttpResponse status_code=200, "text/html; charset=utf-8">
.
----------------------------------------------------------------------
Ran 1 test in 0.721s

OK
Destroying test database for alias 'default'...

Aucun commentaire:

Enregistrer un commentaire