It's easy to test form cleaning by instantiating a form object against a known-good or known-bad dictionary. The associated view logic can be tested by taking these same dicts and using the test client.
However, we're still left with the basic problem of the actual HTML form element. What if I used the wrong method? Or I have a typo in the action? Or I forgot the CSRF_Token? How can I write unit tests that actually test the behavior that the user is likely to experience?
Do I really need to use mechanize?
Or are people parsing the form element by using .get(url) and looking at the html content of the response? Is there a cleaner way to do this?
This does not only relate to Django HTML testing but to any other application where you need to test HTML behavior.
You can use libraries such as requests to test the forms from the browser perspective using different method (GET/POST/etc).
For more user interaction test, you can use Selenium however I personally like Splinter better. In splinter you instantiate this thing called a browser which you can use as a real browser. Then within the browser you can fill text-boxes, hit buttons, etc. and then test the behavior.
Here is a code snippet from splinter web site:
from splinter.browser import Browser
browser = Browser()
# Visit URL
url = "http://www.google.com"
browser.visit(url)
browser.fill('q', "#cobrateam")
# Find and click the 'search' button
button = browser.find_by_css(".lsb")
# Interact with elements
button.click()
if browser.is_text_present("did not match any documents"):
print "nobody likes us =("
else:
print "we're popular =)"
In there the browser will open, will navigate to google, fill in the q field, click the search button, and then test search results. As you can see the library is very simple to use and you can do quite sophisticated testing with it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With