muhuk's blog

Nature, to Be Commanded, Must Be Obeyed

July 30, 2009

Django: Testing With File System Side Effects

Django uses unittest for testing. django.test.TestCase is a special base class for tests that adds various features[1]. Django testing framework takes care of creating a test database, resetting it to its initial state after each test and finally destroying it. So you don’t have to worry tests overwriting anything in your main database.

But if your tests need to create, modify or delete files you need to make sure these side effects are contained. For instance if one of your applications is generating or uploading files within your MEDIA_PATH you would rather not let it mess with files already there.

Here is a little example of using a temporary folder for such operations:

import shutil
import tempfile
from django.test import TestCase


class FooTestCase(TestCase):
    def setUp(self):
        self.__old_foo_dir = settings.FOO_DIR
        settings.FOO_DIR = tempfile.mkdtemp(suffix='foo')

    def test_foo(self):
        # some tests with filesystem side effects
        pass

    def tearDown(self):
        shutil.rmtree(settings.FOO_DIR)
        settings.FOO_DIR = self.__old_foo_dir

Here tempfile.mkdtemp() creates a temporary directory for us and returns its path. When we are finished we remove this temporary directory with shutil.rmtree() and restore our setting FOO_DIR back to its original value. It is always best to clean up thoroughly. We don’t want our tests to fail because of themselves.

Assume settings.FOO_DIR was a directory under MEDIA_PATH. So when you diverted FOO_DIR to the temporary directory, files within couldn’t be served with media server or your development server (if you have configured it to serve static files). If for some reason you need these files accessible over HTTP you need to re-configure your media server. In case of development server it is relatively easy; just divert whole MEDIA_PATH and copy needed files to temporary directory. I suppose you can get away without copying static files to the new location in case of a real media server, nevertheless configuration will be somewhat difficult and a restart might be necessary.


[1]For more information you can refer to official documentation.

If you have any questions, suggestions or corrections feel free to drop me a line.