Home » Python

How do you test that a Python function throws an exception?

Here, we are going to learn how do you test that a Python function throws an exception?
Submitted by Sapna Deraje Radhakrishna, on March 02, 2020

This article elaborates on how to implement a test case for a function that raises an exception.

Consider the following function:

import re

def check_email_format(email):
  """check that the entered email format is correct"""
  if not re.match(r"(^[a-zA-Z0-9_.+-][email protected][a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", email):
    raise Exception("Invalid email format")
  else:
    return "Email format is ok"

The above function validates the correctness of the email address. Also, note that the function raises an exception if the format is not correct.

Now, to test such functionality, the pytest ( the testing module of python) has a built-in method called pytest.raises. The below test case helps in understanding the usage of pytest.raises method in order to assert is the method has raised an exception.

In the below example, the test case is asserting if the "check_email_format" raises an exception if the email address is of the correct format, i.e., this is a negative test case, where we expect the test case to fail.

>>> import pytest
>>> def test_email_exception():
...     """test that exception is raised for invalid emails"""
...     with pytest.raises(Exception):
...             assert check_email_format("[email protected]")

Execution of test case:

pytest invalid_test_case.py 
========================================================================================== test session starts ===========================================================================================
platform darwin -- Python 3.7.0, pytest-5.3.5, py-1.8.1, pluggy-0.13.1
rootdir: /Users/XXX/XXX-work/src
collected 1 item                                                                                                                                                                                         

invalid_test_case.py F                                                                                                                                                                             [100%]

================================================================================================ FAILURES ================================================================================================
__________________________________________________________________________________________ test_email_exception __________________________________________________________________________________________

    def test_email_exception():
    	"""test that exception is raised for invalid emails"""
    	with pytest.raises(Exception):
>   		assert check_email_format("[email protected]")
E     Failed: DID NOT RAISE <class 'Exception'>

invalid_test_case.py:15: Failed
========================================== 1 failed in 0.05s ================================================================

Now consider a positive testcase, where we expect the test case to pass i.e., we expect an exception to be raised.

def test_email_exception():
        """test that exception is raised for invalid emails"""
        with pytest.raises(Exception):
                assert check_email_format("bademail.com")

Execution of test case:

pytest valid_test_case.py 
======================================= test session starts ===============================================================
platform darwin -- Python 3.7.0, pytest-5.3.5, py-1.8.1, pluggy-0.13.1
rootdir: /Users/suri/preeti-work/python_ml_samples/src
collected 1 item                                                                                                                                                                                         

valid_test_case.py .                                                                                                                                                                               [100%]

========================================== 1 passed in 0.01s ================================================================





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.