flask-jwt-extended:测试期间的伪授权标头(pytest)

时间:2017-10-20 10:02:55

标签: 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

当我在上面的灯具中调用create_access_token

时,我仍然得到相同的结果
db.session = session
session._test_access_token = create_access_token(identity='pytest')

yield session

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

5 个答案:

答案 0 :(得分:5)

@jwt_required仅适用于Flask请求的上下文。您可以使用带有标题名称选项的烧瓶测试客户端发送访问令牌:

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-jwt-extended函数来解决这个问题,但随着应用程序的增长和变化,这可能更难维护。

答案 1 :(得分:2)

这就是我最终要为我工作的事情。在conftest.py中:

@pytest.yield_fixture(scope='function')
def app():
  _app = create_app(TestConfig)
  ctx = _app.test_request_context()
  ctx.push()

  yield _app

  ctx.pop()

@pytest.fixture(scope='function')
def testapp(app):
    """A Webtest app."""
    testapp = TestApp(app)

    with testapp.app.test_request_context():
        access_token = create_access_token(identity=User.query.filter_by(email='test@test.com').first(), expires_delta=False, fresh=True)
    testapp.authorization = ('Bearer', access_token)

    return testapp

然后在您的TestConfig中,为flask-jwt-extended设置以下标志:

JWT_HEADER_TYPE = 'Bearer'
JWT_BLACKLIST_ENABLED = False

答案 2 :(得分:1)

在单元测试期间伪造JWT令牌的一个选项是修补jwt_required。更具体地说,修补基础功能verify_jwt_in_request。这样可以模拟装饰器,并且无需为测试创建授权令牌。

from unittest.mock import patch


@patch('flask_jwt_extended.view_decorators.verify_jwt_in_request')
def test_get_all_projects(mock_jwt_required):
    # ...

答案 3 :(得分:0)

就我而言,我在使用@jwt.user_claims_loader包装器作为管理员角色。我还在产品的生产方面使用cookie。为了利用user_claims_loader,我创建了如下测试:

# conftest.py
from my.app import create_app

@pytest.fixture
def app():
    app = create_app(testing=True)
    app.config['JWT_COOKIE_CSRF_PROTECT'] = False
    app.config['JWT_TOKEN_LOCATION'] = 'json'
    jwt = JWTManager(app)

    add_user_claims_loader(jwt)

    return app

如您所见,我还将JWT_TOKEN_LOCATION重置为json,以便它不查找cookie。我创建了另一个夹具来创建访问令牌,以便可以在测试中使用它

# conftest.py
@pytest.fixture
def admin_json_access_token(app, client):
    access_token = create_access_token({'username': 'testadmin',
                                        'role': 'admin'})
    return {
        'access_token': access_token
    }

我在测试中使用了它:

# test_user.py
def test_get_users(app, client, db, admin_json_access_token):
    rep = client.get('/api/v1/users', json=admin_json_access_token)
    assert rep.status_code == 200

作为我的资源状况的一个示例:

# my/resources/admin/api.py
class Users(Resource):
    @jwt_required
    @admin_required # custom wrapper that checks the claims
    def get(self):
        all_users = User.query.all()
        return all_users, 200

答案 4 :(得分:0)

旧主题,但这是有关如何使用@jwt_required测试功能的其他一些见解:

@pytest.fixture(scope="function", autouse=True)
def no_jwt(monkeypatch):
  """Monkeypatch the JWT verification functions for tests"""
  monkeypatch.setattr("flask_jwt_extended.verify_jwt_in_request", lambda: print("Verify"))
相关问题