Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django unit test without creating test database every time I run

Seems like "manage.py test" creates test database every time I run the test. Is there a way to prevent creating test database each time I run test but just truncate data (flush)?

My tables are almost about 40 tables (even for single app, not the whole project), and makes me sick every time I run test.

like image 846
CIF Avatar asked Aug 25 '11 21:08

CIF


People also ask

Should unit tests require a database?

Unit tests shouldn't depend on infrastructureThere's no way to test this function without having a database connection available at the time of testing. If a new developer clones the project they will need to set up a database or else tests will fail.

What database does Django test use?

To help you get started, Django provides and uses a sample settings module that uses the SQLite database. See Using another settings module to learn how to use a different settings module to run the tests with a different database.

What is RequestFactory in Django?

The request factory class RequestFactory. 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.


2 Answers

From Django 1.8 on you could use the --keepdb flag, when calling the manage.py

New in Django 1.8: You can prevent the test databases from being destroyed by adding the --keepdb flag to the test command. This will preserve the test database between runs. If the database does not exist, it will first be created. Any migrations will also be applied in order to keep it up to date. (https://docs.djangoproject.com/en/1.8/topics/testing/overview/#the-test-database)

So your call could look as follows:

python manage.py test --keepdb 

Or using the shorthand -k it could look like that:

python manage.py test -k 
like image 60
Kim Avatar answered Sep 18 '22 15:09

Kim


Depending on your needs you have a few choices:

  • You could write a custom test runner or adjust the default one: https://docs.djangoproject.com/en/1.6/topics/testing/advanced/#other-testing-frameworks

  • You could use SimpleTestCase

  • There are also add-ons like django-test-utils (although I'm not sure if that specific one works with modern Django versions).

  • Alternatively, to speed everything up, you could use SQLite's in-memory database OR create your test database in RAM disk (like tmpfs or ramfs) - in fact this is orthogonal to using other techniques.

like image 29
Tomasz Zieliński Avatar answered Sep 22 '22 15:09

Tomasz Zieliński