from io import BytesIO import openpyxl import pytest from app.models import Asset, AuditLog from app.seed.seed import seed_database @pytest.fixture(scope="module", autouse=True) def seeded_bulk_import_db(db, tmp_path_factory): upload_dir = tmp_path_factory.mktemp("bulk_import_test_uploads") seed_database(db, upload_dir=upload_dir) return upload_dir def _auth_headers(client, email: str) -> 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']}"} def _make_xlsx_bytes(headers: list[str], rows: list[list[object]]) -> bytes: wb = openpyxl.Workbook() ws = wb.active ws.title = "Assets" ws.append(headers) for r in rows: ws.append(r) buf = BytesIO() wb.save(buf) return buf.getvalue() def test_import_template_download_and_rbac(client): bio_headers = _auth_headers(client, "bio@xyz.demo") admin_headers = _auth_headers(client, "admin@xyz.demo") for email in ("dept@xyz.demo", "coord@xyz.demo", "mgmt@xyz.demo"): h = _auth_headers(client, email) assert client.get("/api/assets/import-template", headers=h).status_code == 403 assert ( client.post( "/api/assets/bulk-import", headers=h, files={"file": ("assets.csv", b"asset_code\n", "text/csv")}, ).status_code == 403 ) res = client.get("/api/assets/import-template", headers=bio_headers) assert res.status_code == 200 assert "spreadsheetml.sheet" in res.headers["content-type"] assert 'filename="asset_import_template.xlsx"' in res.headers["content-disposition"] wb = openpyxl.load_workbook(BytesIO(res.content)) assert wb.sheetnames == ["Assets", "Example", "Master Reference"] assert wb["Example"].cell(row=1, column=1).value == "Example only - this sheet is ignored on import" ws = wb["Assets"] headers = [ws.cell(row=1, column=i).value for i in range(1, 16)] assert headers[:6] == ["asset_code", "serial_no", "name", "category", "department", "location"] assert ws.freeze_panes == "A2" # Admin also allowed assert client.get("/api/assets/import-template", headers=admin_headers).status_code == 200 def test_bulk_import_dry_run_validation_and_commit(client, db): bio_headers = _auth_headers(client, "bio@xyz.demo") # Read a valid sample from template so we match real seeded department/location/category tmpl_res = client.get("/api/assets/import-template", headers=bio_headers) wb_tmpl = openpyxl.load_workbook(BytesIO(tmpl_res.content)) ws_tmpl = wb_tmpl["Example"] headers = [wb_tmpl["Assets"].cell(row=1, column=i).value for i in range(1, 16)] cat_name = ws_tmpl.cell(row=2, column=4).value dept_code = ws_tmpl.cell(row=2, column=5).value loc_name = ws_tmpl.cell(row=2, column=6).value sup_name = ws_tmpl.cell(row=2, column=7).value initial_count = db.query(Asset).count() # Mix: 2 valid rows + 1 invalid row (unknown department) rows = [ [ "BLK-IMP-001", "BLK-SN-001", "Bulk Infusion Pump", cat_name, dept_code, loc_name, sup_name, 95000, "2025-02-01", "2025-02-05", "in_service", "critical", "yes", "no", "Dry run test row 1", ], [ "BLK-IMP-002", "BLK-SN-002", "Bulk Syringe Pump", cat_name, dept_code, loc_name, "", 45000, "15-Feb-2025", "", "in_service", "non_critical", "false", "true", "Dry run test row 2", ], [ "BLK-IMP-BAD", "BLK-SN-BAD", "Invalid Dept Equipment", cat_name, "NO_SUCH_DEPT", loc_name, "", 10000, "", "", "in_service", "non_critical", "false", "false", "", ], ] xlsx_bytes = _make_xlsx_bytes(headers, rows) # 1. dry_run=true validates all 3 without inserting into DB dry_res = client.post( "/api/assets/bulk-import?dry_run=true", headers=bio_headers, files={ "file": ( "bulk_assets.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ) }, ) assert dry_res.status_code == 200, dry_res.text dry_data = dry_res.json() assert dry_data["dry_run"] is True assert dry_data["total_rows"] == 3 assert dry_data["valid_count"] == 2 assert dry_data["error_count"] == 1 assert dry_data["created_count"] == 0 assert dry_data["errors"][0]["row"] == 4 assert db.query(Asset).count() == initial_count # 2. dry_run=false & skip_invalid=false rejects with 400 IMPORT_VALIDATION_ERRORS strict_res = client.post( "/api/assets/bulk-import?dry_run=false&skip_invalid=false", headers=bio_headers, files={ "file": ( "bulk_assets.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ) }, ) assert strict_res.status_code == 400 assert strict_res.json()["code"] == "IMPORT_VALIDATION_ERRORS" assert db.query(Asset).count() == initial_count # 3. dry_run=false & skip_invalid=true imports the 2 valid rows and logs audit entries skip_res = client.post( "/api/assets/bulk-import?dry_run=false&skip_invalid=true", headers=bio_headers, files={ "file": ( "bulk_assets.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ) }, ) assert skip_res.status_code == 200, skip_res.text skip_data = skip_res.json() assert skip_data["created_count"] == 2 assert skip_data["error_count"] == 1 assert db.query(Asset).count() == initial_count + 2 created_asset = db.query(Asset).filter(Asset.asset_code == "BLK-IMP-001").first() assert created_asset is not None audit = ( db.query(AuditLog) .filter( AuditLog.entity_type == "asset", AuditLog.entity_id == created_asset.id, AuditLog.action == "bulk_import", ) .first() ) assert audit is not None # 4. CSV import (all valid) + unsupported extension rejected csv_bytes = ( "asset_code,serial_no,name,category,department,location\n" f"BLK-CSV-003,SN-CSV-003,CSV Patient Monitor,{cat_name},{dept_code},{loc_name}\n" ).encode("utf-8") csv_res = client.post( "/api/assets/bulk-import?dry_run=false", headers=bio_headers, files={"file": ("assets.csv", csv_bytes, "text/csv")}, ) assert csv_res.status_code == 200, csv_res.text assert csv_res.json()["created_count"] == 1 bad_ext = client.post( "/api/assets/bulk-import", headers=bio_headers, files={"file": ("assets.txt", b"hello", "text/plain")}, ) assert bad_ext.status_code == 400 assert bad_ext.json()["code"] == "INVALID_FILE_TYPE"