简体   繁体   English

如何根据模拟的函数使用Python Mock副作用返回不同的值

[英]How to user Python Mock side effect to return different value based on function being mocked

I have a common function that I want to use as a side effect for two different functions. 我有一个常用功能,希望用作两个不同功能的副作用。 Based on the function being mocked , they should return a different value. 基于被模拟的函数,它们应该返回不同的值。 The code is: 代码是:

def sleep_three(*args, **kwargs):
    logging.info('Sleeping 3 seconds')
    time.sleep(3)

Used as a side effect for two different functions: 用作两种不同功能的副作用:

 self.foo.side_effect = sleep_three
 self.bar.side_effect = sleep_three

For foo, I want a specific return value, whereas for bar I want a different return value. 对于foo,我想要一个特定的返回值,而对于bar,我想要一个不同的返回值。 I know how to obtain different return values based on different arguments being passed in to side_effect function. 我知道如何基于传递给side_effect函数的不同参数来获取不同的返回值。 In this case though both foo and bar are being passed in the same argument, they just need to return different values. 在这种情况下,尽管foo和bar都在同一个参数中传递,但它们只需要返回不同的值。

My options are: 我的选择是:

  1. Write two different functions for side_effect : sleep_three_foo and sleep_three_bar and then match up return values accordingly. 为side_effect编写两个不同的函数:sleep_three_foo和sleep_three_bar,然后相应地匹配返回值。 This goes against DRY principles though and I would like to avoid it. 但是,这违反了DRY原则,我想避免这样做。

  2. My question is : Is there a way within sleep_three to obtain the original function being mocked? 我的问题是:sleep_three中是否有办法获得被嘲笑的原始函数?

Something like 就像是

if original_mocked_function == foo:
    return a
elif original_mocked_function == bar:
    return b

Any pointers appreciated! 任何指针表示赞赏!

Define a function that takes the desired return value of the side-effect function as an argument and returns the appropriate function. 定义一个函数,该函数将副作用函数的期望返回值作为参数并返回适当的函数。

def make_sleeper(rv):
    def _(*args, **kwargs):
        logging.info("Sleeping 3 seconds")
        time.sleep(3)
        return rv
    return _

self.foo.side_effect = make_sleeper(5)
self.bar.side_effect = make_sleeper(9)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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