![](/img/trans.png)
[英]how to avoid decorators while unit testing in python flask application
[英]Avoid or bypass multiple decorators in unit testing with pytest
之前問過類似的問題:
functools.wraps
在裝飾器中創建了一個名為__wrapped__
的魔法方法,它允許訪問包裝的 function。但是,當您有多個裝飾器時,這將返回一個內部裝飾器,而不是原始的 function。
如何避免或繞過多個裝飾器?
要繞過或避免多個裝飾器並訪問最里面的 function,請使用此遞歸方法:
def unwrap(func):
if not hasattr(func, '__wrapped__'):
return func
return unwrap(func.__wrapped__)
在 pytest 中,您可以在 conftest.py 中擁有這個conftest.py
並通過以下方式訪問整個測試:
# conftest.py
import pytest
@pytest.fixture
def unwrap():
def unwrapper(func):
if not hasattr(func, '__wrapped__'):
return func
return unwrapper(func.__wrapped__)
yield unwrapper
# my_unit_test.py
from my_module import decorated_function
def test_my_function(unwrap):
decorated_function_unwrapped = unwrap(decorated_function)
assert decorated_function_unwrapped() == 'something'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.