Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Testing: Does --keepdb reset changes made during tests?

According to the Django docs regarding tests, the --keepdb flag will preserve the the test database for future runs.

https://docs.djangoproject.com/en/1.8/ref/django-admin/#django-admin-option---keepdb

Just to be clear, will any changes made to the database by the tests (ie: object.save() ) be reset automatically? Or will these changes need to be reversed from within the tests?

like image 765
Adam Starrh Avatar asked Jul 08 '15 09:07

Adam Starrh


People also ask

How does Django test work?

Django provides a test framework with a small hierarchy of classes that build on the Python standard unittest library. Despite the name, this test framework is suitable for both unit and integration tests. The Django framework adds API methods and tools to help test web and Django-specific behavior.

What order Django tests are run?

Order in which tests are executedAll TestCase subclasses are run first. Then, all other Django-based tests (test cases based on SimpleTestCase , including TransactionTestCase ) are run with no particular ordering guaranteed nor enforced among them. Then any other unittest.

What is RequestFactory in Django?

The request factory The RequestFactory shares the same API as the test client. However, instead of behaving like a browser, the RequestFactory provides a way to generate a request instance that can be used as the first argument to any view.


1 Answers

If you're using Django's default TestCase, all tests are run in a transaction, which is rolled back when the tests finishes. If your database supports transactions, you won't have to clean up anything.

If you're using Django's LiveServerTestCase or TransactionTestCase, all tables are truncated after each test, and the initial data, which is serialized before the test, is reloaded into the test database. This will not preserve any data for migrated apps, only for unmigrated apps.

The --keepdb option will not do anything special with the database. It simply prevents that the test database is destroyed, and if a database is found at the start of the tests, it is used instead of creating a new one. So, any data that is somehow left in the database when the tests finish will be seen as initial data. This is mostly relevant if some error or a user interrupt prevents tests without transactions from cleaning up the database. In that case it may be a good idea to recreate the database.

like image 178
knbk Avatar answered Oct 18 '22 19:10

knbk