gpt4 book ai didi

python - flask ,flask_login,pytest : How do I set flask_login's current_user?

转载 作者:行者123 更新时间:2023-12-04 14:46:55 32 4
gpt4 key购买 nike

我正在尝试使用 pytest 对我的 Flask 应用程序进行单元测试。我有以下端点测试用例,需要来自 flask_logincurrent_user 的信息:

def test_approval_logic():
with app.test_client() as test_client:
app_url_put = '/requests/process/2222'

with app.app_context():
user = User.query.filter_by(uid='xxxxxxx').first()
with app.test_request_context():
login_user(user)
user.authenticated = True
db.session.add(user)

data = dict(
state='EXAMPLE_STATE_NAME',
action='approve'
)
resp = test_client.put(app_url_put, data=data)
assert resp.status_code == 200

test_request_context 中,我能够正确设置 current_user。但是,这个测试失败了,因为在处理 PUT 的 requests View 中,没有登录用户和 500 错误结果。错误消息是,AttributeError: 'AnonymousUserMixin' object has no attribute 'email'。有人可以解释为什么 current_user 消失以及我如何正确设置它吗?

最佳答案

使用测试客户端发送请求

当前session未绑定(bind) test_client , 所以请求使用了一个新的 session 。

在客户端设置 session cookie,以便 Flask 可以为请求加载相同的 session :

from flask import session

def set_session_cookie(client):
val = app.session_interface.get_signing_serializer(app).dumps(dict(session))
client.set_cookie('localhost', app.session_cookie_name, val)

用法:

# with app.test_client() as test_client:                            # Change these
# with app.app_context(): #
# with app.test_request_context(): #
with app.test_request_context(), app.test_client() as test_client: # to this
login_user(user)
user.authenticated = True
db.session.add(user)

data = dict(
state='EXAMPLE_STATE_NAME',
action='approve'
)
set_session_cookie(test_client) # Add this
resp = test_client.put(app_url_put, data=data)

关于with app.test_request_context()的兼容性

我。 with app.test_client()

with app.test_client()保留请求的上下文(Flask 文档:Keeping the Context Around),因此在退出内部 with app.test_request_context() 时会出现此错误:

AssertionError: Popped wrong request context. (<RequestContext 'http://localhost/requests/process/2222' [PUT] of app> instead of <RequestContext 'http://localhost/' [GET] of app>)

相反,输入 app.test_request_context()之前app.test_client()如上所示。

二。 with app.app_context()

with app.test_request_context()已经推送了一个应用上下文,所以 with app.app_context()是不必要的。

在不发送请求的情况下使用测试请求上下文

来自 https://flask.palletsprojects.com/en/2.0.x/api/#flask.Flask.test_request_context :

This is mostly useful during testing, where you may want to run a function that uses request data without dispatching a full request.

用法:

data = dict(
state='EXAMPLE_STATE_NAME',
action='approve'
)
with app.test_request_context(data=data): # Pass data here
login_user(user)
user.authenticated = True
db.session.add(user)

requests_process(2222) # Call function for '/requests/process/2222' directly

关于python - flask ,flask_login,pytest : How do I set flask_login's current_user?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69859412/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com