且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在python flask应用程序中进行单元测试时避免装饰器

更新时间:2023-10-21 22:38:52

不要模拟装饰器,而是模拟装饰器正在调用的函数.

我在使用flask_jwt_extended遇到了类似的障碍,我想模拟出 jwt_required 装饰器.

I ran into a similar obstacle using flask_jwt_extended where I wanted to mock out the jwt_required decorator.

@jwt_required
def post(payload)
    ....

代替

mock.patch('flask_jwt_extended.jwt_required')

我查看了 jwt_required 装饰器正在调用的函数(在本例中为 flask_jwt_extended.view_decorators verify_jwt_in_request ).因此,

I looked at the function the jwt_required decorator was calling (which in this case was verify_jwt_in_request from flask_jwt_extended.view_decorators). So,

mock.patch('flask_jwt_extended.view_decorators.verify_jwt_in_request')

成功了!