在功能测试中跳过登录过程

Skip Login Process In Functional Tests

我正在使用 allauth 并开始进行一些功能测试。我已经测试了登录功能,现在想测试其他东西,但我找不到一种方法来开始对预认证用户进行功能测试。我尝试使用以下代码,但我无法让用户自动登录。

def create_pre_authenticated_session(self, username, email):
        session_key = create_pre_authenticated_session(username, email)

        # to set a cookie we need to first visit the domain
        self.browser.get(self.live_server_url + "/")
        self.browser.add_cookie(dict(
            name=settings.SESSION_COOKIE_NAME,
            value=session_key,
            path='/',
        ))
def create_pre_authenticated_session(username, email):
    user = User.objects.create(username=username, email=email)
    session = SessionStore()
    session[SESSION_KEY] = user.pk
    session[BACKEND_SESSION_KEY] = settings.AUTHENTICATION_BACKENDS[0]
    session.save()
    return session.session_key

谢谢。

您可以使用force_login方法登录用户

If your site uses Django’s authentication system, you can use the force_login() method to simulate the effect of a user logging into the site. Use this method instead of login() when a test requires a user be logged in and the details of how a user logged in aren’t important.

Unlike login(), this method skips the authentication and verification steps: inactive users (is_active=False) are permitted to login and the user’s credentials don’t need to be provided.

self.client.force_login(user)

Add the cookie to browser afterwards

cookie = self.client.cookies['sessionid']
self.browser.add_cookie({'name': 'sessionid', 'value': cookie.value, 'secure': False, 'path': '/'})
self.browser.refresh()