Other answers should work to re-define DATABASES
setting in fixture, but this seems like really poor form to me, because that should be defined in a settings file, ideally.
Scenario
You're trying to run tests with a postgres database. This particular database doesn't give your particular user permission to create new databases. This is not uncommon, as an example, using the image quay.io/sclorg/postgresql-15-c9s
the user you get from using the environment variables can not create new databases. Example settings:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "foo",
"USER": "foo",
"PASSWORD": "secret_foo",
"HOST": "localhost",
"PORT": 5444
}
}
Example error:
psycopg.errors.InsufficientPrivilege: permission denied to create database
You have a given database name (you know "foo" database exists), and you expected to use that. But still get this error, what gives?
You're getting that error because it's trying to create a test_foo
database, where "foo" came from the "NAME" entry. It tries to create a new database for tests, to help you. But this is sometimes unhelpful, as in this example.
Solution
You can specify details specific to the test database nested under a "TEST" entry, as follows:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "foo",
"USER": "foo",
"PASSWORD": "secret_foo",
"HOST": "localhost",
"PORT": 5444,
"TEST": {
"NAME": "foo"
}
}
}
This will work so that you can run, for example:
py.test src/app/test/test_alan.py -k test_alan --reuse-db --migrations
The reuse-db versus create-db probably doesn't matter, but --migrations
vs. --no-migrations
will give different behavior only if you have not already migrated your database. The --migrations
option does something equivalent to running python manage.py migrate
, which is a no-op if migrations have already ran, but no-migrations will do a one-step shot to get current model state, which may still be a no-op if already migrated. But this is a warning, you might mess up your existing database with your tests if you do stuff wrong, like using --no-migrations
before manually running migrations. This is why they do not make this default behavior.
This also will not work with
py.test src/app/test/test_alan.py -k test_alan -n4
Because with multiprocessing, each process needs to have its own database, which, yep, you guessed it, means it will try to create those databases. And you don't have permission to do this.