我读过关于从测试开始构建程序的内容,所以我想我会试一试。我已经创建了我的初始project
和app
以及model
,但是当我尝试运行测试时,出现“不存在”错误。我已经进行了迁移,在运行测试之前还有更多的事情要做吗?这是我的代码:
models.py
from django.db import models
class Name(models.Model):
first_name = models.CharField(
"First Name",
max_length=100,
)
middle_name = models.CharField(
"Middle Name or Initial",
max_length=100,
default='',
)
last_name = models.CharField(
"Last Name",
max_length=200,
)
def __str__(self):
return f'{self.last_name}, {self.first_name}'
tests.py
from django.test import TestCase
from contacts.models import Name
class TestNameModel(TestCase):
@classmethod
def setupTestData(cls):
Name.objects.create(first_name='Banny', last_name='Banvil')
def test_name_exists(self):
name = Name.objects.get(id=1)
print (name)
我得到的错误:
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
E
======================================================================
ERROR: test_name_exists (contacts.tests.TestNameModel)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/CrazyCarl/Software/contact/contacts/tests.py", line 12, in test_name_exists
name = Name.objects.get(id=1)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/query.py", line 403, in get
self.model._meta.object_name
contacts.models.DoesNotExist: Name matching query does not exist.
----------------------------------------------------------------------
Ran 1 test in 0.002s
FAILED (errors=1)
Destroying test database for alias 'default'...
我尝试在终端中创建一个对象以查看它是否正常工作:
>>>from contacts.models import Name
>>>Name.objects.create(last_name='John', first_name='Smith')
<Name: John, Smith>
>>>Name.objects.all()
<QuerySet [<Name: John, Smith>]>
>>>n = Name.objects.get(id=1)
>>>print (n)
John, Smith
我错过了什么?
答案 0 :(得分:0)
最好使用fixtures。基本上,当你尝试get(id = 1)
时,你的数据库中没有任何东西此外,灯具将节省您在该功能中的时间。祝你好运!
答案 1 :(得分:0)
setUpTestData
而非setupTestData