简体   繁体   中英

creating test database for Django Unit testing

How do I populate the test database created while testing the Django test cases with the values from some other database(for ex: the Production database.)

In detail:

when I run the below command,

$ python manage.py test

a test data base is created for the testing purpose, but it doesn't have any data in it. I want the test database created to be populated with some initial values.

Thanks..

You can use dumpdata to get a file with data from your live db.

Then you can load data from a file automatically for a test (see Django tests ):

from django.test import TestCase
from django.core.management import call_command

class Tests(TestCase):
    @classmethod
    def setUpTestData(cls):
        call_command('loaddata', 'myfile', verbosity=0)

You may use django fixtures to populate your test database.

Create a fixture of your production db and write it to some file

python manage.py dumpdata > backup.json

You can populate your test database using this command

python manage.py loaddata backup.json

if you want to do this by running python manage.py test then you should write custom django-admin commands

You want to check out fixtures . Here's a link to docs page: https://docs.djangoproject.com/en/1.8/howto/initial-data/

Basically you might want to dump your current database for testing purposes, so you'd do something like:

python manage.py dumpdata

Then you want to place your file in a directory that Django will look for fixtures. You can either specify it in settings with FIXTURE_DIRS variable or use default. The default is simply inside a fixtures directory in your Django app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM