negating a custom unittest in python

Viewed 77

I've written a custom assertion to test if two lists of objects contain objects with the same attributes, and now I want to use the negation of the test to check if two lists are unequal.

from unittest import TestCase
from classes import *

class BaseTestCase(TestCase):
    def assertCountObjectsEqual(self, list1, list2):
        if len(list1) != len(list2):
            raise AssertionError("lists must be the same length")
        elif any(t1.__class__ != t2.__class__ or t1.__dict__ != t2.__dict__ for t1, t2 in zip(list1, list2)):
            raise AssertionError("objects are not the same")
        else:
            pass

The positive case works

class TestFillDemand(BaseTestCase):
    def test_fruit(self):
        self.assertCountObjectsEqual([Apple(), Apple(), Banana()], [Apple(), Apple(), Banana()])

But I want to be able to reuse the code for something like the following:

    def test_fruit_unequal(self):
        self.assertRaises(AssertionError, self.assertCountObjectsEqual([Apple(), Apple(), Banana()], [Apple(), Banana()]))

rather than having to redefine an assertCountObjectsUnequal method. Unfortunately the above code doesn't work.

Is there an easy way to do that?

1 Answers
Related