Update: Due to some strange Django error, Django will refuse to run your app’s tests if your application doesn’t have a models.py file. You’ll need to create an empty models.pyin your app’s folder if you don’t have one
Django comes with a nice testing rig that lets you individually test each app. By using a combination of pyunit & Django’s testing tools, you’ll be able to whip up a testing suite for each of your site’s apps (more information here: http://docs.djangoproject.com/en/dev/topics/testing/)
However there is some strangeness as to how Django expects the tests to be organized. From the Django documentation:
For a given Django application, the test runner looks
for doctests in two places:
* The models.py file. You can define module-level doctests and/or
a doctest for individual models. It's common practice to put
application-level doctests in the module docstring and model-level
doctests in the model docstrings.
* A file called tests.py in the application directory
-- i.e., the directory that holds models.py. This file is a
hook for any and all doctests you want to write that aren't
necessarily related to models.
Which sounds simple enough, until you end up with a bloated tests.py file that covers 5 different aspects of your app.
Now wouldn’t it be great if you could split them into different files and group them into a folder?
Putting your Tests into a Folder
- In your app’s folder, create a new folder called
tests - Break up your
tests.pyfile into “logical” (what that exactly means is up to you
) python files. Remember to add in the importstatements for each file - Move your new files into the
testsfolder - In
tests, create a new file__init__.py - You want to modify your
__init__.pyas such:from [Project Name].[App Name].tests.[filename] import * #starts the test suite __test__= { 'mytest': [filename] }Note that the filename’s
.pyextension should be excluded from[filename]! - And that’s it! Just follow those basic rules to add all your new test files to
__init__.py.You can go ahead and delete the original
tests.pyfile now as well. Happy testing!
2 Comments
I am trying to implement this b/c it is exactly what I have been looking. Unfortunately, I get a NameError: name ‘GeneralTests’ is not defined.
My code for __init__.py :
from pythonproject.testproj.tests.GeneralTests import *
__test__= {
‘mytest’: GeneralTests
}
Python 2.6
Django 1.2.1
Could you offer any help please?
Hrm, make sure GeneralTests.py is in the same folder as __init__.py, and try using
from GeneralTests import *instead2 Trackbacks
[...] Pi/Pi …but that's just one! Skip to content ProjectsCSC309 A1: kääntää TranslationsJump StacksGrksm To UnicodePhotosynth of BahenCSC302 Winter ‘09CSC301 Fall ‘08Project ArgoboxAbout MeContact Me « Organizing Django Tests into Folders [...]
[...] general, I organize my unit tests into folders (ref. Organizing Django Tests into Folders) so I can break them down into manageable [...]