在Django中,多个数据库不应该在一个特定的数据库上通过manage.py创建一个测试数据库



在Django中,我使用了多个数据库,但是通过测试多个数据库的功能,如果运行manage.py test **,应该不会创建一个测试数据库。我该如何解决这个问题?

在你的settings.py中,你可以告诉Django在测试时使用哪个数据库。下面是这样做的代码,如果你想使用SQLite,例如:

settings.py:

if 'test' in sys.argv:
    DATABASES['default'] = {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'tests.db',
    }

Django每次运行manage.py test时都会创建一个新数据库,因此您希望在test.py文件中使用fixture 在运行测试之前预加载数据库(如果您需要预加载数据)。

例如,要为User model生成一个fixture,请使用以下代码:
python manage.py dumpdata auth.User --indent=2 > app_name/fixtures/admin.json

要使用fixtures,你可以这样构造你的tests.py:

tests.py:

from django.test import TestCase
class MyTests(TestCase):
    fixtures = [admin.json]
    def setUp(self):
        # other setup code here
    def test_the_obvious(self):
        assert True == True

最新更新