assertRaises failing even when exception is raised

180 Views Asked by At

I have a function that throws an exception, but when I use assertRaises to test whether an exception is raised, it fails even though, the exception was in fact raised.

project/app/file.py

from math import pi

def circle_area(r):
    try:
        if type(r) == int:
            result = pi * (r ** 2)  # r = radius
            return result
        else:
            raise TypeError("Radius must be a valid positive integer")
    except Exception as ex:
        print("Error:", ex)

project/test/testing.py

from app.file import circle_area
import unittest

class TestCases(unittest.TestCase):
    def test_case_1(self):
        print("Area when radius of circle is not a positive integer")
        self.assertRaises(Exception, circle_area, 1.1)

testSuite = unittest.TestSuite()
testSuite.addTest(TestCases('test_case_1'))
unittest.TextTestRunner().run(testSuite)

Output:

Area when radius of circle is not a positive integer
Error: Radius must be a valid positive integer       # <-- Exception is clearly raised here
F
======================================================================
FAIL: test_case_1 (__main__.TestCases)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "...project\test\test.py", line 7, in test_case_1
    self.assertRaises(Exception, circle_area, 1.1)
AssertionError: Exception not raised by circle_area

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)

Process finished with exit code 0
0

There are 0 best solutions below