2014-03-28 72 views
3

我正在使用WebTest測試表單。但是,有些字段是使用JS動態創建的,因此這些字段不在Form中。當我嘗試設置其中一個字段時,出現錯誤:我可以使用WebTest添加非現有字段嗎?

 
>>> resp.form['new_field'] = 'value' 
or 
>>> resp.form.set('new_field', 'value') 
or 
>>> resp.form.set('new_field', 'value', index=0) 
or 
>>> resp.form['new_field'].force_value('value') 

*** AssertionError: No field by the name 'new_field' found 

有沒有辦法創建字段?

回答

8

您需要將新字段添加到兩個字段和field_order:

from webtest.forms import Text 
def add_dynamic_field(form, name, value): 
    """Add an extra text field to a form. More work required to support files""" 
    field = Text(form, 'input', None, None, value) 
    form.fields[name] = [field] 
    form.field_order.append((name, field)) 

add_dynamic_field(resp.form, 'newfield', 'some value') 
+0

'form.fields'現在將值存儲爲'list'。 –

0

更新@lambacck代碼來處理文件中的字段爲好。

from webtest.forms import Text, File 
from webtest import Upload 


def add_dynamic_field(form, name, value): 
    field_cls = File if isinstance(value, Upload) else Text 
    field = field_cls(form, 'input', None, None, value) 
    form.fields[name] = field 
    form.field_order.append((name, field)) 
相關問題