【发布时间】:2014-07-22 03:20:45
【问题描述】:
有没有办法在 django 测试中检查两个对象列表是否相等。
假设我有一些模型:
class Tag(models.Model):
slug = models.SlugField(max_length=50, unique=True)
def __unicode__(self):
return self.slug
然后我运行这个简单的测试:
def test_equal_list_fail(self):
tag_list = []
for tag in ['a', 'b', 'c']:
tag_list.append(Tag.objects.create(slug=tag))
tags = Tag.objects.all()
self.assertEqual(tag_list, tags)
这失败了:
======================================================================
FAIL: test_equal_list_fail (userAccount.tests.ProfileTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "path/to/tests.py", line 155, in test_equal_list_fail
self.assertEqual(tag_list, tags)
AssertionError: [<Tag: a>, <Tag: b>, <Tag: c>] != [<Tag: a>, <Tag: b>, <Tag: c>]
----------------------------------------------------------------------
这将起作用:
def test_equal_list_passes(self):
tag_list = []
for tag in ['a', 'b', 'c']:
tag_list.append(Tag.objects.create(slug=tag))
tags = Tag.objects.all()
for tag_set in zip(tags, tag_list):
self.assertEqual(*tag_set)
但是,这失败了:
def test_equal_list_fail(self):
tag_list = []
for tag in ['a', 'b', 'c']:
tag_list.append(Tag.objects.create(slug=tag))
tags = Tag.objects.all()
for tag_set in zip(tags, tag_list):
print "\n"
print tag_set[0].slug + "'s pk is %s" % tag_set[0].pk
print tag_set[1].slug + "'s pk is %s" % tag_set[1].pk
print "\n"
self.assertIs(*tag_set)
与:
Creating test database for alias 'default'...
.......
a's pk is 1
a's pk is 1
F.
======================================================================
FAIL: test_equal_list_fail (userAccount.tests.ProfileTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "path/to/tests.py", line 160, in test_equal_list_fail
self.assertIs(*tag_set)
AssertionError: <Tag: a> is not <Tag: a>
这是预期的行为吗?
编辑回应评论
这种比较有效:
class Obj:
def __init__(self, x):
self.x = x
>>> one = Obj(1)
>>> two = Obj(2)
>>> a = [one, two]
>>> b = [one, two]
>>> a == b
True
为什么其他数组的测试失败了?
【问题讨论】:
-
zip() 起作用的原因是标签的文本表示是 slug,这就是您要比较的内容。
-
为什么不比较数组做同样的事情?我将编辑我的问题以显示示例
标签: django django-testing django-tests