首页 > 解决方案 > Django test cases - data not getting loaded into default database

问题描述

I am writing test cases to one of my learning project. I have added sample data via admin site, I can see that data successfully.

While writing test cases for the same model, seems data not loading into test database. I am not sure what I am missing here. Any suggestions greatly appreciated.

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')

test result

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'...

I have tested my model via shell as well

>>> 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'
>>>

标签: pythondjangotesting

解决方案


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

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

因为您正在使用一个类进行测试,所以您可以使用创建的 todo usingself.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(),然后 simpleprint(todo.id)将向您展示 pk 发生的情况。


推荐阅读