烧瓶单元测试:如何测试来自登录用户的请求 [英] flask unit test: how to test request from logged in user

查看:187
本文介绍了烧瓶单元测试:如何测试来自登录用户的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的Flask Web应用程序编写一些单元测试,并试图测试匿名用户和登录用户发出的请求之间的响应差异。

I'm writing some unit tests for my Flask web application and I'm trying to test the differences in the response between a request made by an anonymous user and a logged in user.

我使用 Flask-Login 扩展来实现用户登录/登出。

I'm using the Flask-Login extension to implement the user login/logout.

显然我可以执行一个匿名请求,但是如何模拟来自登录用户的请求?

Obviously I'm able to perform an anonymous request, but how do I simulate a request from a logged in user?

我认为这足以发送头文件 session cookie,但不起作用。
$ b

I thought it was enough to send in the headers the session cookie, but it's not working.

headers = Headers({'Cookie':['WEBSITE_ID=%s; Domain=adsabs.harvard.edu; expires=Thu, 25-Apr-2213 16:53:22 GMT; Path=/' % cookie_value, 
                             'WEBSITE_ID=%s; Domain=.adsabs.harvard.edu; expires=Thu, 25-Apr-2213 16:53:22 GMT; Path=/' % cookie_value,
                             'session="A VERY LONG STRING"; Path=/; HttpOnly',
                 ]})
rv = app.test_client().get('/', headers=headers)

其中session cookie的值是我从真正的登录在我的浏览器中。

Where the session cookie value is a value I got from a real login in my browser.

我缺少什么?

What am I missing?

推荐答案

Flask-Login会在会话中查找 user_id ,您可以在测试中使用 session_transaction

Flask-Login looks for user_id in the session, you can set this in the tests using session_transaction:

with app.test_client() as c:
    with c.session_transaction() as sess:
        sess['user_id'] = 'myuserid'
        sess['_fresh'] = True # https://flask-login.readthedocs.org/en/latest/#fresh-logins
    resp = c.get('/someurl')

其中 myuserid 是您的 user object

这篇关于烧瓶单元测试:如何测试来自登录用户的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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