This method is replacement for django test runner. It uses nose test runner, which will discover all tests in the application (not even in tests module of applications).
For installing put in settings.py:
`TEST_RUNNER = 'nose_runner.run_tests'`
where *nose_runner* is module containing the code
If you have this as your base class for all unit tests you can do the following:
class TestViews(BaseTestCase):
def test_generated_stats(self):
"test that certain stuff in the response"
...create some content for testing or use fixtures...
response = self.client.get('/some/page/')
# At this point response.content is a huge string filled with HTML tags and
# "junk" that you don't need for testing the content thus making it difficult
# to debug the generated HTML because it so huge.
# So we can zoom in on the <div id="stats>...</div> node
html = self._zoom_html(response.content, '#stats')
# the variable 'html' will now be something like this:
"""
<div id="stats">
<p>
<strong>2</strong> students<br/>
<em>1</em> warning.
</p>
</div>
"""
# This makes it easier to debug the response and easier to test
# against but the HTML might still be in the way so this would fail:
self.assertTrue('2 students' in html) # will fail
# To strip away all html use _strip_html()
content = self._strip_html(html)
# Now this will work
self.assertTrue('2 students' in content) # will work
It works for me and I find this very useful so I thought I'd share it.
I wanted to use Nose with Django so I came up with this.
`TEST_RUNNER = 'noserun.run_tests'` in settings.py
It does not do setup/teardown implicitly between test
methods, you need to call *nosetest.test.flush()* and
*nosetest.test.loaddata()* manually if you want that.
Enables the method names *setup* and *teardown*
The environment variable *NOSE_COVER* runs coverage
tests and *NO_DROPDB* preserves the test db.
A management.py loading customized SQL feeding it raw to the database backend.
Just put it as `management.py` in your app and put whatever SQL you want run after syncdb in `app/sql/custom.backend_driver.sql`.
If the `backend_driver` is skipped the SQL will be loaded no matter database backend.
Since it is run after syncdb it will also be run for test.
This is a small addition to the mako template processing plugin for django that allows you to use the unit test framework with mako templates. To install, put the code into a file on your python path, and add the python path to your settings.py file. For example, if you install the code at
/usr/lib/python2.5/site-packages/mako_django/test_integration.py
you would add the following line to settings.py:
TEST_RUNNER="mako_django.test_integration.run_mako_tests"
This code will still call all of the normal test code, it just adds the mako template handler onto the list of things that are monitored.
Sometimes you need to test some model features without a complete django app installation. Just play only with the model object. With these small script you have a complete in memory django installation.
Some Links:
http://www.djangosnippets.org/snippets/1044/ (en)
http://www.jensdiemer.de/permalink/150/mein-blog/99/django-db-model-test/ (de)
http://www.python-forum.de/viewtopic.php?f=3&t=15649 (de)
See also:
https://github.com/readevalprint/mini-django/
This is a simple fixture that is useful for many tests.
It contains the following users:
* admin
* staff
* user0
* user1
* user2
* user3
* inactive0
* inactive1
The password of every user is the same as his username, e.g.: admin/admin
This TestSettingsManager class takes some of the pain out of making temporary changes to settings for the purposes of a unittest or doctest. It will keep track of the original settings and let you easily revert them back when you're done.
It also handles re-syncing the DB if you modify INSTALLED_APPS, which is especially handy if you have some test-only models in tests/models.py. This makes it easy to dynamically get those models synced to the DB before running your tests.
Sample doctest usage, for testing an app called "app_under_test," that has a tests/ sub-module containing a urls.py for testing URLs, a models.py with some testing models, and a templates/ directory with test templates:
>>> from test_utils import TestManager; mgr = TestManager()
>>> import os
>>> mgr.set(INSTALLED_APPS=('django.contrib.contenttypes',
... 'django.contrib.sessions',
... 'django.contrib.auth',
... 'app_under_test',
... 'app_under_test.tests'),
... ROOT_URLCONF='app_under_test.tests.urls',
... TEMPLATE_DIRS=(os.path.join(os.path.dirname(__file__),
... 'templates'),))
...do your doctests...
>>> mgr.revert()
"Make fixture" command. Highly useful for making test fixtures.
Use it to pick only few items from your data to serialize, restricted by primary keys.
By default command also serializes foreign keys and m2m relations.
You can turn off related items serialization with `--skip-related` option.
How to use:
python manage.py makefixture
will display what models are installed
python manage.py makefixture User[:3]
or
python manage.py makefixture auth.User[:3]
or
python manage.py makefixture django.contrib.auth.User[:3]
will serialize users with ids 1 and 2, with assigned groups, permissions and content types.
python manage.py makefixture YourModel[3] YourModel[6:10]
will serialize YourModel with key 3 and keys 6 to 9 inclusively.
Of course, you can serialize whole tables, and also different tables at once, and use options of dumpdata:
python manage.py makefixture --format=xml --indent=4 YourModel[3] AnotherModel auth.User[:5] auth.Group
As Simon Willison mentions in his [Debugging Django](http://simonwillison.net/2008/May/22/debugging/) presentation, using the Test Client in the interpreter can be a great way to take a peek at the raw results from a view. In some cases you may need to add additional headers to the request (for instance a piece of middleware may rely on them).
Though it is not mentioned in the reference documentation, a quick peek at the code confirmed my hopes that it would be possible to add data to the request. The Client *get* and *post* methods both accept an **extra** kwargs parameter that allow you to populate the request with additional data.
A replacement test runner which outputs a coverage report after the tests. Simply change your ``TEST_RUNNER`` setting to point to ``run_tests_with_coverage`` and you're good to go.
Note that 'as-is' this snippet reports the coverage of all modules underneath the app, by walking the directory tree and loading all of the .py modules (this may be a naive approach).
If you change it to use `get_coverage_modules()` instead, it will only display the coverage of modules that have been imported by the test suite, using the Python `inspect` lib, which may be more reliable.
Uses [coverage.py](http://nedbatchelder.com/code/modules/coverage.html). Based on ideas from: [1](http://www.thoughtspark.org/node/6), [2](http://blogs.23.nu/c0re/stories/15428/) and [3](http://siddhi.blogspot.com/2007/04/code-coverage-for-your-django-code.html)
[zope.testing](http://pypi.python.org/pypi/zope.testing/) is a test framework and test runner, similar to the django test runner and nose.
This snippet is a [Layer](http://pypi.python.org/pypi/zope.testing/3.5.1#layers) class which you can assign as a layer attribute of your test suite to initialise and clean up the django test environment appropriately and to reset the test database between tests.
for example:
tests/suite.py
import unittest
from zope.testing import doctest
def test_suite():
suite = doctest.DocFileSuite("models.txt")
suite.layer = DjangoLayer
return suite
runtests.py
import os
from zope.testing import testrunner
os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'
defaults = [
'--path', 'tests',
'--tests-pattern', '^suite$',
'-c'
]
testrunner.run(defaults)
I hate when my unittest hits database. Especially when each test case needs different dataset.
So I wrote this db mock, that's local to specific test and uses sqlite3 in-memory db.
Usage (nosetests):
class TestMainNoData(DbMock):
'testing main function with no meaningful data'
def test_no_posts(self):
'there are no posts'
assert models.Post.objects.count() == 0, 'should be no feeds'