检查是否调用了函数而不更改其行为

时间:2017-08-02 12:03:10

标签: python python-3.x

如何测试调用python函数而不改变其行为

有许多相关的帖子,但我找不到其中一个涵盖了所有内容:

基本上,我只需要监视函数以了解它是否被调用。

例如,以下代码段具有极其令人惊讶的行为

from unittest.mock import patch

def func(a,b):
    print('was called')
    return a * b

with patch('test.func') as patched_function:
    print(func(4,5))

print(patched_function.called)

输出:

<MagicMock name='func()' id='1721737249456'>
True
was called
20
False

虽然我只是期待

was called
20
True

1 个答案:

答案 0 :(得分:1)

你应该像这样为函数创建一个装饰器:

class CheckCall(object):
    called = False

    def __init__(self, func):
        self.func = func

    def __call__(self *args, **kwargs):
        self.called = True
        return self.func(*args, **kwargs)

然后你可以像这样应用你的装饰

with patch('test.func') as patched_function:
    patched_function = CheckCall(patched_function)
    print(patched_function.called) # Prints False
    patched_function(...)
    print(patched_function.called) # Prints True