我可以在Python装饰器包装函数之前对其进行修补吗?

2024-06-16 15:04:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有decorator的函数,我正在PythonMock库的帮助下尝试测试它。我想使用mock.patch将真正的decorator替换为只调用函数的mock'bypass'decorator。我不知道的是如何在真正的装饰器包装函数之前应用补丁。我在patch目标上尝试了一些不同的变体,并重新排序了patch和import语句,但是没有成功。有什么想法吗?


Tags: 函数import目标排序装饰decorator变体语句
3条回答

Decorators在函数定义时应用。对于大多数函数,这是在加载模块时进行的。(在其他函数中定义的函数在每次调用封闭函数时都会应用decorator。)

所以,如果你想给装饰工打补丁,你需要做的是:

  1. 导入包含它的模块
  2. 定义mock decorator函数
  3. 设置例如module.decorator = mymockdecorator
  4. 导入使用decorator的模块,或在自己的模块中使用它

如果包含decorator的模块也包含使用它的函数,那么当您看到它们时,它们已经被修饰了,您可能是S.O.L

编辑以反映对Python的更改,因为我最初编写了这篇文章:如果decorator使用functools.wraps(),并且Python的版本足够新,那么您可以使用__wrapped__属性挖掘原始函数并重新装饰它,但这并不能保证,而且您要替换的decorator也可能不是应用的唯一decorator。

需要注意的是,这里的几个答案将为整个测试会话而不是单个测试实例修补decorator;这可能是不可取的。下面是如何修补只在单个测试中持续存在的decorator。

我们的单位将与不受欢迎的装修商进行测试:

# app/uut.py

from app.decorators import func_decor

@func_decor
def unit_to_be_tested():
    # Do stuff
    pass

来自decorators模块:

# app/decorators.py

def func_decor(func):
    def inner(*args, **kwargs):
        print "Do stuff we don't want in our test"
        return func(*args, **kwargs)
    return inner

在测试运行期间收集测试时,不需要的decorator已经应用到了被测单元(因为这发生在导入时)。为了消除这个问题,我们需要手动替换decorator模块中的decorator,然后重新导入包含UUT的模块。

我们的测试模块:

#  test_uut.py

from unittest import TestCase
from app import uut  # Module with our thing to test
from app import decorators  # Module with the decorator we need to replace
import imp  # Library to help us reload our UUT module
from mock import patch


class TestUUT(TestCase):
    def setUp(self):
        # Do cleanup first so it is ready if an exception is raised
        def kill_patches():  # Create a cleanup callback that undoes our patches
            patch.stopall()  # Stops all patches started with start()
            imp.reload(uut)  # Reload our UUT module which restores the original decorator
        self.addCleanup(kill_patches)  # We want to make sure this is run so we do this in addCleanup instead of tearDown

        # Now patch the decorator where the decorator is being imported from
        patch('app.decorators.func_decor', lambda x: x).start()  # The lambda makes our decorator into a pass-thru. Also, don't forget to call start()          
        # HINT: if you're patching a decor with params use something like:
        # lambda *x, **y: lambda f: f
        imp.reload(uut)  # Reloads the uut.py module which applies our patched decorator

清理回调kill_patches,恢复原始的decorator并将其重新应用到我们正在测试的单元。这样,我们的补丁只在一个测试中持续运行,而不是整个会话——这正是任何其他补丁的行为方式。此外,由于清理调用patch.stopall(),我们可以在setUp()中启动所需的任何其他修补程序,它们将在一个位置全部清理。

关于这个方法,重要的是要了解重新加载将如何影响事物。如果一个模块花费的时间太长,或者有在导入时运行的逻辑,您可能只需要耸耸肩并将decorator作为单元的一部分进行测试。:(希望你的代码写得更好。正确的?

如果不关心补丁是否应用于整个测试会话,最简单的方法是在测试文件的顶部:

# test_uut.py

from mock import patch
patch('app.decorators.func_decor', lambda x: x).start()  # MUST BE BEFORE THE UUT GETS IMPORTED ANYWHERE!

from app import uut

确保用decorator而不是UUT的本地作用域修补文件,并在用decorator导入单元之前启动修补程序。

有趣的是,即使修补程序停止了,所有已经导入的文件仍然会将修补程序应用到decorator,这与我们开始的情况相反。请注意,此方法将修补测试运行中随后导入的任何其他文件—即使它们自己没有声明修补程序。

当我第一次遇到这个问题时,我常常绞尽脑汁好几个小时。我找到了一个更简单的方法来处理这个问题。

这将完全绕过decorator,就像目标一开始甚至没有被装饰一样。

这个被分成两部分。我建议读下面的文章。

http://alexmarandon.com/articles/python_mock_gotchas/

我经常碰到两个问题:

1.)在导入函数/模块之前模拟Decorator。

装饰器和函数是在加载模块时定义的。 如果在导入之前不模拟,它将忽略模拟。加载后,您必须执行一个奇怪的mock.patch.object,这会更加令人沮丧。

2)确保您模拟的是到装饰器的正确路径。

记住,您模拟的decorator的补丁是基于模块如何加载decorator的,而不是测试如何加载decorator的。这就是为什么我建议总是使用完整的导入路径。这使得测试变得更加容易。

步骤:

1.)模拟函数:

from functools import wraps

def mock_decorator(*args, **kwargs):
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            return f(*args, **kwargs)
        return decorated_function
    return decorator

2)嘲笑装修师:

2a.)内部通道。

with mock.patch('path.to.my.decorator', mock_decorator):
     from mymodule import myfunction

2b.)文件顶部的修补程序,或在TestCase.setUp中

mock.patch('path.to.my.decorator', mock_decorator).start()

这两种方法都允许您在测试用例或其方法/测试用例中随时导入函数。

from mymodule import myfunction

2.)使用单独的函数作为mock.patch的副作用。

现在您可以为每个要模拟的装饰器使用mock_decorator。你将不得不分别嘲笑每一个装饰,所以小心那些你错过的。

相关问题 更多 >