How to preserve django test database after running test cases

You can prevent the test databases from being destroyed by using the test --keepdb option.

https://docs.djangoproject.com/en/dev/topics/testing/overview/#the-test-database


According to the docs, you can preserve the database after running tests by:

$ python manage.py test -k

or

$ python manage.py test --keepdb

While passing -k to manage.py test will retain the test database, it will still delete the records that was created in your test cases. This is because Django's TestCase classes will still reset your database after every test case (django.test.TransactionTestCase will do a flush, while django.test.TestCase will wrap each of your test case in a transaction and do a rollback when the test case is done).

The only real solution to making Django retain test data is to extend the TestCase class and override the code that resets your database.

However, if you do not have the time to do this, you can also make your test case pause execution before it finishes, giving you the time to inspect your database before it gets reset. There are several ways of achieving this, but, now, THIS IS A HACK, asking for user input in your Python code will make Python pause execution and wait for user input.

from django.test import TestCase


class MyTestCase(TestCase):
    def test_something_does_something(self):
        result = do_something_with_the_database()
        self.assertTrue(result)

        # Ask for `input` so execution will pause and wait for input.
        input(
            'Execution is paused and you can now inspect the database.\n'
            'Press return/enter key to continue:')

Alternatively, you can also use pdb's set_trace function, which will also make the execution pause and wait for input, and at the same time lets you debug the environment in that point of code execution.

Just make sure that you remove the input() (or pdb.set_trace()) call before you send your code to your automated build system or else it will wait for user input and time out.