assertraises is a function that fails unless an exception is raised by an object of a class. It is mostly used in testing scenarios to prevent our code from malfunctioning.,The program gives an error when a string is passed as a radius. We want functions to cover all cases of errors, which is why we need to use assertRaises to validate the radius passed. Let’s write the code for the test file:,Imagine that you are asked to write a function that calculates the volume of a sphere where the radius is given.,When we run the code above, it gives an error for boolean and negative values. This error tells us that our test has failed, which means we are on the right track. So, we will remove the invalid values. Now, our test gives the correct output.
def sphere_volume(radius):
pi = 3.141592653589793
return 4 / 3 * pi * (radius ** 3)
r = [1, 2.5, 3.4, 5.6, 7, 9.0]
for x in r:
print("Volume of sphere with radius = ", x, "is", sphere_volume(x))
def sphere_volume(radius):
pi = 3.141592653589793
return 4 / 3 * pi * (radius ** 3)
r = [1, 2.5, 3.4, 5.6, 7, 9.0, -2, -5, True, False, "string"]
for x in r:
print("Volume of sphere with radius = ", x, "is", sphere_volume(x))
I am developing a django app and in my models class I am defining an exception that should be raised when a validation fails:
class MissingValueException(Exception):
""
"Raise when a required attribute is missing."
""
def __init__(self, message):
super(MissingValueException, self).__init__()
self.message = message
def __str__(self):
return repr(self.message)
This code is called from a publication class in a validation method:
def validate_required_fields(self):
# Here is the validation code.
if all_fields_present:
return True
else:
raise MissingValueException(errors)
In my unit test I create a case where the exception should be raised:
def test_raise_exception_incomplete_publication(self):
publication = Publication(publication_type = "book")
self.assertRaises(MissingValueException, publication.validate_required_fields)
Unittest supports skipping individual test methods and even whole classes of tests. In addition, it supports marking a test as an “expected failure,” a test that is broken and will fail, but shouldn’t be counted as a failure on a TestResult.,If the setUp() method raises an exception while the test is running, the framework will consider the test to have suffered an error, and the test method will not be executed.,Note that in order to test something, we use one of the assert*() methods provided by the TestCase base class. If the test fails, an exception will be raised with an explanatory message, and unittest will identify the test case as a failure. Any other exceptions will be treated as errors.,If tests is given, it must be an iterable of individual test cases or other test suites that will be used to build the suite initially. Additional methods are provided to add test cases and suites to the collection later on.
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
if __name__ == '__main__':
unittest.main()
... -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Ran 3 tests in 0.000 s OK
test_isupper(__main__.TestStringMethods)...ok test_split(__main__.TestStringMethods)...ok test_upper(__main__.TestStringMethods)...ok -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Ran 3 tests in 0.001 s OK
python - m unittest test_module1 test_module2 python - m unittest test_module.TestClass python - m unittest test_module.TestClass.test_method
python - m unittest tests / test_something.py
python - m unittest - v test_module
Last Updated : 20 Aug, 2020
assertRaises(exception, function, * args, ** keywords)
assertRaises(exception)
assertRaises(exception, function, * args, ** keywords)
assertRaises(exception)
. -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Ran 1 test in 0.000 s OK
Test that an exception (first argument) is raised when a function is called with any positional or keyword arguments. The test passes if the expected exception is raised, is an error if another exception is raised, or fails if no exception is raised. To catch any of a group of exceptions, a tuple containing the exception classes may be passed as exception.,The testraise() function uses assertRaises() function to see if division by zero occurs when div() function is called. The above code will raise an exception. But changes arguments to div() function as follows −,Python testing framework provides the following assertion methods to check that exceptions are raised.,Tests that regexp matches on the string representation of the raised exception. regexp may be a regular expression object or a string containing a regular expression suitable for use by re.search().
In the example below, a test function is defined to check whether ZeroDivisionError is raised.
import unittest
def div(a, b):
return a / b
class raiseTest(unittest.TestCase):
def testraise(self):
self.assertRaises(ZeroDivisionError, div, 1, 0)
if __name__ == '__main__':
unittest.main()
The testraise() function uses assertRaises() function to see if division by zero occurs when div() function is called. The above code will raise an exception. But changes arguments to div() function as follows −
self.assertRaises(ZeroDivisionError, div, 1, 1)
When a code is run with these changes, the test fails as ZeroDivisionError doesn't occur.
F
===
=== === === === === === === === === === === === === === === === === === === === =
FAIL: testraise(__main__.raiseTest)
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Traceback(most recent call last):
File "raisetest.py", line 7, in testraise
self.assertRaises(ZeroDivisionError, div, 1, 1)
AssertionError: ZeroDivisionError not raised
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Ran 1 test in 0.000 s
FAILED(failures = 1)
Here, testraseRegex() test doesn't fail as first argument. "Point" is found in the second argument string.
=== === === === === === === === === === === === === === === === === === === === === =
FAIL: testraiseRegex(__main__.raiseTest)
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Traceback(most recent call last):
File "C:/Python27/raiseTest.py", line 11, in testraiseRegex
self.assertRaisesRegexp(TypeError, "invalid", reg, "Point", "TutorialsPoint")
AssertionError: TypeError not raised
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
However, the change is as shown below −
self.assertRaisesRegexp(TypeError, "invalid", reg, 123, "TutorialsPoint")
I am developing a django app and in my models class I am defining an exception that should be raised when a validation fails:,This could happen if your tests and your product code are importing your exception class through two different paths, so asserRaises doesn't realize that the exception you got was the one you were looking for., 2 days ago AssertRaises fails even though exception is raised; Testing for expected 404 with Django test client leads to unhandled exception; how to configure django on apache and make https in the apache so that django url should open with https://<ip>:80 port; Where to up django app startup code that must interact with the database? ,So it looks like the exception is raised (which is the case - I even checked it in an interactive IPython session), but it seems that assertRaises is not catching it.
class MissingValueException(Exception): ""
"Raise when a required attribute is missing."
""
def __init__(self, message): super(MissingValueException, self).__init__() self.message = message def __str__(self): return repr(self.message)
class MissingValueException(Exception): ""
"Raise when a required attribute is missing."
""
def __init__(self, message): super(MissingValueException, self).__init__() self.message = message def __str__(self): return repr(self.message)
def validate_required_fields(self): # Here is the validation code.if all_fields_present: return Trueelse: raise MissingValueException(errors)
def test_raise_exception_incomplete_publication(self): publication = Publication(publication_type = "book") self.assertRaises(MissingValueException, publication.validate_required_fields)
=== === === === === === === === === === === === === === === === === === === === === === === = ERROR: test_raise_exception_incomplete_publication(core_knowledge_platform.core_web_service.tests.logic_tests.BusinessLogicTests) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --Traceback(most recent call last): File "/media/data/Dokumente/Code/master_project/core_knowledge_platform/../core_knowledge_platform/core_web_service/tests/logic_tests.py", line 45, in test_raise_exception_incomplete_publicationself.assertRaises(MissingValueException, method, ) File "/usr/lib/python2.7/unittest/case.py", line 465, in assertRaisescallableObj( * args, ** kwargs) File "/media/data/Dokumente/Code/master_project/core_knowledge_platform/../core_knowledge_platform/core_web_service/models.py", line 150, in validate_required_fieldsraise MissingValueException(errors) MissingValueException: 'Publication of type book is missing field publisherPublication of type book is missing field titlePublication of type book is missing field year'