[英]Why use Flask's app.test_client() over requests.Session() for testing
如果requests.Session()
可以处理cookie并且几乎完成app.test_client()
所做的一切。 那为什么要使用app.test_client()
?
经过一番挖掘后,我想我找到了一个很好的理由来使用app.test_client()
以及Flask提供的其他一些上下文管理器。
app.test_client()
允许您通过其上下文管理器访问本地上下文当尝试访问_request_ctx_stack
( 请求上下文堆栈)上的变量时,这非常有用。 例如request
和session
上下文本地。
一些扩展还在_request_ctx_stack
上存储变量。 例如, flask_login存储current_user
, flask_stateless_auth将current_stateless_user
存储在请求上下文堆栈中。
from flask import request
from flask_stateless_auth import current_stateless_user
with app.test_client() as c:
test_path = '/resource_for_authenticated_users'
c.get(test_path)
assert request.path == test_url
assert flask.session is not None # You can also access the session context local from here
assert current_stateless_user is not None
如果在没有test_client()
上下文管理器的情况下调用它,则会在弹出_request_ctx_stack
后尝试访问请求本地上下文时抛出运行时错误。 此外, current_stateless_user
将返回None
app.app_context()
同样,您可以通过app.app_context()
上下文管理器访问存储在应用程序上下文中的app.app_context()
,如下所示:
from my_app.db import db # db connections are commonly stored on the `_app_ctx_stack`
with app.app_context():
db.create_tables()
assert db.session
assert db.query.MyTable.all()
您还可以访问应用程序上下文全局变量 (通常用于存储不在跨session
全局等多个请求中使用的应用程序相关全局变量)
with app.app_context():
assert g.my_global_app_var
test_request_context()
然后你有app.test_request_context()
上下文管理器,它用于临时激活请求上下文。 这是官方文档最好的解释。
app.test_client().session_transaction()
最后,还有session_transaction()
上下文管理器。 这通常用于修改会话对象。 这应该嵌套在app.test_client()
。
__exit__()
方法时,会安全地存储会话。
来自docs的示例:
with app.test_client() as c:
with c.session_transaction() as sess:
sess['a_key'] = 'a value'
# once this is reached the session was stored
test_client已预先安装到烧瓶中,这使人们可以更轻松地快速测试他们的程序。 请求实用程序和test_client服务器都具有相同的功能,因此使用情况仅基于个人偏好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.