我刚刚在django上开了一个小应用程序。目前,它的目标只是管理测试人员(即用户)和团队。这是我的model.py:
from django.db import models
class Team(models.Model):
name = models.CharField(max_length=200)
def __unicode__(self):
return self.name
def get_testers(self):
return self.tester_set.all()
class Tester(models.Model):
team = models.ForeignKey(Team)
visa = models.CharField(max_length=3)
privileged = models.BooleanField()
def __unicode__(self):
return self.visa
我正在尝试为“get_testers”函数编写测试。 这是:
from models import Team, Tester
def testTeamGetTesters_test():
t = list(Team.objects.get(id=2L).get_testers())
a = Tester(visa = 'a', privileged = True)
b = Tester(visa = 'b', privileged = True)
assert(t[0].visa == a.visa and t[0].privileged == a.privileged and t[1].visa == b.visa and t[1].privileged == b.privileged)
但是当我跑步时:
$ python manage.py test tmg
我收到此错误:
nosetests --verbosity 1 tmg
E
======================================================================
ERROR: tempsite.tmg.tests.testTeamGetTesters_test
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.6/nose/case.py", line 183, in runTest
self.test(*self.arg)
File "/home/charlie/code/tempsite/../tempsite/tmg/tests.py", line 8, in testTeamGetTesters_test
t = list(Team.objects.get(id=2L).get_testers())
File "/usr/lib/pymodules/python2.6/django/db/models/manager.py", line 132, in get
return self.get_query_set().get(*args, **kwargs)
File "/usr/lib/pymodules/python2.6/django/db/models/query.py", line 341, in get
% self.model._meta.object_name)
DoesNotExist: Team matching query does not exist.
所以,我写了几乎相同的测试,但直接可以运行:
from models import Team, Tester
t = list(Team.objects.get(id=2L).get_testers())
a = Tester(visa = 'a', privileged = True)
b = Tester(visa = 'b', privileged = True)
print "%r" % (t[0].visa == a.visa and t[0].privileged == a.privileged and t[1].visa == b.visa and t[1].privileged == b.privileged)
......当我跑的时候:
$ python tests.py
True
这非常令人困惑......我检查了数据库,对象都完美检索,但我仍然收到此错误...
答案 0 :(得分:1)
您是否在测试中的某处创建了ID为2的Team对象?不要忘记测试从空白数据库开始。