TestCase self.assertEqual 不匹配相似的字符串

TestCase self.assertEqual does not match a similar string

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

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

我尝试了许多其他不同的方法,但 none 行得通。有没有人想过我怎样才能得到 first_.categories.all() 的信息来与其他东西进行比较?

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

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

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