from io import BytesIO import openpyxl import pytest from app.seed.seed import seed_database @pytest.fixture(scope="module", autouse=True) def seeded_task2_db(db, tmp_path_factory): upload_dir = tmp_path_factory.mktemp("task2_test_uploads") seed_database(db, upload_dir=upload_dir) return upload_dir def _auth_headers(client, email: str = "admin@poona.demo") -> dict[str, str]: res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"}) assert res.status_code == 200, res.text return {"Authorization": f"Bearer {res.json()['access_token']}"} @pytest.mark.parametrize( "template_url,import_url,file_field,filename,expected_sheet1", [ ( "/api/assets/import-template", "/api/assets/bulk-import?dry_run=true", "file", "asset_template.xlsx", "Assets", ), ( "/api/contracts/import-template", "/api/contracts/bulk-import?dry_run=true", "file", "contracts_template.xlsx", "Contracts", ), ( "/api/calibration/import-template", "/api/calibration/bulk-import?dry_run=true", "file", "calibration_template.xlsx", "Calibration Plans", ), ( "/api/insurance/import-template", "/api/insurance/bulk-import?dry_run=true", "file", "insurance_template.xlsx", "Insurance Policies", ), ], ) def test_download_template_and_upload_unchanged_dry_run_zero_rows( client, template_url, import_url, file_field, filename, expected_sheet1 ): headers = _auth_headers(client) # 1. Download template dl_res = client.get(template_url, headers=headers) assert dl_res.status_code == 200 content = dl_res.content # 2. Verify sheet structure wb = openpyxl.load_workbook(BytesIO(content)) assert wb.sheetnames == [expected_sheet1, "Example", "Master Reference"] ws1 = wb[expected_sheet1] # First sheet has only header row (max_row == 1) assert ws1.max_row == 1 ws2 = wb["Example"] # Second sheet has disclaimer on row 1 assert ws2.cell(row=1, column=1).value == "Example only - this sheet is ignored on import" # Second sheet has sample row on row 2 assert ws2.cell(row=2, column=1).value is not None # 3. Upload unchanged template with dry_run=true: must return total_rows == 0 up_res = client.post( import_url, headers=headers, files={file_field: (filename, content, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")}, ) assert up_res.status_code == 200, up_res.text data = up_res.json() assert data["total_rows"] == 0 assert data["valid_count"] == 0 assert data["error_count"] == 0 assert data["created_count"] == 0