Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choose test database?

I'm trying to run

./manage.py test

But it tells me

Got an error creating the test database: permission denied to create database

Obviously it doesn't have permission to create the database, but I'm on a shared server, so there's not much I can do about that. I can create a new database through the control panel but I don't think there's any way I can let Django do it automatically.

So, can't I create the test database manually and instead tell Django to flush it every time, rather than recreating the whole thing?

like image 716
mpen Avatar asked Jul 23 '10 17:07

mpen


2 Answers

I had a similar issue. But I wanted Django to just bypass the creation of a test database for one of my instances (it is not a mirror tough). Following Mark's suggestion, I created a custom test runner, as follows

from django.test.simple import DjangoTestSuiteRunner


class ByPassableDBDjangoTestSuiteRunner(DjangoTestSuiteRunner):

    def setup_databases(self, **kwargs):
        from django.db import connections
        old_names = []
        mirrors = []

        for alias in connections:
            connection = connections[alias]
            # If the database is a test mirror, redirect its connection
            # instead of creating a test database.
            if connection.settings_dict['TEST_MIRROR']:
                mirrors.append((alias, connection))
                mirror_alias = connection.settings_dict['TEST_MIRROR']
                connections._connections[alias] = connections[mirror_alias]
            elif connection.settings_dict.get('BYPASS_CREATION','no') == 'no':
                old_names.append((connection, connection.settings_dict['NAME']))
                connection.creation.create_test_db(self.verbosity, autoclobber=not self.interactive)
        return old_names, mirrors

Then I created an extra dict entry in one of my databases entries inside settings.py, 'BYPASS_CREATION':'yes',

Finally, I configured a new TestRunner with

TEST_RUNNER = 'auth.data.runner.ByPassableDBDjangoTestSuiteRunner'
like image 107
Thiago Ganzarolli Avatar answered Sep 26 '22 06:09

Thiago Ganzarolli


I would suggest using sqlite3 for testing purposes while keeping on using mysql/postgres/etc for production.

This can be achieved by placing this in your settings file:

if 'test' in sys.argv:
    DATABASES['default'] = {'ENGINE': 'django.db.backends.sqlite3'}

see Running django tests with sqlite

a temporary sqlite database file will be created in your django project home which you will have write access to. The other advantage is that sqlite3 is much faster for testing. You may however run in to problems if you are using any mysql/postgres specific raw sql (which you should try to avoid anyway).

like image 44
Michael Bylstra Avatar answered Sep 26 '22 06:09

Michael Bylstra