繁体   English   中英

使用 Pytest 测试 Flask 会话

[英]Testing Flask Sessions with Pytest

目前我正在做一个 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 语句之后,而不是在里面,所以代码应该是:

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

这个简单的缩进解决了我的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM