我正在使用WebTest测试表单。但是,某些字段是使用JS动态创建的,因此这些字段不在表单中。当我尝试设置其中一个字段时出错:
>>> 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
有没有办法创建一个字段?
答案 0 :(得分:10)
您需要将新字段添加到字段和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')
答案 1 :(得分: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, 999, value)
form.fields[name] = [field]
form.field_order.append((name, field))