【问题标题】:Django test cases - data not getting loaded into default databaseDjango 测试用例 - 数据未加载到默认数据库中
【发布时间】:2021-01-12 23:56:44
【问题描述】:

我正在为我的一个学习项目编写测试用例。我已经通过管理站点添加了示例数据,我可以成功看到该数据。

为同一模型编写测试用例时,似乎数据未加载到测试数据库中。我不确定我在这里缺少什么。任何建议都非常感谢。

todos/models.py

from django.db import models

# Create your models here.
class Todo(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()

    def __str__(self):
        return self.title

todos/tests.py

from django.test import TestCase
from .models import Todo

# Create your tests here
class TodoModelTest(TestCase):


    @classmethod
    def setupTestData(cls):
        Todo.objects.create(title='first todo', body='a body here')

    def test_todo_count(self):
        todo_count = Todo.objects.all()
        self.assertEqual(len(todo_count), 1)


    def test_title_content(self):
        todo = Todo.objects.get(id=1)
        expected_object_name = f'{todo.title}'
        self.assertEquals(expected_object_name, 'first todo')

    def test_body_content(self):
        todo = Todo.objects.get(id=1)
        expected_object_body = f'{todo.body}'
        self.assertEquals(expected_object_name, 'a body here')

测试结果

Creating test database for alias 'default'...
System check identified no issues (0 silenced).
EEF
======================================================================
ERROR: test_body_content (todos.tests.TodoModelTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/tests.py", line 23, in test_body_content
    todo = Todo.objects.get(id=1)
  File "/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/python3.9/site-packages/django/db/models/query.py", line 429, in get
    raise self.model.DoesNotExist(
todos.models.Todo.DoesNotExist: Todo matching query does not exist.

======================================================================
ERROR: test_title_content (todos.tests.TodoModelTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/tests.py", line 18, in test_title_content
    todo = Todo.objects.get(id=1)
  File "/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/python3.9/site-packages/django/db/models/query.py", line 429, in get
    raise self.model.DoesNotExist(
todos.models.Todo.DoesNotExist: Todo matching query does not exist.

======================================================================
FAIL: test_todo_count (todos.tests.TodoModelTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/tests.py", line 14, in test_todo_count
    self.assertEqual(len(todo_count), 1)
AssertionError: 0 != 1

----------------------------------------------------------------------
Ran 3 tests in 0.005s

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

我也通过 shell 测试了我的模型

>>> from todos.models import Todo
>>> t = Todo.objects.create(title="this is title", body="This is body")
>>> t.title
'this is title'
>>> t.body
'This is body'
>>>

【问题讨论】:

  • 您打电话给setUpTestData而不是简单的setUp有什么特殊原因吗?我不是超级熟悉。 setUpTestData 但我认为它会为每个测试创建新对象。
  • @hansTheFranz,感谢您的回复。不,我只是按照我以前练习的教程中的名称。
  • @hansTheFranz 成功了,我重命名为setUp,它起作用了:D。谢谢你。请添加您的评论作为答案。
  • 我认为这正是为什么? stackoverflow.com/questions/29428894/…

标签: python django testing


【解决方案1】:

您的测试数据库会在测试期间增加 pk,即使 db 中只有一个。状态回退,但 pk 计数器不回退。

如果需要显式测试主键,有:https://docs.djangoproject.com/en/3.1/topics/testing/advanced/#django.test.TransactionTestCase.reset_sequences

因为您正在使用一个类进行测试,所以您可以使用 self.todo 创建的待办事项

class TodoModelTest(TestCase):

    @classmethod
    def setupTestData(cls):
        self.todo = Todo.objects.create(title='first todo', body='a body here')

    def test_title_content(self):
        expected_object_name = f'{self.todo.title}'
        self.assertEquals(expected_object_name, 'first todo')

如果您对 pk 感兴趣,可以尝试使用 todo = Todo.objects.first(),然后简单的 print(todo.id) 将向您展示 pk 发生了什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-07
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    • 1970-01-01
    相关资源
    最近更新 更多