简体   繁体   English

创建测试数据库Django

[英]Creating a Testing Database Django

I have a mysql database defined in settings.py 我在settings.py中定义了一个mysql数据库

DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME':'<name>',
            'USER':'<user>',
            'PASSWORD':'<password>'
        }
    }

Now I need to create a test database for my unittesting. 现在,我需要为单元测试创​​建一个测试数据库。 Where do I need to mention the settings of test database or I don't have to mention them at all? 我在哪里需要提及测试数据库的设置,或者根本不需要提及它们?

For testing when I do: 我做测试时:

python manage.py test my_app

it says: 它说:

Creating test database for alias 'default'...
Skipping creation of NoticeTypes as notification app not found
E
======================================================================
ERROR: test_update_quiz (toolbox.tests.TestQuizCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/opt/2.0/site/toolbox/tests.py", line 20, in test_update_quiz
    akit = AssignmentKit.objects.get(pk = akit_id)
  File "/usr/local/lib/python2.7/site-packages/django/db/models/manager.py", line 131, in get
    return self.get_query_set().get(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 366, in get
    % self.model._meta.object_name)
DoesNotExist: AssignmentKit matching query does not exist.

----------------------------------------------------------------------
Ran 1 test in 0.003s

FAILED (errors=1)
Destroying test database for alias 'default'...

The error the test gives is wrong. 测试给出的错误是错误的。 Because I do have that object in my database I checked from ORM. 因为我的数据库中确实有该对象,所以我从ORM中进行了检查。 Why is this error coming? 为什么会出现此错误? are my database not properly linked? 我的数据库没有正确链接吗?

The docs for testing do explain this. 测试文档确实解释了这一点。 You don't create a database for tests, Django does it automatically when the tests are run. 您无需为测试创建数据库,而Django在测试运行时会自动创建。 But the db is created from scratch each time, so your tests themselves need to populate the db with any required data: either via fixtures, or by creating the entities directly in the test or in the setUp method. 但是db每次都是从头开始创建的,因此您的测试本身需要用任何必需的数据填充db:通过固定装置,或者通过直接在测试中或在setUp方法中创建实体。

The whole point of unit tests is that they are entirely self-contained, and don't rely on any external state: using an existing database would violate that. 单元测试的全部要点是它们是完全独立的,并且不依赖任何外部状态:使用现有数据库将违反该要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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