首页 > 解决方案 > 不确定如何在单元测试中发布表单数据

问题描述

我有一个 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”参数。

标签: pythonhtmlflask

解决方案


您可以使用flask's 内置test_client

app.test_client().post("/select", data=dict(car_select=car))

推荐阅读