How to check django database schema?

I want to write tests that can show if the database is synchronized with my models.py file. In fact, I already wrote them, only to find out that django creates a new database every time tests are run based on the models.py file. Is there a way to make a models.py test use an existing database schema? The one that is in mysql / postgresql, and not the one that is in /myapp/models.py?

I don’t need the data that the database only cares about in the schema I want my tests to notice that the table in the database has fewer fields than the schema in my models.py.

I am using the unittest framework (actually the django extension for it) if that makes any difference.

thanks

+6
python django unit-testing model
source share
1 answer

What we did was canceled by default test_runner so that it would not create a new database for testing. Thus, it runs a test against any current local database. But be very careful if you use this method, because any changes in the data that you make in your tests will be permanent. I made sure that all our tests return any changes to their original state and save our initial version of our database on the server and are backed up.

To do this, you need to copy the run_test method from django.test.simple to a place in your project - I placed my file myproject / test / test_runner.py

Then make the following changes to this method:

// change old_name = settings.DATABASE_NAME from django.db import connection connection.creation.create_test_db(verbosity, autoclobber=not interactive) result = unittest.TextTestRunner(verbosity=verbosity).run(suite) connection.creation.destroy_test_db(old_name, verbosity) // to: result = unittest.TextTestRunner(verbosity=verbosity).run(suite) 

Be sure to make all the necessary import data at the top, and then set the parameter in your settings file:

 TEST_RUNNER = 'myproject.test.test_runner.run_tests' 

Now when you run the test. /manage.py, Django will run tests against the current state of your database, and not create a new version based on your current model definitions.

Another thing you can do is create a copy of your database locally and then do a check in your new run_test () method as follows:

 if settings.DATABASE_NAME != 'my_test_db': sys.exit("You cannot run tests using the %s database. Please switch DATABASE_NAME to my_test_db in settings.py" % settings.DATABASE_NAME) 

Thus, there is no danger of running tests against your main database.

+8
source share

All Articles