I am trying to run unit tests that I've written for my Django project, but testing fails at the database creation stage. I have a single database "test", one of which as a foreign key relationship with another. I run the following:
python3 manage.py test --settings myapp.settings_test
And see the following output:
Creating test database for alias 'test'...
Got an error creating the test database: (1007, "Can't create database 'test_test'; database exists")
Type 'yes' if you would like to try deleting the test database 'test_test', or 'no' to cancel: yes
Destroying old test database for alias 'test'...
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.5/dist-packages/django/db/backends/mysql/base.py", line 71, in execute
return self.cursor.execute(query, args)
File "/usr/local/lib/python3.5/dist-packages/MySQLdb/cursors.py", line 250, in execute
self.errorhandler(self, exc, value)
File "/usr/local/lib/python3.5/dist-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler
raise errorvalue
File "/usr/local/lib/python3.5/dist-packages/MySQLdb/cursors.py", line 247, in execute
res = self._query(query)
File "/usr/local/lib/python3.5/dist-packages/MySQLdb/cursors.py", line 411, in _query
rowcount = self._do_query(q)
File "/usr/local/lib/python3.5/dist-packages/MySQLdb/cursors.py", line 374, in _do_query
db.query(q)
File "/usr/local/lib/python3.5/dist-packages/MySQLdb/connections.py", line 277, in query
_mysql.connection.query(self, query)
_mysql_exceptions.IntegrityError: (1215, 'Cannot add foreign key constraint')
I've seen many answers such as this: Django MySQL error when creating tables.
Such answers show that, in general, this error is caused by adding a table that has a foreign key field before adding the table that the foreign key referencing. However, I have not found many helpful answers on how to address this in a testing scenario.
Other things I have tried:
I've tried to run tests in a Django shell so that I can then use "django.db.connection" to show the raw MySQL commands Django is running, but I can't seem to figure out how to run the tests in the Django shell.
I've tried to run tests without migrations (https://pypi.org/project/django-test-without-migrations/) but that seems to have no effect.
In my test settings file, I added the MIGRATION_MODULES variable to address the app "badapp" that has the foreign key field:
MIGRATION_MODULES = { 'badapp': None }
but this made no difference as well.
I would like to know:
1.) How can I verify that this error is caused by adding tables in the incorrect order?
2.) How can I force tables to be added in a specific order when running tests?