[英]flask-jwt-extended: Fake Authorization Header during testing (pytest)
This is the function I wish to test这是我想测试的功能
@jwt_required
def get_all_projects(self):
# implementation not included here
I call the function from a pytest class我从 pytest 类调用该函数
def test_get_all_projects(db_session):
all_projects = ProjectController.get_all_projects()
with the db_session
fixture使用
db_session
固定装置
@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()
This result in the error这导致错误
> 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
I still get the same result when I call create_access_token
in the fixture above当我在上面的夹具中调用
create_access_token
时,我仍然得到相同的结果
db.session = session
session._test_access_token = create_access_token(identity='pytest')
yield session
How can I fake JWT tokens during testing with pytest
?在使用
pytest
测试期间如何伪造 JWT 令牌?
@jwt_required
only works in the context of a Flask request. @jwt_required
仅适用于 Flask 请求的上下文。 You can send in the access token using the flask test client with the headers name option:您可以使用带有标头名称选项的烧瓶测试客户端发送访问令牌:
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
Optionally, you could unwrap the decorated method by using the __wrapped__
property.或者,您可以使用
__wrapped__
属性来解包装饰的方法。 In your case, it would look like:在你的情况下,它看起来像:
method_response = get_all_projects.__wrapped__()
Note that any calls to the flask-jwt-extended helper functions in your endpoint (such as get_jwt_identity()
, current_user
, etc).请注意,对端点中的 flask-jwt-extended 辅助函数的任何调用(例如
get_jwt_identity()
、 current_user
等)。 would not work this way, as they require a flask request context.不会以这种方式工作,因为它们需要一个烧瓶请求上下文。 You could get around this by mocking the flask-jwt-extended functions used inside the function, but that may be harder to maintain as the application grows and changes.
您可以通过模拟函数内部使用的 flask-jwt-extended 函数来解决这个问题,但是随着应用程序的增长和变化,这可能更难维护。
One option for faking JWT tokens during unit testing is to patch jwt_required.在单元测试期间伪造 JWT 令牌的一种选择是修补 jwt_required。 More specifically patch the underlying function
verify_jwt_in_request
.更具体地说,修补底层函数
verify_jwt_in_request
。 This mocks the decorator and removes the need to create authorization tokens for the test.这模拟了装饰器并消除了为测试创建授权令牌的需要。
from unittest.mock import patch
@patch('flask_jwt_extended.view_decorators.verify_jwt_in_request')
def test_get_all_projects(mock_jwt_required):
# ...
Here's what i ended up doing and works for me.这就是我最终所做的并且为我工作。 In conftest.py:
在 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
And then in your TestConfig, set the following flags for flask-jwt-extended:然后在您的 TestConfig 中,为 flask-jwt-extended 设置以下标志:
JWT_HEADER_TYPE = 'Bearer'
JWT_BLACKLIST_ENABLED = False
Old topic, but here's some additional insight about how to test functions with @jwt_required:旧主题,但这里有一些关于如何使用 @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"))
In my case, I was using the @jwt.user_claims_loader
wrapper for admin roles.就我而言,我使用
@jwt.user_claims_loader
包装器作为管理员角色。 I was also using cookies for the production side of things.我还在产品的生产方面使用了 cookie。 In order to take advantage of the user_claims_loader, I created a test like so:
为了利用 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
As you can see, I also reset my JWT_TOKEN_LOCATION
to json
so that it isn't looking for cookies.如您所见,我还将
JWT_TOKEN_LOCATION
重置为json
这样它就不会寻找 cookie。 I created another fixture to create the access token so I could use it across tests我创建了另一个夹具来创建访问令牌,以便我可以在测试中使用它
# 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
}
And I used it in my tests:我在测试中使用了它:
# 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
As an example of what my resource looked like:作为我的资源的示例:
# 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.