【问题标题】:TestCase self.assertEqual does not match a similar stringTestCase self.assertEqual 不匹配类似的字符串
【发布时间】:2016-08-29 01:34:32
【问题描述】:

我正在尝试为多对多关系创建模型单元测试。 目的是检查是否在成分表中保存了正确的类别。

class IngredientModelTest(TestCase):
    def test_db_saves_ingredient_with_category(self):
        category_one = IngredientsCategory.objects.create(name='Food')
        first_Ingredient = Ingredient.objects.create(name='Apple')
        first_Ingredient.categories.add(category_one)

        category_two = IngredientsCategory.objects.create(name='Medicine')
        second_Ingredient = Ingredient.objects.create(name='Antibiotics')
        second_Ingredient.categories.add(category_two)

        first_ = Ingredient.objects.first()
        self.assertEqual('Apple', first_.name)
        self.assertEqual(first_.categories.all(), [category_one])
        self.assertEqual(first_, first_Ingredient)

对于倒数第二行的self.asserEqual(first_.categories.all(), [category_one]),我得到了这个奇怪的断言:

AssertionError: [<IngredientsCategory: Food>] != [<IngredientsCategory: Food>]

我尝试了许多其他不同的方法,但都没有奏效。有没有人想我如何获得first_.categories.all() 的信息来与其他东西进行比较?

【问题讨论】:

  • 这很可能是因为类型不匹配。 all() 返回查询集,您将其与列表进行比较。你检查了吗?
  • 如果您想测试那里只有一个结果,请尝试self.assertEqual(first_.categories.get(), category_one)

标签: python django-testing django-unittest django-tests


【解决方案1】:

那是因为它们不相等 - 一个是 QuerySet,另一个是 list - 它们恰好具有相同的 str 表示形式。

您可以将QuerySet 转换为带有list(first_.categories.all()) 的列表,或者针对这种情况的可能解决方案是:

self.assertEqual(first_.categories.get(), category_one)

【讨论】:

  • 感谢您的帮助。这适用于那些遇到同样问题并想要比较多个QuerySet 值的人。至少我知道它在我的情况下是如何工作的:self.assertEqual([value for value in last_.categories.all()], [category_one, category_two,])
  • 不用担心。如果您愿意,可以只使用list(last_.categories.all()) 而不是使用列表推导。
  • 不错。是的,看起来好多了
猜你喜欢
  • 2021-07-26
  • 2011-05-11
  • 2013-07-10
  • 1970-01-01
  • 1970-01-01
  • 2013-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多