Jack Ha
Jack Ha

Reputation: 20991

How to automatically create postgis database for Django testing?

I'm trying to test my Django apps which run on a PostGIS database, by following the info in the Django testing docs.

Normally I create a new database by copying a template:

(as user postgres)

createdb -T template_postgis -O lizard test_geodjango2

When I run ./manage.py test, I get the following message:

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

Type 'yes' if you would like to try deleting the test database 'test_geodjango2', or 'no' to > cancel:

What's the best way to let the system create the database?

Upvotes: 5

Views: 2811

Answers (3)

Scott Stafford
Scott Stafford

Reputation: 44818

As of Django 1.11, Django supports the Postgres-only setting settings.DATABASE[whatever]['TEST']['TEMPLATE'] that dictates what template the test database is created from:

https://docs.djangoproject.com/en/dev/ref/settings/#template

Upvotes: 0

monkut
monkut

Reputation: 43870

As S.Lott mentioned, use the standard test command.

Using geodjango with postgis you'll need to add the following to your settings for the spatial templates to be created properly.

settings.py

POSTGIS_SQL_PATH = 'C:\\Program Files\\PostgreSQL\\8.3\\share\\contrib'
TEST_RUNNER='django.contrib.gis.tests.run_tests'

console

manage.py test

Described here: http://geodjango.org/docs/testing.html?highlight=testing#testing-geodjango-apps

I haven't looked into it yet, but when I do this I get prompted for the database password when it attempts to install the necessary sql.

Upvotes: 2

S.Lott
S.Lott

Reputation: 392010

It may be that your DATABASE_USER doesn't have permissions to create a new database/schema.


Edit

If you read the source for the Django test command, you'll see that it always creates a test database. Further, it modifies your settings to reference this test database.

See this: http://docs.djangoproject.com/en/dev/topics/testing/#id1

What you should do is use fixtures. Here's how we do it.

  1. From your template database, create a "fixture". Use the manage.py dumpdata command to create a JSON file with all of your template data. [Hint, the --indent=2 option gives you readable JSON that you can edit and modify.]

  2. Put this in a fixtures directory under your application.

  3. Reference the fixtures file in your TestCase class definition. This will load the fixture prior to running the test.

    class AnimalTestCase(TestCase):
        fixtures = ['mammals.json', 'birds']
        def testFluffyAnimals(self):
             etc.
    

The fixtures replace your template database. You don't need the template anymore once you have the fixtures.

Upvotes: 4

Related Questions