2

Currently I am doing Unit Testing in Fastapi using from fastapi.testclient import TestClient

def test_login_api_returns_token(session,client):
    form_data = {
        "username": "mike@gmail.com",
        "password": "mike"
    }
    response = client.post(  
        "/api/login", 
        data=form_data,
        headers={"content-type": "multipart/form-data"}
        # headers={"content-type": "application/x-www-form-urlencoded"}
    )
    result = response.json()
    assert response.status_code == 200

I am supposed to get token as response which I am getting when I run the fastapi application but not able to proceed with Unit Testing with the same.

Example of postman request for the same

enter image description here

How do I make sure form-data is being sent from TestClient?

api/login.py

@router.post("/login")
async def user_login(form_data: OAuth2PasswordRequestForm = Depends(), session: Session = Depends(get_session)):
    user = authenticated_user(form_data.username, form_data.password, session)
    user = user[0]
    if not user:
        raise token_exception()
    token_expires = timedelta(minutes=120)
    token = create_access_token(username=user.username, user_id=user.id, expires_delta=token_expires)
    token_exp = jwt.decode(token, SECRET, algorithms=[ALGORITHM])
    return {
        "status_code": status.HTTP_200_OK,
        "data":{
            "username": user.username,
            "token": token,
            "expiry": token_exp['exp'],
            "user_id": user.id
        }
    }

enter image description here

code_10
  • 155
  • 1
  • 2
  • 10

1 Answers1

1

Try set the header to Content-Type form-data like

def test_login_api_returns_token(session,client):
    form_data = {
        "username": "mike@gmail.com",
        "password": "mike"
    }
    response = client.post(  
        "/api/login", 
        data=form_data,
        headers={ 'Content-Type': 'application/x-www-form-urlencoded'}
    )
    result = response.json()
    assert response.status_code == 200