[英]Accessing Flask test client session in pytest test when using an app factory
我正在嘗試使用pytest和app工廠對應用程序進行單元測試,但我似乎無法在我的測試中訪問客戶端會話對象。 我確定有一些背景我不是在推動某個地方。 我在我的'app'夾具中推送應用程序上下文。 我應該在某處推送請求上下文嗎?
以下是MWE。
mwe.py:
from flask import Flask, session
def create_app():
app = Flask(__name__)
app.secret_key = 'top secret'
@app.route('/set')
def session_set():
session['key'] = 'value'
return 'Set'
@app.route('/check')
def session_check():
return str('key' in session)
@app.route('/clear')
def session_clear():
session.pop('key', None)
return 'Cleared'
return app
if __name__ == "__main__":
mwe = create_app()
mwe.run()
conftest.py:
import pytest
from mwe import create_app
@pytest.fixture(scope='session')
def app(request):
app = create_app()
ctx = app.app_context()
ctx.push()
def teardown():
ctx.pop()
request.addfinalizer(teardown)
return app
@pytest.fixture(scope='function')
def client(app):
return app.test_client()
test_session.py:
import pytest
from flask import session
def test_value_set_for_client_request(client): # PASS
client.get('/set')
r = client.get('/check')
assert 'True' in r.data
def test_value_set_in_session(client): # FAIL
client.get('/set')
assert 'key' in session
def test_value_set_in_session_transaction(client): # FAIL
with client.session_transaction() as sess:
client.get('/set')
assert 'key' in sess
請注意,直接運行它可以正常工作,我可以跳轉/設置,/檢查,/清除它,它的行為符合預期。 類似地,僅使用測試客戶端來獲取頁面的測試按預期工作。 但是,似乎沒有直接訪問會話。
從cookiecutter -flask中的conftest.py查看以下內容。 它可能會給你一些想法。
@pytest.yield_fixture(scope='function')
def app():
"""An application for the tests."""
_app = create_app(TestConfig)
ctx = _app.test_request_context()
ctx.push()
yield _app
ctx.pop()
@pytest.fixture(scope='function')
def testapp(app):
"""A Webtest app."""
return TestApp(app)
問題在於您使用測試客戶端的方式。
首先,您不必創建客戶端夾具。 如果你使用pytest-flask
,它提供了一個client
裝置來使用。 如果您仍想使用自己的客戶端(可能因為您不想使用pytest-flask
),您的客戶端夾具應該充當上下文處理器來包裝您的請求。
所以你需要以下內容:
def test_value_set_in_session(client):
with client:
client.get('/set')
assert 'key' in session
當天的信息:pytest-flask有一個類似的客戶夾具。 區別在於pytest-flask使用上下文管理器為您提供客戶端,每次測試可節省1行
@pytest.yield_fixture
def client(app):
"""A Flask test client. An instance of :class:`flask.testing.TestClient`
by default.
"""
with app.test_client() as client:
yield client
你用pytest-flask
client
測試
def test_value_set_in_session(client):
client.get('/set')
assert 'key' in session
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.