如何在测试中生成flask_wtf表格的发布请求数据

时间:2016-09-27 01:50:19

标签: forms testing flask

我的表格如下:

from flask_wtf import Form

    class MyForm(Form):
        domain = StringField('domain')
        hosts = StringField('hosts')
        startdate = StringField('Start Date', validators=[InputRequired()])
        enddate = StringField('End Date', validators=[InputRequired()] )
        starthour = SelectField('Start Hour',coerce=int, choices=[(i, i) for i in range(0, 24)], default=0)
        endhour = SelectField('End Hour',coerce=int, choices=[(i, i) for i in range(0, 24)], default=23)
        submit1 = SubmitField('Submit1')
        submit2 = SubmitField('Submit2')

我尝试使用unittest测试它:

 def test_form(self):
    form = {
    "domain": "fake",
    "hosts": "fake",
    "startdate": "fake",
    "enddate": "fake",
    "starthour": 1,
    "endhour": 2,
    'submit1': True,
    'submit2': None
    }
    response = self.client.post(url_for('/'), data=form)

但是,虽然打印的接收数据看起来正确,但 form.validate_on_submit()函数永远无法通过。这里有没有人知道为帖子请求提供表单数据的写入方式?

谢谢,

1 个答案:

答案 0 :(得分:0)

在深入研究flask_wtf源代码后,我找到了根本原因。验证失败来自隐藏元素“csrf_token”。我认为有很多方法可以解决它,但我是通过在视图函数中创建MyForm对象时传递参数来实现的:

form = MyForm(csrf_enabled=False)