""" Run pytest from terminal in the project directory: pytest -v . These tests cover the full request-to-response cycle—including file parsing, data aggregation, console printing, and error handling using FastAPI TestClient. This script tests the FastAPI router, UploadFile handling, business logic, and console output together as one integrated pipeline. """ import io import pytest from fastapi.testclient import TestClient from main import app client = TestClient(app) def test_upload_valid_csv_and_print_summary(capsys): # Create an in-memory CSV file csv_content = ( "category,amount\n" "Electronics,150.00\n" "Books,25.50\n" "Electronics,50.00\n" ) csv_file = io.BytesIO(csv_content.encode("utf-8")) # Send POST request with the simulated file upload response = client.post( "/upload-csv/", files={"file": ("sales_report.csv", csv_file, "text/csv")}, ) # Verify HTTP response and processed JSON payload assert response.status_code == 200 data = response.json() assert data["filename"] == "sales_report.csv" assert data["rows_processed"] == 3 assert data["summary"] == {"Electronics": 200.0, "Books": 25.5} # Capture stdout and verify the printed tabulated summary captured = capsys.readouterr() assert "Category" in captured.out assert "Total Sales" in captured.out assert "Electronics" in captured.out assert "$200.00" in captured.out assert "Books" in captured.out assert "$25.50" in captured.out def test_upload_invalid_file_extension(): txt_file = io.BytesIO(b"plain text content") response = client.post( "/upload-csv/", files={"file": ("notes.txt", txt_file, "text/plain")}, ) assert response.status_code == 400 assert response.json()["detail"] == "Only CSV files are allowed." def test_upload_malformed_csv_columns(): bad_csv = io.BytesIO(b"wrong_header,price\nElectronics,100\n") response = client.post( "/upload-csv/", files={"file": ("bad_data.csv", bad_csv, "text/csv")}, ) assert response.status_code == 422 assert "Invalid CSV format" in response.json()["detail"]