目前我正在做一个 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 状态代码。
所以我的问题是如何正确传递 session 值?
OBS:应用程序正常运行, session 的 if 语句工作正常。
请您参考如下方法:
我找到了解决方案,我想与您分享答案。
在 API 文档中 Test Client说:
When used in combination with a with statement this opens a session transaction. This can be used to modify the session that the test client uses. Once the with block is left the session is stored back.
对于这项工作,我们应该将 assert 放在 with 语句之后,而不是 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
这个简单的缩进解决了我的问题。
