0

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

3
  • I notice you've tagged the question with "mocking". If you are familiar with Python's mock library, you can mock out a function that is called by your try block and have it raise an exception. Is your try block actually so minimal as to not call any other functions? If so, it also probably will not raise any exceptions either. Commented Dec 10, 2021 at 4:17
  • The try block is exactly as shown here. The thing is the value being checked here (DELETE_FILES_ON_SUCCESS), comes from a config and that value can be invalid causing exceptions, which is what I am trying to test here, if the invalid values causes an exception. Commented Dec 10, 2021 at 4:23
  • 1
    I see. There seems to be a good answer already for how to mock this, but my gut instinct is that this shouldn't need to deal with exceptions. I don't know your full situation, but in general I wouldn't expect that accessing constants could cause exceptions. Is there error handling all over your program whenever constants are needed? Perhaps the config file could be loaded and validated on program startup, or invalid values could be prevented from entering the config file in the first place? Commented Dec 10, 2021 at 5:02

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.