Trewq
Trewq

Reputation: 3237

Running tests with unmanaged tables in django

My django app works with tables that are not managed and have the following defined in my model like so:

class Meta:
    managed  = False
    db_table = 'mytable'

When I run a simple test that imports the person, I get the following:

(person)bob@sh ~/person/dapi $  > python manage.py test
Creating test database for alias 'default'...
DatabaseError: (1060, "Duplicate column name 'db_Om_no'")

The tests.py is pretty simple like so:

import person.management.commands.dorecall
from person.models import Person
from django.test import TestCase
import pdb

class EmailSendTests(TestCase):
    def test_send_email(self):
        person = Person.objects.all()[0]
        Command.send_email()

I did read in django docs where it says "For tests involving models with managed=False, it’s up to you to ensure the correct tables are created as part of the test setup.". So I understand that my problem is that I did not create the appropriate tables. So am I supposed to create a copy of the tables in the test_person db that the test framework created?

Everytime I run the tests, the test_person db gets destroyed (I think) and re-setup, so how am I supposed to create a copy of the tables in test_person. Am I thinking about this right?

Update:

I saw this question on SO and added the ManagedModelTestRunner() in utils.py. Though ManagedModelTestRunner() does get run (confirmed through inserting pbd.set_trace()), I still get the Duplicate column name error. I do not get errors when I do python manage.py syncdb (though this may not mean much since the tables are already created - will try removing the table and rerunning syncdb to see if I can get any clues).

Upvotes: 8

Views: 2443

Answers (1)

rgilligan
rgilligan

Reputation: 804

I had the same issue, where I had an unmanaged legacy database that also had a custom database name set in the models meta property.

Running tests with a managed model test runner, as you linked to, solved half my problem, but I still had the problem of Django not knowing about the custom_db name:

django.db.utils.ProgrammingError: relation "custom_db" does not exist

The issue was that ./manage.py makemigrations still creates definitions of all models, managed or not, and includes your custom db names in the definition, which seems to blow up tests. By installing:

pip install django-test-without-migrations==0.2

and running tests like this:

./manage.py test --nomigrations

I was able to write tests against my unmanaged model without getting any errors.

Upvotes: 2

Related Questions