python - flask-jwt-extended:测试期间的假授权 header (pytest)

标签 python flask pytest flask-jwt flask-jwt-extended

这是我要测试的功能

@jwt_required
    def get_all_projects(self):
        # implementation not included here

我从 pytest 类调用该函数

def test_get_all_projects(db_session):
    all_projects = ProjectController.get_all_projects()

使用 db_session fixture

@pytest.fixture(scope='function')
def db_session(db, request):
    """Creates a new database session for a test."""
    engine = create_engine(
                            DefaultConfig.SQLALCHEMY_DATABASE_URI,
                            connect_args={"options": "-c timezone=utc"})
    DbSession = sessionmaker(bind=engine)
    session = DbSession()
    connection = engine.connect()
    transaction = connection.begin()
    options = dict(bind=connection, binds={})
    session = db.create_scoped_session(options=options)
    db.session = session

    yield session

    transaction.rollback()
    connection.close()
    session.remove()

这导致了错误

>           raise NoAuthorizationError("Missing {} Header".format(header_name))
E           flask_jwt_extended.exceptions.NoAuthorizationError: Missing Authorization Header

../../.virtualenvs/my-app/lib/python3.6/site-packages/flask_jwt_extended/view_decorators.py:132: NoAuthorizationError

手动调用create_access_token

当我在上面的 fixture 中调用 create_access_token 时,我仍然得到相同的结果

db.session = session
session._test_access_token = create_access_token(identity='pytest')

yield session

如何在使用 pytest 进行测试时伪造 JWT token ?

最佳答案

@jwt_required 仅适用于 Flask 请求的上下文。您可以使用带有 header 名称选项的 flask 测试客户端发送访问 token :

def test_foo():
    test_client = app.test_client()
    access_token = create_access_token('testuser')
    headers = {
        'Authorization': 'Bearer {}'.format(access_token)
    }
    response = test_client.get('/foo', headers=headers)
    # Rest of test code here

您可以选择使用 __wrapped__ 属性解包装饰方法。在您的情况下,它看起来像:

method_response = get_all_projects.__wrapped__()

请注意,在您的端点中对 flask-jwt-extended 辅助函数的任何调用(例如 get_jwt_identity()current_user 等)。不会以这种方式工作,因为它们需要 flask 请求上下文。您可以通过模拟函数内部使用的 flask-jwt-extended 函数来解决这个问题,但随着应用程序的增长和变化,这可能更难维护。

关于python - flask-jwt-extended:测试期间的假授权 header (pytest),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46846762/

相关文章:

python - 在 Django >= 1.5 中引用用户模型的最佳方式

python - 简单图像反卷积问题

python - assert _backend in {'theano' , 'tensorflow' } AssertionError

python - Flask、MySQL 和 SQLAlchemy 查询 ID 错误

python - Pytest 在哪里存储预期数据

python - 为什么在 pytest-django 中使用 ThreadPoolExecutor 时会得到空的 django 查询集?

python - 对于给定的精度,float32 将给出与 float64 相同结果的最大值是多少?

python-3.x - 带单选按钮的 flask handle 形式

css - 如何使 SCSS 中的字体 URL 与不同的 Flask 应用程序根目录一起使用

python - 如何为keras源代码运行pytest