Fastapi: [QUESTION] Testing: overwrite Depends(OAuth2)

Created on 8 May 2020  路  2Comments  路  Source: tiangolo/fastapi

Description

Is it possible to overwrite a Depends by an external authentication provider inside a test?

I have this function and would like to overwrite the Depends to allow the test client to call the function without authentication.

@app.post("/")
async def get_data(api_key: str = Depends(OAuth2AuthorizationCodeBearer(token_url))):
    return "authenticated"

Do you know how to use dependency_overrides to allow requests without authentication?

app.dependency_overrides[OAuth2AuthorizationCodeBearer.__call__] = True
client = TestClient(app)
r = client.post("/")

I appreciate any hints :-)

answered question

All 2 comments

You should probably do:

oauth2_code_bearer = OAuth2AuthorizationCodeBearer(token_url)

@app.post("/")
async def get_data(api_key: str = Depends(oauth2_code_bearer)):
    return "authenticated"

and then:

def oauth2_code_bearer_override():
    return "somefaketoken"

app.dependency_overrides[oauth2_code_bearer] = oauth2_code_bearer_override
client = TestClient(app)
r = client.post("/")

Thanks for your answer. :)

Was this page helpful?
0 / 5 - 0 ratings