Question

Using webapp2 I create unit tests for a form where there are checkboxes for votes so multiple values can be posted for the vote field and they are retrieved via request.POST.getall('vote'):

<input type="checkbox" name="vote" value="Better">
<input type="checkbox" name="vote" value="Faster">
<input type="checkbox" name="vote" value="Stronger">

In the unit test I tried passing a list:

response = app.get_response('/vote',
  POST={'vote': [u'Better', u'Faster', u'Stronger']},
  headers=[('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8')]
)

But looks like it's simply converted to a string:

votes = self.request.POST.getall('vote')
# => [u"[u'Better', u'Faster', u'Stronger']"]

How can I pass multiple values for vote that will be retrieved as a list via request.POST.getall()?

Was it helpful?

Solution

POST data is encoded using query string encoding, and multiple items by the same name are represented by repeating the key with different values. For instance:

vote=Better&vote=Faster&vote=Stronger

Python has library functions to do this for you, though:

urllib.urlencode({
  'vote': ['Better', 'Faster', 'Stronger'],
}, True)

The second argument (True) to urlencode is called 'doseq', and instructs urlencode to encode sequences as lists of separate elements.

OTHER TIPS

The webtest library is helpful for these test cases.

http://webtest.pythonpaste.org/en/latest/index.html#form-submissions

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top