Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Test Python Function for Exception Handling



When you write tests in Python, it is important to make sure that your function raises the correct exception for invalid input or unexpected conditions. This helps to confirm that your code handles errors properly.

You can test exceptions using the following ways in python ?

  • Using the try-except blocks manually
  • Using the unittest module
  • Using the pytest module

Using try-except Block

One of the basic ways to test for exceptions is by manually using a try-except block. This allows you to execute code and catch any exceptions that occur.

If the function doesn't raise the expected error, you can display a message or even raise an error yourself to indicate that something went wrong.

Example

In this example, the try-except block tests the divide() function to check if it raises a ValueError when trying to divide a number by zero -

def divide(a, b):
   if b == 0:
      raise ValueError("Cannot divide by zero")
   return a / b

# Manual test
try:
   divide(10, 0)
except ValueError:
   print("Test passed: ValueError was raised")
else:
   print("Test failed: ValueError was not raised")

We get the output as shown below -

Test passed: ValueError was raised

Using uthe nittest Module

The unittest module has a method called assertRaises() to check if an exception is thrown during a function call. You can use it inside a test case class that inherits from unittest.TestCase class.

Example

In this example, assertRaises() method checks that ValueError is raised when dividing by zero -

import unittest

def divide(a, b):
   if b == 0:
      raise ValueError("Cannot divide by zero")
   return a / b

class TestDivide(unittest.TestCase):
   def test_divide_by_zero(self):
      self.assertRaises(ValueError, divide, 10, 0)

if __name__ == "__main__":
   unittest.main()

Following is the output of the above code -

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

OK

Using with self.assertRaises() Function

Another way to test if an exception is raised is by using the self.assertRaises() function as a context manager with the with statement. This approach is helpful, especially when the function you are testing contains multiple lines of code or steps.

By using this approach, all the code inside the with block is expected to raise the specified exception. If it doesn't, the test will fail.

Example

In this example, we use the self.assertRaises() function to verify that a specific exception (ValueError) is raised during the execution of the code within the with block -

import unittest

class TestDivide(unittest.TestCase):
   def test_divide_by_zero(self):
      with self.assertRaises(ValueError):
         divide(10, 0)

if __name__ == "__main__":
   unittest.main()

We get the output as follows -

E
======================================================================
ERROR: test_divide_by_zero (__main__.TestDivide.test_divide_by_zero)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/cg/root/6818cec0b940d/main.py", line 6, in test_divide_by_zero
    divide(10, 0)
    ^^^^^^
NameError: name 'divide' is not defined

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

FAILED (errors=1)

Using pytest.raises() Function

If you are using pytest module, you can test for exceptions with the help of pytest.raises() function. It functions similarly to a context manager, making the code very readable.

Example

In the following example, pytest.raises() function is used to check if the divide() function raises a ValueError when dividing by zero. Save the following code in a file named greet.py -

import pytest

def divide(a, b):
   if b == 0:
      raise ValueError("Cannot divide by zero")
   return a / b

def test_divide_by_zero():
   with pytest.raises(ValueError) as excinfo:
      divide(10, 0)
   print(f"Error: {excinfo.value}")

Open your Command Prompt and set the location where your file greet.py is saved. Then, run the following command to execute the test -

pytest -s greet.py

Without the -s flag, pytest suppresses the print output to keep the test results clean. The following output will be displayed in the terminal -

================================================= test session starts =================================================
platform win32 -- Python 3.13.2, pytest-8.3.5, pluggy-1.5.0
rootdir: C:\Users\Tutorialspoint\Desktop
plugins: anyio-4.9.0
collected 1 item

greet.py Error: Cannot divide by zero
.

================================================== 1 passed in 0.04s ==================================================

Testing for Error Messages

You can also check if the exception message contains specific text by using the match keyword in pytest.raises() function, or by manually checking the exception object.

Example

In the following example, we use the pytest.raises() function with the match keyword to make sure that the exception message includes the phrase "divide by zero" -

def test_error_message():
   with pytest.raises(ValueError, match="divide by zero"):
      divide(5, 0)

This ensures that not only the correct exception type is raised, but also that the exception message contains the expected text.

Updated on: 2025-05-15T13:00:41+05:30

345 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements