开发者

How to unit-test post request for multiple checkboxes with the same name under webapp2

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()?


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.


The webtest library is helpful for these test cases.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜