在成功发布到表单端点后,我使用我的客户端代码可以与之交互的一些 URL 参数重定向回相同的端点。
@bp.route('/submit', methods=['GET', 'POST'])
def submit():
form = SubmissionForm()
labels = current_app.config['TRELLO_LABELS']
if form.validate_on_submit():
submission = Submission().create(
title=form.data['title'], email=form.data['email'], card_id=card.id, card_url=card.url)
# reset form by redirecting back and setting the URL params
return redirect(url_for('bp.submit', success=1, id=card.id))
return render_template('submit.html', form=form)
但是我在尝试为此代码编写测试时遇到了一些问题,因为我不知道如何测试这些 URL 参数是否在我的重定向 URL 上。我不完整的测试代码是:
import pytest
@pytest.mark.usefixtures('session')
class TestRoutes:
def test_submit_post(self, app, mocker):
with app.test_request_context('/submit',
method='post',
query_string=dict(
email='email@example.com',
title='foo',
pitch='foo',
format='IN-DEPTH',
audience='INTERMEDIATE',
description='foo',
notes='foo')):
assert resp.status_code == 200
我尝试了几种不同的方法来对此进行测试。使用和不使用上下文管理器,我深入研究了 test_client
和 test_request_context
上的 Flask 和 Werkzeug 源代码。
我只想测试 success
和 id
的 URL 参数是否存在于有效 POST 后的重定向中。
最佳答案
这是一个 super 简单但包含所有内容的示例,它修补了 Flask 的 url_for
方法(可以在 Python 解释器中按原样运行):
import flask
from unittest.mock import patch
@patch('flask.url_for')
def test(self):
resp = flask.url_for('spam')
self.assert_called_with('spam')
但是,上面的示例仅在您直接导入 Flask 并且不在路由代码中使用 from flask import url_for
时才有效。您必须修补确切的 namespace ,它看起来像这样:
@patch('application.routes.url_for')
def another_test(self, client):
# Some code that envokes Flask's url_for, such as:
client.post('/submit', data={}, follow_redirects=True)
self.assert_called_once_with('bp.submit', success=1, id=1)
有关更多信息,请查看 Where to Patch在模拟文档中。
关于python - 在 Flask 重定向中测试 URL 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48333196/