簡體   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