Search code examples
pythondjango-testingdjango-unittestdjango-tests

TestCase self.assertEqual does not match a similar string


I'am trying to create a model unittest for a ManyToMany relationship. The aim is to check, if there is the right category saved in the table 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)

for self.asserEqual(first_.categories.all(), [category_one]) in the second last row I get this weird assert:

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

I tried many other different ways, but none of it worked. Does any one suppose how I can get the information of first_.categories.all() to compare it with something else?


Solution

  • That'll be because they're not equal - one is a QuerySet, the other is a list - they just happen to have the same str representations.

    You could either cast the QuerySet to a list with list(first_.categories.all()), or a possible solution for this situation may be:

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