librelist archives

« back to archive

How to test a Flask app that uses WTForms FormFields

How to test a Flask app that uses WTForms FormFields

From:
Scott Sturdivant
Date:
2012-08-08 @ 21:26
Hi,

Given a form that uses a WTForms FormField, how can I test the
submittal?  When executing the test_client's post() method, the data
keyword arg seems to expect a flat dict, not a dict of dicts as a Form
using FormFields provides.  For what it's worth, the app itself does
work properly, but I would like to have unit tests also working.  An
example below:

# http://wtforms.simplecodes.com/docs/1.0.1/fields.html#field-enclosures
>>> from wtforms import Form, FormField, IntegerField, TextField, validators
>>> class TelephoneForm(Form):
...    country_code = IntegerField('Country Code', [validators.required()])
...    area_code    = IntegerField('Area Code/Exchange',
[validators.required()])
...    number       = TextField('Number')

>>> class ContactForm(Form):
...    first_name   = TextField()
...    last_name    = TextField()
...    mobile_phone = FormField(TelephoneForm)
...    office_phone = FormField(TelephoneForm)

>>> # Create the form
>>> form = ContactForm()
>>> form.data
{'office_phone': {'area_code': None, 'number': None, 'country_code':
None}, 'first_name': None, 'last_name': None, 'mobile_phone':
{'area_code': None, 'number': None, 'country_code': None}}


>>> # Try to post against a test client with this form
>>> import app
>>> tc = app.test_client()
>>> tc.post('volunteer', data=form.data)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File 
"/home/scott/CRRR/venv/local/lib/python2.7/site-packages/Werkzeug-0.8.3-py2.7.egg/werkzeug/test.py",
line 755, in put
    return self.open(*args, **kw)
  File 
"/home/scott/CRRR/venv/local/lib/python2.7/site-packages/Flask-0.9-py2.7.egg/flask/testing.py",
line 97, in open
    builder = make_test_environ_builder(self.application, *args, **kwargs)
  File 
"/home/scott/CRRR/venv/local/lib/python2.7/site-packages/Flask-0.9-py2.7.egg/flask/testing.py",
line 28, in make_test_environ_builder
    return EnvironBuilder(path, base_url, *args, **kwargs)
  File 
"/home/scott/CRRR/venv/local/lib/python2.7/site-packages/Werkzeug-0.8.3-py2.7.egg/werkzeug/test.py",
line 312, in __init__
    self._add_file_from_data(key, value)
  File 
"/home/scott/CRRR/venv/local/lib/python2.7/site-packages/Werkzeug-0.8.3-py2.7.egg/werkzeug/test.py",
line 329, in _add_file_from_data
    self.files.add_file(key, **value)
TypeError: add_file() got an unexpected keyword argument 'area_code'

Thank you,

Scott