如何在python flask应用程序中进行单元测试时避免装饰器 [英] how to avoid decorators while unit testing in python flask application

查看:73
本文介绍了如何在python flask应用程序中进行单元测试时避免装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python和flask的新手.我想为编写的api创建单元测试.我们已经使用 jwt 进行身份验证.

I am new to python and flask. I wanted to create unit tests for an api written. We have used jwt for authentication.

要进行单元测试,我不希望流程输入 @jwt_required 装饰器.除此之外,我还为该方法链接了其他一些装饰器.

To unit test, I don't want the flow to enter @jwt_required decorator. In addition to that I have chained a few other decorators for that method.

class A():

   @jwt_required()
   @mandatory_fields_check
   @unlock_and_lock()
   def get(self, address, name): 
      ..
      ..
      ..
       return jsonify(
            {"payload": data,
             "message": "data received successfully"}), 200

我要编写的单元测试

def test_get():
   a_obj = A()
   a_obj.get("address123", 'xyz')

当我使用py.test在测试之上运行时,出现运行时错误

When I run above test using py.test, I am getting Runtime error

    def _find_app():
            top = _app_ctx_stack.top
            if top is None:
               raise RuntimeError(_app_ctx_err_msg)
     RuntimeError: Working outside of application context.
E
E           This typically means that you attempted to use functionality that needed
E           to interface with the current application object in some way. To solve
E           this, set up an application context with app.app_context().  See the
E           documentation for more information.

以下是我的目标:

  1. 我不希望流程进入装饰器逻辑

  1. I don't want flow to enter decorators logic

Jwt装饰器正在请求上下文.但是,我的目的是对该方法作为没有任何烧瓶功能的常规类方法进行单元测试.

Jwt decorator is asking for context. However my intention is to unit test this method as a normal class method without any flask features.

如何模拟在被测方法内部创建的对象?

How can I mock objects created inside the method under test?

推荐答案

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

我在使用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')

成功了!

这篇关于如何在python flask应用程序中进行单元测试时避免装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆