How to setup and teardown temporary django db for unit testing?

Posted by blokeley on Stack Overflow See other posts from Stack Overflow or by blokeley
Published on 2010-03-28T15:41:27Z Indexed on 2010/03/28 15:43 UTC
Read the original article Hit count: 174

Filed under:
|
|
|

I would like to have a python module containing some unit tests that I can pass to hg bisect --command.

The unit tests are testing some functionality of a django app, but I don't think I can use hg bisect --command manage.py test mytestapp because mytestapp would have to be enabled in settings.py, and the edits to settings.py would be clobbered when hg bisect updates the working directory.

Therefore, I would like to know if something like the following is the best way to go:

import functools, os, sys, unittest

sys.path.append(path_to_myproject)
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'


def with_test_db(func):
    """Decorator to setup and teardown test db."""
    @functools.wraps
    def wrapper(*args, **kwargs):
        try:
            # Set up temporary django db
            func(*args, **kwargs)
        finally:
            # Tear down temporary django db


class TestCase(unittest.TestCase):

    @with_test_db
    def test(self):
        # Do some tests using the temporary django db
        self.fail('Mark this revision as bad.')


if '__main__' == __name__:
    unittest.main()

I should be most grateful if you could advise either:

  1. If there is a simpler way, perhaps subclassing django.test.TestCase but not editing settings.py or, if not;
  2. What the lines above that say "Set up temporary django db" and "Tear down temporary django db" should be?

© Stack Overflow or respective owner

Related posts about django

Related posts about unit-testing