简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM