Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django unit testing for form edit

Someone has probably already developed a technique for relieving the tedium for the following idiomatic unit test:

  1. GET a url with form data already populated
  2. POST a revised form with one or more fields edited
  3. Check response (profit!)

Step 2 is the most tedious, cycling through the form fields. Are there any time-saving hacks for testing Django forms?

[Update: I'm not testing Django forms handling. I'm verifying that my application produces correct responses when a user makes changes to a form. This is an application which processes clinical information, hence a lot of possible responses to test.]

like image 932
Jeff Bauer Avatar asked Feb 13 '10 15:02

Jeff Bauer


1 Answers

It depends what you are trying to test. I would target your tests a bit more finely than it sounds like you are doing.

If the code you need to test is the form validation logic, then I would simply instantiate the form class directly in your tests, pass it various data dictionaries and call .is_valid(), check for the proper errors or lack thereof. No need to involve HTML or HTTP requests.

If it's view logic (which IMO should be minimized) that you are testing, you will probably want to use the test client, but you shouldn't need to do multi-stage tests or very many tests at this level. In testing view logic I wouldn't scrape HTML (that's testing templates), I'd use response.context to pull out the form object from the context.

If what you want to test is that the templates contain the proper HTML to make the form actually work (in order to catch errors like forgetting to include the management form for a formset in the template), I use WebTest and django-webtest, which parse your HTML and make it easy to fill in field values and submit the form like a browser would.

like image 126
Carl Meyer Avatar answered Sep 23 '22 06:09

Carl Meyer