简体   繁体   中英

Django Rest Framework - Testing client.login doesn't login user, ret anonymous user

Problem

So I am testing my drf app, and I am trying to test if my user created at the setUp method was logged in after using self.client.login(**creds) method. For some reason, I am not able to authenticate and login.

Background

I use the built-in django auth feature by providing a login template for my authentication/login process. I am currently using django2.2.3 and drf3.10.1 with python3.6.6

Keep in mind, the login processes works in a browser, and I am able to login without any problems.

The problem is consistent using django.test.TestCase in my other component of django tests.

api.tests.py

from rest_framework.test import APITestCase
from rest_framework.reverse import reverse as api_reverse
from django.contrib import auth

class AppAPITestCase(APITestCase):
    """
    testing for API endpoints
    """

    def setUp(self):
        new_user1_data = {
            "username": "dummy",
            "first_name": "a",
            "last_name": "dummy",
            "password": "randompassword",
            "email": "test@test.com",
        }

        new_user1 = User.objects.create_user(
            username=new_user1_data["username"],
            first_name=new_user1_data["first_name"],
            last_name=new_user1_data["last_name"],
            email=new_user1_data["email"],
            password=new_user1_data["password"]
        )

        self.new_student = Student.objects.create(user=new_user1)

    def test_get_list_auth(self):
        """
        testing retrieve functionality authenticated
        """
        # login student
        login_data = {
            "username": self.new_student.user.username,
            "password": self.new_student.user.password
        }
        login_response = self.client.login(
            username=login_data['username'], password=login_data['password'])
        if login_response is True:
            url = api_reverse("api-student:StudentListCreateApi")
            response = self.client.get(url)
            self.assertEqual(response.status_code, status.HTTP_200_OK)

        else:
            print("[!] Login failed!")

This will always output [!] Login Failed , when the test is being run.

If I used the following to retrieve the user, and log it, it returns as anonymous user

        user = auth.get_user(self.client)
        print("user: ", user)

Question

What am I doing wrong, how come I cannot authenticate and login during tests?

您应该使用set_password设置密码,以便在存储密码之前先对其进行哈希处理。

So the problem was actually the way I was logging in my user. I was using self.new_student.user.password in my login_data dictionary, and it is a hash.

Instead I used self.client.login(username=login_data['username'], password="randompassword")

And it worked!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM