I'm using the code from this tutorial for authentication https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt/
My endpoint is:
@router.get("/me", response_model=WaiterBase)
async def get_logged_in_waiter(current_user: Waiter = Depends(get_current_user)):
"""Get current logged in user."""
return current_user
I'm writing a tests for protected FastAPI endpoints in this way:
def test_get_me(self, test_client, access_token):
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {access_token}",
}
response = test_client.get("/waiters/me", headers=headers)
assert response.status_code == 200
Fixtures are:
@pytest.fixture(scope="module")
def test_client():
"""Test client initiation for all tests."""
client = TestClient(app)
yield client
@pytest.fixture(scope="function")
def access_token():
"""Access token."""
token = utils.create_access_token(
data={"sub": "string"}, expires_delta=timedelta(minutes=30)
)
return token
But this test gives me an assertion error:
E assert 401 == 200
E where 401 = <Response [401 Unauthorized]>.status_code
How do I test it?
CodePudding user response:
You should ask for the credentials of that given API. You cannot communicate with an API which is protected by default. If the given API offers public endpoints, then you should be good to go. Anyhow, you already tested your code and it works correctly. You are trying to get data from this particular API and it returns 401 - Unauthorized due to lacking credentials. Everything works as expecte
CodePudding user response:
You should ask for the credentials of that given API. You cannot communicate with an API which is protected by default. If the given API offers public endpoints, then you should be good to go. Anyhow, you already tested your code and it works correctly. You are trying to get data from this particular API and it returns 401 - Unauthorized due to lacking credentials. Everything works as expected.