Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I unit test Django Views?

I want to begin integrating unit tests into my Django projects and I've discovered unit testing a view to be tricky because of the way Django implements views with functions.

For example, each function is a view/page in Django if the function has a URL.

How do I unit test Django views?

like image 203
Thomas Schultz Avatar asked Sep 02 '09 15:09

Thomas Schultz


People also ask

How do you write unit test cases 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 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.


2 Answers

I'm not sure how testing a view is tricky.

You just use the test client.

Code coverage is easy. You reason how how a URL request maps to a code path and make the appropriate URL requests.

You can, if you want, call the view functions "manually" by creating a Request object and examining the Response object, but this is too much work.

If you have doubts about your code coverage, that's a good thing. It means you have code you can't easily map to a URL (which is all a user can ever see of a web application.) If you have code that doesn't map to a URL, you should probably either (a) delete the code or (b) refactor it into a separate module.

We have lots of modules outside our view functions. Our view functions import these modules. We test these "outside the view function" modules with ordinary unittest.


Here's a typical structure.

some_big_product/
|-- __init__.py
|-- settings.py
|-- urls.py
|-- logging.ini
|-- other_global_files.py
|-- an_app_1/
|   |-- __init__.py
|   |-- urls.py
|   |-- models.py
|   |-- views.py
|   |-- tests.py <-- the generic Django testing 
|   |-- app_specific_module.py
|   |-- app_specific_package/
|   |   |-- __init__.py
|   |-- test_app_specific_module.py <-- unittest 
|   |-- test_app_specific_package.py
|-- generic_module.py
|-- generic_package/
|   |-- __init__.py
|-- tests/
|   |-- test_this.py
|   |-- test_that.py
|   |-- test_all.py <-- not always practical
|-- scripts/
    |-- run_tests.sh 
like image 188
S.Lott Avatar answered Sep 20 '22 02:09

S.Lott


django.test.client should have everything you need for basic unit testing of the view. I also really like twill and selenium for testing the full stack.

like image 29
thraxil Avatar answered Sep 23 '22 02:09

thraxil