This part explains how to use django-sane-testing to create a workable test suite. For test writers, most important part is about creating tests, testers and CI admins may be more interested in executing them.
Various test types were identified when taking look at developer tests. Every test type has it’s corresponding class in djangosanetesting.cases, namely:
However, you are not required to inherit from those (except for twill), althrough it’s much advised to keep test cases intent-revealing. Job of the library is to:
Those are done by plugins, and they dermine their jobs by looking at class attributes, namely:
All of those are booleans. Because class attributes are currently used to determine behaviour, nor doctest nor function tests are supported (they will not break things, but you’ll get no goodies from library).
To support proper test selection and error-handling, tests also has class atribute required_sane_plugins, which specifies list of plugins (from those available) that are required for this type of test; if it’s not, test automatically skip itself.
Proper defaults are selected when using library test cases; however, if you have your own and complicated test inheritance model, you can integrate it on your own.
When writing tests, keep in mind limitations of the individual test cases to prevent interacting tests:
Easiest way to run tests is to put TEST_RUNNER="djangosanetesting.testrunner.DstNoseTestSuiteRunner" into your settings.py. This allows You to use manage.py test command (all plugins are enabled by default).
You can still use standard nosetests command. However, keep in mind:
Most likely, you’ll end up with something like DJANGO_SETTINGS_MODULE="settings" PYTHONPATH=".:.." nosetests --with-django; you can, however, flexibly add another nose modules (like --with-coverage).
Fine-grained test type selection is available via SaneTestSelectionPlugin.
Provided plugins:
DjangoPlugin takes care about basic Django environment setup. It must be loaded in order to use other plugins with Django (obviously). This plugin takes care about DatabaseTestCase and DestructiveDatabaseTestCase:
django.db.transaction is also available under self.transaction. Use at own discretion; you should only access it when using DestructiveDatabaseTestCase (to make data available for server thread), messing with it when using database_single_transaction can cause test interaction.
Since 0.6, You can use --persist-test-database. This is similar to quicktest command from django-test-utils: database is not flushed at the beginning if it exists and is not dropped at the end of the test run. Useful if You are debugging single test in flush-heavy applications.
Warning
By definition, strange things will happen if You’ll change tests You’re executing. Do not overuse this feature.
Warning
Tested by hand, not covered by automatic tests. Please report any bugs/testcases You’ll encounter.
Responsible for starting HTTP server, sort of same as ./manage.py runserver, however testing server is multithreaded (as if with patch from #3357, but always enabled: if you’ll any problems with it, write me).
Server is first started when start_live_server attribute is first encountered, and is stopped after whole testsuite.
Warning
Because application logic is always executed in another thread (even when server would be single-threaded), it’s not possible to use HttpTestCase‘s with in-memory databases (well, theoretically, we could do database setup in each thread and have separate databases, but that will be really nasty).
Thus, if encountered with in-memory database, server is not started and SkipTest is raised instead.
Warning
Because of twill integration, if non-empty _twill attribute is encountered, twill’s reset_browser is called. This might be a problem if You, for whatever reason, set this attribute without interacting with it.
If it annoys You, write me and I might do something better. Until then, it’s at least documented.
Responsible for starting HTTP server, in similar way to DjangoLiveServerPlugin. However, CherryPy WSGI is used instead, as it’s much more mature and considered to be production-ready, unlike Django’s development server.
Use when in need of massive parallel requests, or when encountering a bug (like #10117).
Note
When using ./manage.py test, Django server is used by default. You can use CherryPy‘s by setting CHERRYPY_TEST_SERVER = True in settings.py.
Warning
DjangoLiveServerPlugin (--with-djangoliveserver) and CherryPyLiveServerPlugin (--with-cherrypyliveserver) are mutually exclusive. Using both will cause errors, and You’re responsible for choosing one when running tests with nosetests (see Running tests for details).
Selenium is excellent tool for regression (web application) testing. SeleniumPlugin easily allows you to use xUnit infrastructure together with Selenium RC and enjoy unified, integrated infrastructure.
Selenium proxy server must be set up and running, there is no support for auto-launching (yet).
SeleniumPlugin recognizes following configuration variables in settings.py:
When plugin encounters selenium_start attribute (set to True), it tries to start browser on selenium proxy. If exception occurs (well, I’d catch socket errors, but this seems to be impossible on Windows), it assumes that proxy is not running, thus environment conditions are not met and SkipTest is raised. If FORCE_SELENIUM_TESTS is set to True, then original exceptin is raised instead, causing test to fail (usable on web testing CI server to ensure tests are runnig properly and are not mistakenly skipped).
Test cases varies in their speed, in order:
As your test suite will grow, you’ll probably want to do test pipelining: run your tests in order, from fastest to slowest, and if one of the suites will break, you’ll stop running slower tests to save time and resources.
This can be done with SaneTestSelectionPlugin. When enabled by --with-sanetestselection, you can pass additional parameters to enable respecitve types of tests:
Only selected test types will be run. Test type is determined from class attribute test_type; when not found, test is assumed to be unittest.
Note
You’re still responsible for loading required plugins for respective test cases. Unlike test selection with usual plugins, selection plugin enables you to run slower tests without faster (i.e. HTTP tests without unittests), and also skipping is faster (Selection plugin is run before others, thus skip is done without any unneccessary database handling, which may not be true for usual skips).
Warning
This plugin relies on setUp from SaneTestCase. Thus, it will work only with tests inheriting from it. Also, if You are overwriting setUp, You have to behave nicely and call super(YourTestClass, self).setUp().
If make_translation is True (default for every test), django.utils.translation.activate() is called before every test. If translation_language_code is set, it’s passed to activate(); otherwise settings.LANGUAGE_CODE or ‘en-us’ is used.
This allows you to use translatable string taking usage of ugettest_lazy in tests.
Warning
It looks like Django is not switching back to “null” translations once any translation has been selected. make_translations=False will thus return lastly-activated translation.
syncdb alone is now rarely used, as excellent South entered mainstream. Thus, by default, migrate is called every time database is recreated. This behavior can be adjuted using DST_RUN_SOUTH_MIGRATIONS settings variable
You may be doing something irresponsible like, say, referencing ContentType ID from fixtures, working around their dynamic creation by having own content type fixture. This, however, prevents you from specifying those in fixtures attribute, as flush emits post-sync signal causing ContentTypes to be created.
By specifying TEST_DATABASE_FLUSH_COMMAND, you can reference a function for custom flushing (you can use resetdb instead).
Note
You must specify function object directly (it takes one argument, test_case object). Recognizing objects from string is not yet supported as it’s not needed for me - patches and tests welcomed.
Note
When using TEST_DATABASE_FLUSH_COMMAND, please note that migrate runs before TEST_DATABASE_FLUSH_COMMAND. This behavior will change in future releases.
Also, create_test_db (which is needed to be run at the very beginning) emits post_sync signal. Thus, you also probably want to set FLUSH_TEST_DATABASE_AFTER_INITIAL_SYNCDB to True.
Twill is simple browser-like library for page browsing and tests. For HttpTestCase and all inherited TestCases, self.twill is available with twill’s get_browser(). It’s setted up lazily and is resetted and purged after test case.
Browser has patched go() method: You can pass relative paths to it. Besides, it will throw HTTPError (from urllib2), if server serves page with status 500.
Also, use can use go_xpath() to use lxml-based XPath to specify hyperlink on page to visit.
self.twill also has commands attribute, equal to twill.commands.
self.assert_code is same as twill.commands.code("number"), except it raises usual AssertionError.
Note
Twill is using standard HTTP instead of WSGI intercept. This might be available in the future as an option, if there is a demand or patch written.
Behavior of django-sane-testing can be configured to match your needs.
TODO: List of whatever settings you can play with.