python - TestCase self.assertEqual 不匹配类似的字符串

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

我正在尝试为多对多关系创建模型单元测试。 目的是检查 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/

相关文章:

python - Django Rest框架测试权限

python - 如何获取上下文来测试我的 View 页面?

python - 在Django的unittest中更改Client()的默认域

python - 如何检查一个列表/字典的元素是否存在于python中的另一个列表/字典中

python - 将 opencv 图像连同其他数据一起发送到 Flask Server

python - 使用 selenium 运行 django-test 时管道错误

python - 有没有办法在 Django 的单元测试中获取 Client() 的默认域?

python - 获取 django 模型属性的类型

python - 在 python 中使用带宽方法进行投资组合再平衡

python数据框列应用函数