Monthly Archives: September 2014

Concurrent Jenkins builds of a Django application

If you try to run multiple Jenkins builds of a single Django project on Jenkins out of the box you might be met with a message similar to:

Got an error creating the test database: database "test_projectdb" already exists

Got an error recreating the test database: database "test_projectdb" is being accessed by other users
DETAIL:  There is 1 other session using the database.

To fix this you need to edit the ‘DATABASES’ Dictionary within your Django project settings module, adding another key ‘TEST_NAME’.

TEST_NAME is the name of the test database Django will create when running your tests with manage.py.

We can make this name unique by adding the following function to our Django setting module:

def get_test_db_name():
    md5 = hashlib.md5()
    md5.update(os.environ.get('BUILD_TAG', b'no-tag'))
    return md5.hexdigest()

(This will take the unique BUILD_TAG environment variable set by Jenkins and md5 it)

And then calling it within the DATABASES Dictionary:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'projectdb',
        'USER': 'django',
        'PASSWORD': 'django',
        'HOST': '127.0.0.1',
        'PORT': '',
        'TEST_NAME': get_test_db_name(),
    }
}

That’s it, Jenkins should now work fine with concurrent builds of your application.