I would like to write a function that raises an error when it fails and then passes that to unittest. Consider the following:
class undefinedTerms(unittest.TestCase):
def setUp(self):
self.A = frozenset((1,2,3,2,1,4,2,5,6,3,5,7,1,5,2,4,8))
self.B = frozenset((1,4,5,6,3,4,2,5,4,3,1,3,4,2,5,3,6,7,4,2,3,1))
self.C = frozenset((1,2,3,2,1,4,2,5,6,3,5,7,1,5,2,4))
self.D = (1,2,1)
def is_a_set(self,set_this):
try:
assert isinstance(set_this, (set,frozenset))
except TypeError:
raise TypeError("The object you passed is not a set.")
return True
def test_A_is_a_set(self):
self.assertTrue(self.is_a_set(self.A))
def test_B_is_a_set(self):
self.assertTrue(self.is_a_set(self.B))
def test_C_is_a_set(self):
self.assertTrue(self.is_a_set(self.C))
def test_D_is_a_set(self):
self.assertTrue(self.is_a_set(self.D), self.is_a_set(self.D))
suite = loader.loadTestsFromTestCase(undefinedTerms)
unittest.TextTestRunner(verbosity=2).run(suite)
This gives the following output.
test_A_is_a_set (__main__.undefinedTerms) ... ok
test_B_is_a_set (__main__.undefinedTerms) ... ok
test_C_is_a_set (__main__.undefinedTerms) ... ok
test_D_is_a_set (__main__.undefinedTerms) ... FAIL
======================================================================
FAIL: test_D_is_a_set (__main__.undefinedTerms)
----------------------------------------------------------------------
Traceback (most recent call last):
File "<ipython-input-33-4751f8653e7a>", line 27, in test_D_is_a_set
self.assertTrue(self.is_a_set(self.D), self.is_a_set(self.D))
File "<ipython-input-33-4751f8653e7a>", line 12, in is_a_set
(type(set_this) is set))
AssertionError
----------------------------------------------------------------------
Ran 4 tests in 0.001s
FAILED (failures=1)
What I would like is for the AssertionError
to be the TypeError
defined in the function. I am open to radically different implementations.
Update
I think I was unclear as to precisely what I am after. After reading comments and answers I believe what I want is to create a custom assertion.
This has previously been addressed here.