[Python] Mocking custom exceptions in Python

Discussão em 'Python' iniciado por Stack, Setembro 11, 2024.

  1. Stack

    Stack Membro Participativo

    Most third-party Python libraries throw custom exceptions. Many of these exceptions have their own dependencies and side effects. Consider, for example, the following situation:

    class ThirdPartyException(BaseException):
    def __init__(self):
    print("I do something arcane and expensive upon construction.")
    print("Maybe I have a bunch of arguments that can't be None, too.")

    def state(self) -> bool:
    # In real life, this could be True or False
    return True


    Let's say, moreover, that I absolutely have to handle this exception, and to do it, I need to look at the exception's state. If I want to write tests to examine the behavior when this exception is handled, I must have the ability to create a ThirdPartyException. But I may not even be able to figure out how, let alone how to do it cheaply.

    If this weren't an Exception and I wanted to write tests, I would immediately reach for MagicMock. But I cannot figure out how to use MagicMock with an exception.

    How do I test the error handling cases in the following code, ideally using py.test?

    def error_causing_thing():
    raise ThirdPartyException()

    def handle_error_conditionally():
    try:
    error_causing_thing()
    exception ThirdPartyException as e:
    if state:
    return "Some non-error value"
    else:
    return "A different non-error value"

    Continue reading...

Compartilhe esta Página