背景關系:我有兩個處理相同請求資料的 Flask 路由(一個互動,一個作為 API)。為了讓我的代碼干的,我想撰寫一個函式process_post_request()是
- 接受來自每個路由的輸入引數中的請求,
- 決議請求,
- 回傳路由可以使用的結果。
例如,在 views.py 中:
@app.route('/interactive', methods=['GET', 'POST'])
def interactive():
if request.method == 'POST':
sum, product = process_post_request(request)
# present the results on a web page
@app.route('/api', methods=['GET', 'POST'])
def api():
if request.method == 'POST':
sum, product = process_post_request(request)
# return the results so that JavaScript can parse them
def process_post_request(request):
param1 = request.form.get('param1')
param2 = request.form.get('param2')
sum = param1 param2
product = param1 * param2
return sum, product
問題:如何為 撰寫 pytest process_post_request()?問題是,如果我創建一個“請求”并嘗試將其傳遞給process_post_request(),則請求會轉到路由,因此該路由會回傳結果。例如,在 views_test.py 中:
import pytest
@pytest.fixture
def client():
"""Create a client to make requests from"""
with app.test_client() as client:
with app.app_context():
pass
yield client
def test_process_post_request():
request = client.post('/interactive', data={'param1': 5, 'param2': 7})
sum, product = process_post_request(request)
assert sum == 12
因為request回傳一個回應,pytest 拋出這個錯誤:
> request = client.post('/interactive', data={'param1': 5, 'param2': 7})
E AttributeError: 'function' object has no attribute 'post'
uj5u.com熱心網友回復:
我創建了一個應用程式路由來回傳逗號分隔的引數:
@app.route('/pass-through', methods = ['GET', 'POST'])
def pass_through():
if request.method == 'POST':
params = process_post_request(request)
return ','.join(params)
然后測驗該應用程式路由:
def test_process_post_request():
with app.test_client() as client:
response = client.post('/pass-through', data={'param1': 5, 'param2': 7})
sum, product = response.data.decode().split(',')
assert sum == 12
其中decode()從位元組轉換為字串。
這不是最令人滿意的解決方案,因為它確實測驗了應用程式路由,因此它依賴于pass_through()使用與process_post_request().
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/358509.html
