Skip to content Skip to sidebar Skip to footer

How To Avoid Decorators While Unit Testing In Python Flask Application

I am new to python and flask. I wanted to create unit tests for an api written. We have used jwt for authentication. To unit test, I don't want the flow to enter @jwt_required deco

Solution 1:

Instead of trying to mock the decorator, mock out the function the decorator is calling.

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)
    ....

Instead of

mock.patch('flask_jwt_extended.jwt_required')

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')

did the trick!


Solution 2:

based on the description here

It should be like this, but not tested.

import mock
def mock_jwt_required(realm):
    return

@mock.patch('flask_jwt.jwt_required', side_effect=mock_jwt_required)
def test_get(jwt_required_fn):
    a_obj = A()
    a_obj.get("address123", 'xyz')

Solution 3:

I used this library called undecorated and its working fine for me. https://stackoverflow.com/a/35418639

https://pypi.org/project/undecorated/

This is clean, however if there is a any easier way without importing libraries please suggest.


Post a Comment for "How To Avoid Decorators While Unit Testing In Python Flask Application"