Disable database access when writing unit tests in Django

Consider this curio:

import mock
from django.utils.functional import curry

no_database = curry(
    mock.patch, 'django.db.backends.util.CursorWrapper',
    Mock(side_effect=RuntimeError("Using the database is not permitted")))

This snippet creates a decorator that can wrap a test case or method and raises an exception if the database is accessed. This can be useful if you’re a puritan about true unit tests.

Use by wrapping a TestCase subclass:

from django.test import TestCase

class UnitTestCase(TestCase):

or method:

from django.test import TestCase

class UnitTestCase(TestCase):

    def test_something(self):

This snippet is a reformulation of one from Carl Meyer’s excellent ‘Testing and Django’ (about 24 minutes in).

Challenge: create a similar decorator that prevents all file-system access in a test method.


Something wrong? Suggest an improvement or add a comment (see article history)
Tagged with: django, testing, python
Filed in: tips

Previous: How to install PIL on 64-bit Ubuntu 12.04
Next: A useful Git post-checkout hook for Python repos

Copyright © 2005-2023 David Winterbottom
Content licensed under CC BY-NC-SA 4.0.