I'm writing unit tests for my Django application. However, I don't know how to test the HTML output of a view.
Sometimes I might want to check if a specific element contains certain value, or how many of those elements are displayed, or things like that. How can I do such tests?
I would like a solution that uses unittest
and django's own django.test
.
I know I can use Selenium or Pyccuracy (which uses Selenium), but Selenium tests are quite slow because of the huge overhead of launching a browser. Also, unit tests work out-of-the-box with django-coverage package.
The preferred way to write tests in Django is using the unittest module built-in to the Python standard library. This is covered in detail in the Writing and running tests document. You can also use any other Python test framework; Django provides an API and tools for that kind of integration.
Writing tests Django's unit tests use a Python standard library module: unittest . This module defines tests using a class-based approach. When you run your tests, the default behavior of the test utility is to find all the test cases (that is, subclasses of unittest.
Django comes with a small set of its own tools for writing tests, notably a test client and four provided test case classes. These classes rely on Python's unittest module and TestCase base class. The Django test client can be used to act like a dummy web browser and check views.
I've always found a combination of BeautifulSoup, and assertContains and assertFormError from TestCase's available assertions to do the trick.
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