If you want to test a post request to a form, you need to give all input fields, even if you just want to test if one value gets changed.
This snippets parses the HTML of a view and gives you a dictionary that you can give to django.test.Client.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | import cStringIO
import ClientForm
def html_form_to_post_dict(content, base_uri):
'''
content: HTML string.
Return a dictionary mapping form names to a dictionary
with input values.
{'form_name': {'input1: 'default text', ...} }
Example usage in a django unittest.
url=reverse('myapp.views.foo.edit', kwargs={'foo_id': foo_id})
response=self.client.get(url) # client: django.test.Client
post=html_form_to_post_dict(response.content, url)['foo']
post['text']='my input'
response=self.client.post(url, post)
assert response.status_code==302, 'No redirect after POST. Form might contain errors?'
foo=Foo.objects.get(id=foo.id)
assert foo.text=='my input', u'Foo not updated: text: %s' % foo.text
Needs ClientForm from: http://wwwsearch.sourceforge.net/ClientForm/
'''
fd=cStringIO.StringIO(content)
forms={}
for form in ClientForm.ParseFile(fd, base_uri, backwards_compat=False):
old=forms.get(form.name)
assert not old, 'Broken HTML: two forms with the same name %s %s' % (
old.name, form.name)
values={}
for control in form.controls:
if isinstance(control, (ClientForm.IgnoreControl, ClientForm.SubmitControl)):
continue
old=values.get(control.name)
assert not old, 'Broken HTML: form %s contains the input name %s twice.' % (
form.name, control)
values[control.name]=control.value
forms[form.name]=values
return forms
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.