本文介绍了带有django.test.client.login()的AnonymousUser的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试登录功能.

def setUpClass(cls):
    super(BasePage_loggedin, cls).setUpClass()
    cls.selenium = WebDriver()
    cls.client = Client()
    cls.user_1 = MyUser.objects.create_user(username='myself',password='12345')
    cls.client.login(username=cls.user_1.username, password=cls.user_1.password)

    # create session cookie:
    session = SessionStore()
    session[SESSION_KEY] = cls.user_1.pk
    session[BACKEND_SESSION_KEY] = settings.AUTHENTICATION_BACKENDS[0]
    session[HASH_SESSION_KEY] = cls.user_1.get_session_auth_hash()
    session.save()

    # Finally, create the cookie dictionary
    cookie = {
        'name': settings.SESSION_COOKIE_NAME,
        'value': session.session_key,
        'secure': False,
        'path': '/',
    }
    # add the session cookie
    cls.selenium.get('{}'.format(cls.live_server_url))
    cls.selenium.add_cookie(cookie)
    cls.selenium.refresh()
    cls.selenium.get('{}'.format(cls.live_server_url))

因此我可以通过登录页面,但是,当我执行request.user检查该用户的数据时,它是 AnonymousUser

So I can pass the login page, but then, when I do request.user to check the data for this user, it's an AnonymousUser

推荐答案

请检查您的settings.py并尝试以下代码.

Please check your settings.py and try below codes.

REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework.authentication.SessionAuthentication', # needed only up to the test env
            'rest_framework.authentication.TokenAuthentication',
        )
    }

这篇关于带有django.test.client.login()的AnonymousUser的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 17:18