1

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?

pillow_willow
  • 99
  • 3
  • 11
  • 1
    It is most probably because of types are not matching. all() returns queryset and you're comparing it with a list. Have you check it? – Heval May 03 '16 at 20:34
  • Try `self.assertEqual(first_.categories.get(), category_one)` if you want to test that there's only one result there. – Ben May 03 '16 at 22:03

1 Answers1

1

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)
Ben
  • 6,687
  • 2
  • 33
  • 46
  • Thanks for the help. And this is for those who come along with the same problem and wants to compare more then one `QuerySet` value. At least I figured out how it will work in my case: `self.assertEqual([value for value in last_.categories.all()], [category_one, category_two,])` – pillow_willow May 04 '16 at 08:26
  • No worries. You can just do `list(last_.categories.all())` instead of using the list comprehension if you prefer. – Ben May 04 '16 at 10:02
  • Nice. Yes that looks much better – pillow_willow May 05 '16 at 21:43