views:

330

answers:

3

I've been using django for a couple months now and I'm starting to get comfortable with it. At this point in my development I want to begin integrating unit testing and I've discovered unit testing a view to be tricky because of the way that django implements views with functions. For example, each function is a view/page in django if the function is assigned a url.

I could also be confused on how MVT is supposed to be working. I think in MVT the V is similar to the C in MVC but if that's not the case then I could see how I may not need to unit test the views. I understand how to unit test the models but I guess I need to figure out how to test the controlling code while still maintaining proper use of the django framework.

Basically I just want to have as near to 100% code coverage as possible in django.

Thanks guys!

+4  A: 

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-soecific-package
|   |   |-- __init__.py
|   |-- test_app_specific_module.py <-- unittest 
|   |-- test_app_specific_package.py
|-- generic-module.py
|-- generic-package.py
|   |-- __init__.py
|-- tests
|   |-- test_this.py
|   |-- test_that.py
|   |-- test_all.py <-- not always practical
|-- scripts
|   |-- run_tests.sh
S.Lott
Hmm this could answer another question I have. How do you manage the directory structure when adding other modules in the django project/app hierarchy?
Thomas Schultz
Thanks! That helps out a lot.
Thomas Schultz
+1  A: 

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.

thraxil
A: 

You could try tddspry - collection of helpers to test Django with nosetests and twill. Nose also have coverage plugin which generate pretty reports of the coverage.

Hotsyk