[英]How can i mock decorator with pytest
我看到使用 pytest 模擬裝飾器的許多變體,但沒有一個對我有幫助。 我正在為我的 celery 應用程序編寫單元測試。 還有一項任務 function 有裝飾器:
def update_state(state):
def decorator(func):
@wraps(func)
def wrapper(*args, task_id=None, **kwargs):
print(f"something with {kwargs} and {task_id}")
result = func(*args, **kwargs)
if not result:
print(f"something was bad with {kwargs} and {task_id}")
else:
print(f"something was successfully updated with {kwargs} and {task_id}")
return wrapper
return decorator
我的任務看起來像:
@celery.task
@update_state(Some state)
def make_some_task(a, b, c):
with context_session() as session:
"""Making something with a,b,c"""
session.add_all()
session.commit()
return a, b, c
最后我的測試:
def test_change_statuses(self,mocker: MockFixture):
mocker.patch("utils.utils.update_state", return_value=True) # This rout to the decorator
mocker.patch.object(Session, 'add_all')
mocker.patch.object(Session, 'commit')
result = change_status.apply(
args=(a, b, c).get()
assert isinstance(result, tuple)
assert isinstance(result[0], int)
沒有裝飾器 'update_state' 測試工作正常。 但是使用裝飾器我得到了結果=無。 我應該怎么辦? 我真的不知道該怎么辦
你不應該在裝飾器中返回結果嗎?
def update_state(state):
def decorator(func):
@wraps(func)
def wrapper(*args, task_id=None, **kwargs):
print(f"something with {kwargs} and {task_id}")
result = func(*args, **kwargs)
if not result:
print(f"something was bad with {kwargs} and {task_id}")
else:
print(f"something was successfully updated with {kwargs} and {task_id}")
return result # <--------------- why you don't return the result?
return wrapper
return decorator
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.