我正在尝试为多对多关系创建模型单元测试。 目的是检查 Ingredient 表中是否保存了正确的类别。
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()
的信息并将其与其他内容进行比较吗?
最佳答案
这是因为它们不相等 - 一个是 QuerySet
,另一个是 list
- 它们只是碰巧具有相同的 str
表示。
您可以使用 list(first_.categories.all())
将 QuerySet
转换为列表,或者这种情况的可能解决方案可能是:
self.assertEqual(first_.categories.get(), category_one)
关于python - TestCase self.assertEqual 不匹配类似的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37013738/