测试 Flask 登录和身份验证? [英] Testing Flask login and authentication?

查看:39
本文介绍了测试 Flask 登录和身份验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 Flask 应用程序并使用 Flask-security 进行用户身份验证(反过来在下面使用 Flask-login).

I'm developing a Flask application and using Flask-security for user authentication (which in turn uses Flask-login underneath).

我有一条需要身份验证的路由,/user.我正在尝试编写一个单元测试来测试对于经过身份验证的用户,这会返回适当的响应.

I have a route which requires authentication, /user. I'm trying to write a unit test which tests that, for an authenticated user, this returns the appropriate response.

在我的单元测试中,我正在创建一个用户并以该用户的身份登录:

In my unittest I'm creating a user and logging as that user like so:

from unittest import TestCase
from app import app, db
from models import User
from flask_security.utils import login_user

class UserTest(TestCase):
   def setUp(self):
       self.app = app
       self.client = self.app.test_client()
       self._ctx = self.app.test_request_context()
       self._ctx.push()

       db.create_all()

   def tearDown(self):
       if self._ctx is not None:
           self._ctx.pop()

       db.session.remove()
       db.drop_all()

   def test_user_authentication():
       # (the test case is within a test request context)
       user = User(active=True)
       db.session.add(user)
       db.session.commit()
       login_user(user)

       # current_user here is the user
       print(current_user)

       # current_user within this request is an anonymous user
       r = test_client.get('/user')

在测试中 current_user 返回正确的用户.但是,请求的视图总是返回一个 AnonymousUser 作为 current_user.

Within the test current_user returns the correct user. However, the requested view always returns an AnonymousUser as the current_user.

/user 路由定义为:

class CurrentUser(Resource):
    def get(self):
        return current_user  # returns an AnonymousUser

我很确定我只是没有完全理解测试 Flask 请求上下文的工作原理.我已经阅读了这个 Flask Request Context documentation 一堆,但我仍然不明白如何解决这个问题特定的单元测试.

I'm fairly certain I'm just not fully understanding how testing Flask request contexts work. I've read this Flask Request Context documentation a bunch but am still not understanding how to approach this particular unit test.

推荐答案

问题是 test_client.get() 调用导致推送一个新的请求上下文,所以你推送的那个您的测试用例的 setUp() 方法不是 /user 处理程序看到的方法.

The problem is that the test_client.get() call causes a new request context to be pushed, so the one you pushed in your the setUp() method of your test case is not the one that the /user handler sees.

我认为登录和注销测试添加消息 文档部分是最好的方法用于测试登录.这个想法是通过应用程序发送登录请求,就像普通客户端一样.这将负责在测试客户端的用户会话中注册登录用户.

I think the approach shown in the Logging In and Out and Test Adding Messages sections of the documentation is the best approach for testing logins. The idea is to send the login request through the application, like a regular client would. This will take care of registering the logged in user in the user session of the test client.

这篇关于测试 Flask 登录和身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆