4

I want to use the --keepdb option that allow to keep the database after running tests, because in my case, the creation of the dabatase takes a while (but running tests is actualy fast)

However, I would like to keep the database structure only, not the data. Each time a run tests, I need an empty database.

I know I could use tearDown method to delete each object created, but it is a tedious and error-prone way to do. I just need to find a way to tell Django to flush the whole dabatase (not destroy it) at the end of the unit tests.

I have thinking of making a very simple script that:

  1. Run the tests keeping the db: manage.py test --keepdb
  2. run manage.py flushdb --database test_fugodb

However, with 2nd step, I got a django.db.utils.ConnectionDoesNotExist: The connection test_fugodb doesn't exist. What is the name of this test db? I took the one displayed when running tests:

What's wrong? Thanks!

David Dahan
  • 10,576
  • 11
  • 64
  • 137
  • doesnt django automatically delete, whatever you create within the tests. Assuming you are running tests with `python manage.py test`? – N. Ivanov Nov 28 '17 at 15:51
  • 1
    Sorry my initial post was not clear enough, I updated it. TL/DR: I want to use --keepdb to avoid creating the database each time. – David Dahan Nov 28 '17 at 15:55
  • 1
    Deploying the database should be a separate step from running tests in the first place. This is one of those situations where the, "It does everything for you out of the box!" frameworks starts getting in your way instead of helping because they didn't foresee your use case. Most likely, you'll need to integrate a task somewhere to truncate your data. – jpmc26 Nov 28 '17 at 16:21
  • 2
    @jpmc26 I was thinking of using `flushdb --database ` but can't find the right name of the test database (cf. my edited post). Thanks! – David Dahan Nov 28 '17 at 16:35

1 Answers1

1

drop all the collections of the test database after tests. in this way, the db doesn't need to be recreated, and the db is empty after tests.

for the problem of test database name, it is described in django doc: https://docs.djangoproject.com/en/1.8/topics/testing/overview/#the-test-database

you could create your own test runner to replace your script: django unit tests without a db

Hao XU
  • 352
  • 1
  • 11
  • Is it not already in a separate db? When running tests: `Creating test database for alias 'default' ('test_fugodb')...` – David Dahan Nov 28 '17 at 16:01
  • yes, it is a separate db, but not a new db every time. if creation of db is expensive, you could keep it and drop all its collections after the tests. – Hao XU Nov 28 '17 at 16:08
  • I have re-read your post, don't know which point i missed. Hope the others get your points. – Hao XU Nov 28 '17 at 16:17
  • Thanks for your edit. i edited my question too, cf. the "I have thinking of making a "script" that..." part – David Dahan Nov 28 '17 at 16:28