我的Flask应用程序中有一些基于会话管理的功能。例如,当来自会话的请求传入时,更新字典中的值(datetime.now()值)
def update_existing_session(active_sessions):
"""[Updates the value of the session in the management dictionary with
a current timestamp]
Args:
active_sessions ([dictionary]): [Dictionary containing session info.
key = session token, value = last request timestamp]
Returns:
active_sessions ([dictionary]): [Updated dictionary of active sessions.
Key = session token, value = last request timestamp]
"""
session_name = session.get('public_user')
logging.info("New request from " + str(session_name))
active_sessions[session_name] = datetime.now()
return active_sessions
当我尝试单元测试这个或类似的方法(也使用会话)时,例如下面的例子,我得到以下错误:
def test_generate_new_session(self):
active_sessions = {}
active_sessions = session_management.generate_new_session(active_sessions)
self.assertEqual(len(active_sessions), 1)
RuntimeError: Working outside of request context.
This typically means that you attempted to use functionality that needed
an active HTTP request. Consult the documentation on testing for
information about how to avoid this problem.
如何使用活动HTTP请求进行单元测试,以生成会话,从而使代码运行
您要使用Flask的test client:
烧瓶文档通常建议您使用PyTest,这样可以更轻松地设置夹具。文档中的示例:
但简单的回答是,只需在
app
对象上调用test_client()
相关问题 更多 >
编程相关推荐