简体   繁体   English

我如何用 pytest 模拟装饰器

[英]How can i mock decorator with pytest

I see many variant to mock decorator with pytest, but none helps me.我看到使用 pytest 模拟装饰器的许多变体,但没有一个对我有帮助。 I'm writing unittest for my celery app.我正在为我的 celery 应用程序编写单元测试。 And one task function have decorator:还有一项任务 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

And my task looks like:我的任务看起来像:

@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

Finally my test:最后我的测试:

    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)

Without decorator 'update_state' test work fine.没有装饰器 'update_state' 测试工作正常。 But with decorator I got result=None.但是使用装饰器我得到了结果=无。 What should I do?我应该怎么办? I really do not know what to do我真的不知道该怎么办

Shouldn't you return the result in the decorator?你不应该在装饰器中返回结果吗?


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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM