5

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": "[email protected]", "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

2
  • What headers are set in your postman request? Commented Jan 7, 2023 at 18:01
  • I had missed adding login route in fixture, hence was getting 404 not found in response. Commented Jan 9, 2023 at 10:49

1 Answer 1

3

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

def test_login_api_returns_token(session,client): form_data = { "username": "[email protected]", "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 
Sign up to request clarification or add additional context in comments.

6 Comments

Getting {'detail': 'Not Found'} from result.
Can you add your endpoint code?
@code_10 I just updated it to use json= instead of data= can you try that?
Try setting headers to { 'Content-Type': 'application/x-www-form-urlencoded'}
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.