python - 不确定如何在单元测试中发布表单数据
问题描述
我有一个 HTML 模板,它提交一个包含用户选择结果的表单。此表单发布到“routes.py”中的 python 函数,该函数根据此选择的值添加到数据库中。我正在尝试对此功能运行单元测试,但是不知道如何在单元测试文件中发布表单。
这是 HTML 模板中表单的相关部分:
<form method="POST" action="{{ url_for('select') }}">
<div class="info">
<div >
<div >
<span>Select a car</span>
<br/>
<br>
<select name="car_select">
{% for i in cars %}
<option>{{i}}</option>
{% endfor %}
</select>
</div>
<br><br>
<button type="submit" onclick="time()">Vote</button>
</div>
</form>
这是“routes.py”中我的函数的相关部分,我正在运行单元测试:
@app.route("/select" , methods=['GET', 'POST'])
def select():
select = request.form.get('car_select')
这是我在单元测试中用于启动“选择”功能(不正确)的辅助功能:
def select(self, car):
return self.app.post("/select", data=dict(car_select=car), follow_redirects = True)
我期望这个辅助函数做的是模拟 HTML 表单方法执行的 POST,使得“request.form.get('car_select')”等于辅助函数的“car”参数。
解决方案
您可以使用flask
's 内置test_client
:
app.test_client().post("/select", data=dict(car_select=car))
推荐阅读
- r - 使用for循环填充r中预定义的空矩阵?
- excel - 使用 VBA 从多个 Excel 文件中复制相同范围的单元格
- security - 如何安全地将 SPA 客户端日志推送到 AWS Cloudwatch
- python - 列表列表的Python自定义排序
- ruby-on-rails - Rails 服务器问题(春季)
- java - 通过 REST API 发送 3rd 方凭据的最佳方式
- python - 赋值错误之前引用的 Python 局部变量
- python - Python3:将连接的字符串分配给变量
- timer - Timer1中的“OCR1x更新”是什么意思 - Atmega32
- r - 如何选择ID的倒数第二个日期?