Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test (using unittest) the HTML output of a Django view?

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.

like image 437
Denilson Sá Maia Avatar asked Jan 28 '11 16:01

Denilson Sá Maia


People also ask

How do I test a Django project?

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.

How do I write unit tests in Django?

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.

How do I test my Django site?

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.


1 Answers

I've always found a combination of BeautifulSoup, and assertContains and assertFormError from TestCase's available assertions to do the trick.

like image 131
Steve Jalim Avatar answered Sep 30 '22 18:09

Steve Jalim