matt snider
matt snider

Reputation: 4113

django - specify database for TestCase fixtures

I have two databases that my site uses and I have an app that uses both of them. I need to write a TestCase that loads fixtures for both databases. I use a DB router, which works fine in production, but in the testing framework, Django insists on using the 'default' database for all fixtures, even for models that specify the other database. How do I tell Django to run a fixture against another database?

My TestCase is defined list:

class VerifierTestCase(TestCase):
    fixtures = ['zipcodes_test.json', 'all_states.json', 'wtf.json']
    multi_db = True

Upvotes: 16

Views: 2936

Answers (3)

Kedar
Kedar

Reputation: 1698

If you have a multi-db setup with models exclusive to each database. You need to save a fixture file for each database (with the non-applicable database files being empty).

If your code defines fixtures = ["sample"] and you have two databases default and other.

You need two files: sample.default.json and sample.other.json. If sample contains only models from db default, sample.other.json will be an empty file ([]) and vice-versa.

Tried with Django 3.2

Upvotes: 0

zenWeasel
zenWeasel

Reputation: 1889

There is actually a bug in Django that causes it to ignore the name-based db-specific pointers if you specify the entire fixture name.

so if you do fixtures = ["mydata.default.yaml", "mydata.myotherdatabase.yaml"]

It will load both fixtures into the default database.

But if you do fixtures = ['mydata']

It will load correctly. This is also true for dbengine specific filenames (e.g. mydata.default.postgresql.sql) as well.

Upvotes: 5

GDorn
GDorn

Reputation: 8811

Fixtures are targeted at specific databases by filename. This is true in TestCase instances as well, as they just call the loaddata command.

See https://docs.djangoproject.com/en/dev/ref/django-admin/#database-specific-fixtures

Upvotes: 2

Related Questions