2016-12-18 8 views
0

데코레이터 @auth은 기본적으로 데이터베이스를 검사하여 사용자가 주어진 REST 호출에 액세스 할 수 있는지 확인합니다. 이 호출에 대한 단위 테스트를 작성하고 싶습니다. 나의 초기 아이디어는 단순히 장식자를 아무 것도하지 않는 패스로 넘겨주는 것이었다. (내 초기 아이디어는 실패 했으므로 항상 기능을 수행 할 수 있도록 @auth의 일부 기능을 monkeypatch 할 수 있습니다. 그러나 장식자를 완전히 무시할 수 있다면 여전히 궁금합니다.)단위 테스트를위한 데코레이터 생략하기

나는 달성하기를 희망합니다.

example.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 

test_example.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 

이러한 목표를 달성하기 위해 몇 가지 정직 방법이 있나요?

def raw_add... 

add = sample_decorator(raw_add) 

assert example.raw_add... 
+0

의 라인을 따라 뭔가가, 당신이 그렇게 할 시간에 의해 장식 패치를 너무 늦었어요. 그러나 파이썬 3.2+를 사용하고 꾸미기가'functools.wraps'를 사용한다면 래핑 된 버전에 접근 할 수있을 것입니다 : http://stackoverflow.com/a/25909794/3001761 – jonrsharpe

+0

참조 [또한 패치 할 수 있습니까? 파이썬 데코레이터 함수를 래핑하기 전에?] (http://stackoverflow.com/questions/7667567/can-i-patch-a-python-decorator-before-it-wraps-a-function) –

답변

1

데코레이터은, 랩 된 기능에 대한 액세스 권한을 부여 포장 기능에 대한 속성을 설정할 수 있습니다

+0

데코레이터를 수정하지 않고 이것이 가능하다면 좋겠지 만 여전히 가장 직접적인 접근법처럼 보입니다. – Shatnerz

0

는 그냥 정의가 별도로 보관.

모듈이로드 될 때 함수를 래핑

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

@wrap_foo 
def foo(): 
pass 

# Wrapped 
foo() 

# Unwrapped 
foo.__wrapped_fn() 
+1

이것은 너무 많은 – Shatnerz