Use mock in python to return instead of raising an exception?

This is what I am planning to do:

def foo(flag):
    """
    other irrelevant code
    """
    if flag:
        import random
        return random.random()
    """
    other irrelevant code
    """
    raise Exception()

      

I know it mock

can be used to change the behavior of a class or function, but not sure how it can be used to return instead of raising an exception.

I am wondering if there is a way I mock

can change this raise

to return something without affecting other code

+3


source to share


1 answer


I find the argument wraps

useful for this kind of situations. Here I am creating a generic function capture

that will loop through any return value, but turn the exceptions into a return value. Then I use mock.patch

with an argument wraps

. I use functools.partial

to let the function capture

know what we are wrapping. Untested, but that should give the main idea.



def capture(fn, *args, **kwargs):
    try: return fn(*args, **kwargs)
    except Exception: return whatever_you_like

importe module, functools
with mock.patch('module.foo', wraps = functools.partial(capture, module.foo)):
    do stuff

      

0


source







All Articles