2016-09-27 104 views
0

POST請求的flask_wtf形式的數據我有一個表格如下:如何生成測試

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') 

我嘗試使用單元測試來測試它:

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()永遠不會通過。有沒有人在這裏知道寫入方式來提交表單數據以便發佈請求?

謝謝,

回答

0

我發現的根源戳進flask_wtf源代碼之後。驗證失敗來自隱藏元素「csrf_token」。我認爲有很多方法來解決它,但我通過在視圖函數中創建MyForm對象時通過參數來實現:

form = MyForm(csrf_enabled=False)