[Django]-Writing django tests that use the main database

2👍

Make a backup of your current database and name it as ‘test_database_name’.

Eg. DB_name = django. Then keep the backup database’s name as test_django.

mysqldump -u username -p database_name > database_backup.sql
mysql -u username -p test_database_name < database_backup.sql

When you run the tests, use this command

python manage.py test --keepdb

Django will use the backup DB for testing and then you don’t have to apply migrations again and again. But make sure the name of the test database is correct. The command –keepdb will keep the DB and won’t allow Django to delete the database everytime you run tests.

Also, every time you run the tests, Django will flush all the data in the backup DB but it won’t flush migrations. So every time you run the test you have to make a SetUp class to set all the users, permissions, groups etc.

1👍

you can run the django test case to persistence the test db.

python manage.py test -k

It will create test database onece, it keeps that.

0👍

You can use pytest to acess / reuse database.

Just use @pytest.mark.django_db in your test case.

pytest is great for testing your django code. I definitely recommend it.

See here for more information

Leave a comment