python - 使用 Pytest 测试 Flask 会话
问题描述
目前我正在做一个 Flask 项目,需要做一些测试。
我正在努力的测试是关于 Flask Sessions 的。
我有这样的看法:
@blue_blueprint.route('/dashboard')
"""Invoke dashboard view."""
if 'expires' in session:
if session['expires'] > time.time():
pass
else:
refresh_token()
pass
total_day = revenues_day()
total_month = revenues_month()
total_year = revenues_year()
total_stock_size = stock_size()
total_stock_value = stock_value()
mean_cost = total_stock_value/total_stock_size
return render_template('dashboard.html.j2', total_day=total_day, <br> total_month=total_month, total_year=total_year, total_stock_size=total_stock_size, total_stock_value=total_stock_value, mean_cost=mean_cost)
else:
return redirect(url_for('blue._authorization'))
并进行此测试:
def test_dashboard(client):
with client.session_transaction(subdomain='blue') as session:
session['expires'] = time.time() + 10000
response = client.get('/dashboard', subdomain='blue')
assert response.status_code == 200
我目前的 conftest.py 是:
@pytest.fixture
def app():
app = create_app('config_testing.py')
yield app
@pytest.fixture
def client(app):
return app.test_client(allow_subdomain_redirects=True)
@pytest.fixture
def runner(app):
return app.test_cli_runner(allow_subdomain_redirects=True)
但是,当我执行测试时,我得到的是 302 状态码,而不是预期的 200 状态码。
所以我的问题是如何正确传递会话值?
OBS:应用程序正常运行,会话的 if 语句工作正常。
解决方案
我找到了解决方案,我想与您分享答案。
在 API 文档测试客户端中说:
当与 with 语句结合使用时,这将打开一个会话事务。这可用于修改测试客户端使用的会话。离开 with 块后,会话将被存储回来。
对于这项工作,我们应该将断言放在 with 语句 not in 之后,所以代码应该是:
def test_dashboard(client):
with client.session_transaction(subdomain='blue') as session:
session['expires'] = time.time() + 10000
response = client.get('/dashboard', subdomain='blue')
assert response.status_code == 200
这个简单的缩进解决了我的问题。
推荐阅读
- linux - wget 现在自动将输出重定向到日志文件,如何返回到下面的输出
- raspberry-pi2 - how to modify pocketsphinx continuous.c
- dsl - 我需要在哪里设置 karate.config.dir 以在多个环境中运行我的测试
- azure - You have no keys in this region yet
- javascript - 如何使用 BTN 将文本从一个文本字段输入复制到另一个?
- qt - GeometryRenderer Why render lines, but not Triangles
- r - R中分组数据和聚合数据的按日期排序
- string - 如何在 MARIE 中修剪字符串?
- c - 基于优先级的多线程?
- r - 如何从 r 中带有空格的文本制作数据框?