LiveServerTestCase设置.数据库配置不正确

2024-04-29 02:05:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试建立一个LiveServerTestCase。在

为此,我在Testclass中创建一个用户

class ExampleTest(LiveServerTestCase):
    user = User.objects.create_superuser('Testuser','test@user.com','1234')
    user.save()
.
.
.(rest of the test)

如果没有这一行,服务器和测试将启动,但显然它无法登录,因为之前没有用户创建。在

但有了这条线,我得到了

^{pr2}$

错误。在

我需要在中设置服务器吗设置.py对于LiveServerTestCase,如果是,使用哪些值或者在哪里可以找到它们?在

更新:

我在做这个测试

python manage.py test

所以它建立了一个数据库,我不需要在设置.py,还是我错了。在

更新2:

我已经定义了一个“生产”数据库(在我问这个问题之前),它看起来像这样:

DATABASES = {
 'default': {
     'ENGINE': 'django.db.backends.postgresql_psycopg2',
     'HOST': 'localhost',  # 10.1.2.41
     'NAME': 'pim_testdatabase',
     'USER': 'postgres',
     'PASSWORD': '1234',
     'PORT': '5432',
     'HAS_HSTORE': True,
     'TEST':{
             'NAME': 'test_pim_testdatabase'
      },
  },
}

但例外情况还是出现了。在


Tags: 用户namepytest服务器数据库objectsdatabase
2条回答

您需要在^{}设置中设置数据库。在

Django sets up a test database corresponding to every database that is defined in the DATABASES definition in your settings file.

By default the test databases get their names by prepending test_ to the value of the NAME settings for the databases defined in DATABASES.

如果要使用其他数据库名称,请在TEST字典中为DATABASES中的任何给定数据库指定NAME。在

测试数据库配置示例:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'USER': 'mydatabaseuser',
        'NAME': 'mydatabase',
        'TEST': { # test database settings
            'NAME': 'mytestdatabase', # test database name
        },
    },
}

问题是您在类定义中创建用户。它在加载测试类时运行,在创建数据库之前。在

class ExampleTest(LiveServerTestCase):
    user = User.objects.create_superuser('Testuser','test@user.com','1234')
    user.save()  # This save isn't required   it has been saved already

您可以通过将用户创建移动到单个测试中来解决该问题。然后,在创建数据库之后,当测试方法运行时,将创建用户。在

^{pr2}$

django1.8有一个^{}方法,您可以在其中为整个测试用例设置一次初始数据。这样做更快,重复性更少。在

class ExampleTest(LiveServerTestCase):
    @classmethod
    def setUpTestData(cls):
        # Set up data for the whole TestCase
        self.user = User.objects.create_superuser('Testuser','test@user.com','1234')

    def test_user(self):
        # access the user with self.user
        ...

在没有setUpTestData的Django的早期版本中,可以在^{}方法中创建用户。在

class ExampleTest(LiveServerTestCase):
    def setUp(self):
        self.user = User.objects.create_superuser('Testuser','test@user.com','1234')

相关问题 更多 >