Search code examples
pythonunit-testingexceptionmockingassert

Unit Test exception block of simple python function


I am trying to test the exception block of a simple python function as follows

function_list.py

def option_check():
"""
Function to pick and return an option
"""
try:
    # DELETE_FILES_ON_SUCCESS is a config value from constants class. Valid values True/False (boolean)
    flag = Constants.DELETE_FILES_ON_SUCCESS
    if flag:
        return "remove_source_file"
    else:
        return "keep_source_file"

except Exception as error:
    error_message = F"task option_check failed with below error {str(error)}"
    raise Exception(f"Error occured: {error}") from error

How do I force and exception to unit test the exception block? Please note that what I have here in exception block is a simplified version of what I actually have. What I am looking for is a way to force an exception using unit test to test the exception scenarios. Python version is 3.6


Solution

  • You could patch the Constants class and delete the attribute you access from the mock.

    from unittest import mock
    
    # replace __main__ with the package Constants is from
    with mock.patch("__main__.Constants") as mock_constants:
        del mock_constants.DELETE_FILES_ON_SUCCESS
        option_check()
    

    When option_check() tries to access Constants.DELETE_FILES_ON_SUCCESS, it will raise an AttributeError, allowing you to reach the except block.