python 测试时覆盖FastAPI中的JWTBearer Auth依赖

6za6bjd0  于 2023-06-28  发布在  Python
关注(0)|答案(1)|浏览(180)

我在尝试从测试阶段覆盖JWT验证时遇到了麻烦。
当调用API端点或我使用SwaggerUI调用它们时,验证工作正常。
我的所有端点都声明如下:

@router.get("/some-path/{id}", response_model=SomeModel, dependencies=[Depends(JWTBearer())])
async def read_card_basic(*, db: Session = Depends(get_db), id: int):
    # do something

JWTBearer类有一个__call__方法来执行验证:

async def __call__(self, request: Request):
    credentials: HTTPAuthorizationCredentials = await super(JWTBearer, self).__call__(request)
    if credentials:
        if not credentials.scheme == "Bearer":
            raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Invalid authentication scheme.")
        if not self.verify_jwt(credentials.credentials):
            raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Invalid or expired token.")
        return credentials.credentials
    else:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Invalid authorization code.")

我正在使用Pytest,并且已经在www.example.com文件中做了如下依赖项覆盖:

def pytest_configure() -> None:
    """
    Pytest will identify this function automatically and will run it before running any test
    """
    initialize_testing_db()
    initialize_other_testing_db()

    create_data()
    create_other_data()

    app.dependency_overrides[get_db] = get_test_db
    app.dependency_overrides[get_other_db] = get_other_test_db

我尝试按照文档中的示例进行操作,但我找不到删除它的方法,因为我们从外部服务获取令牌,并且在测试期间不需要它。
任何帮助将不胜感激,我可以添加更多的信息,如果需要的话。

b0zn9rqh

b0zn9rqh1#

首先,将auth依赖项作为示例注入。来源
例如,在JWTBearer类之后添加jwt_bearer = JWTBearer()
然后,像这样声明端点:

@router.get("/some-path/{id}", response_model=SomeModel, dependencies=[Depends(jwt_bearer)])
async def read_card_basic(*, db: Session = Depends(get_db), id: int):
    # do something

其次,创建一个类来覆盖你的JWTBearer类的行为:

class OverrideJWTBearer(JWTBearer):
    async def __call__(self, request: Request):
        return True

最后,在conftest.py上,像这样覆盖依赖项:

app.dependency_overrides[jwt_bearer] = OverrideJWTBearer()

你好!

相关问题