I have a POST endpoint with fastapi that goes a little like this. This takes in an excel file and turns it into a pandas dataframe.
@router.post(
"/endpoint/upload_excel",
status_code=status.HTTP_200_OK
)
async def upload_excel(user_excel_file: UploadFile = File(...)):
"""
read user Excel file from multipart/form-data into pd dataframe
"""
user_excel_bytes = await user_excel_file.read()
user_excel_bytes_io = io.BytesIO(user_excel_bytes)
user_lineage = pd.read_excel(user_excel_bytes_io)
This function continues to manipulate the pandas dataframe, such as sorting columns, checking for nulls, and checking data types.
How could I test this function with pytest in python? I believe I need to mock the the multipart/form-data (user_excel_file: UploadFile = File(...)). I want to test for the edge cases like catching nulls or having ints where strings should be, but I don't want to create a separate test excel file for each case.
If the input to this function was a pandas dataframe, I could easily mock that! But how can I mock the input excel?
pandasandio.BytesIO, then wrapping it in a FastAPIUploadFilemock. This lets you mock any Excel content dynamically without creating real files. You just build a DataFrame for each edge case and convert it to a mockUploadFile.