绕过装饰器进行单元测试

Sha*_*erz 0 python monkeypatching pytest

我有一个装饰器@auth,它基本上检查数据库以确保用户可以访问给定的 REST 调用。我想为这些调用编写一些单元测试。我最初的想法是简单地将装饰器修补成一个什么都不做的通道。(我最初的想法失败了,所以我可能只是在里面修补一些函数,@auth以便它总是通过,但我仍然很好奇是否可以完全绕过装饰器)

我拼凑了一个我希望完成的快速样本。

例子.py

# example.py
from __future__ import print_function

def sample_decorator(func):
    def decorated(*args, **kwargs):
        print("Start Calculation")
        ans = func(*args, **kwargs) + 3
        print(ans)
        print("Finished")
        return ans
    return decorated

@sample_decorator
def add(a, b):
    return a + b
Run Code Online (Sandbox Code Playgroud)

测试示例.py

# test_example.py
from __future__ import print_function
import pytest

import example

def test_add_with_decorator():
    assert example.add(1, 1) == 5

def testadd_with_monkeypatch_out_decorator(monkeypatch):
    monkeypatch.setattr(example, 'sample_decorator', lambda func: func)
    assert example.add(1, 1) == 2  # this fails, but is the behaviour I want
Run Code Online (Sandbox Code Playgroud)

有没有一些直接的方法来实现这一点?

use*_*968 7

装饰器可以在包装函数上设置一个属性,以提供对包装函数的访问。

沿线的东西

def wrap_foo(func):
 def decorated(*args, **kwargs):
  func(*args, **kwargs)
 decorated.__wrapped__ = func
 return decorated

@wrap_foo
def foo():
 pass

# Wrapped
foo()

# Unwrapped
foo.__wrapped__()
Run Code Online (Sandbox Code Playgroud)