fix: resolve audit report gaps across bulk imports, auth, scoping, and exports

This commit is contained in:
Atharv1705
2026-11-16 13:03:41 +05:30
parent ee9390a2a0
commit f356442900
25 changed files with 1994 additions and 45 deletions
+238
View File
@@ -0,0 +1,238 @@
from io import BytesIO
import openpyxl
import pytest
from app.models import Asset, CalibrationPlan, CalibrationRecord, Contract, InsurancePolicy, Vendor
from app.seed.seed import seed_database
@pytest.fixture(scope="module", autouse=True)
def seeded_extra_import_db(db, tmp_path_factory):
upload_dir = tmp_path_factory.mktemp("extra_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(sheet_name: str, headers: list[str], rows: list[list[object]]) -> bytes:
wb = openpyxl.Workbook()
ws = wb.active
ws.title = sheet_name
ws.append(headers)
for r in rows:
ws.append(r)
buf = BytesIO()
wb.save(buf)
return buf.getvalue()
def test_contracts_bulk_import_lifecycle(client, db):
admin_headers = _auth_headers(client, "admin@poona.demo")
asset = db.query(Asset).filter(Asset.asset_code.isnot(None)).first()
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
assert asset is not None
assert vendor is not None
headers = [
"asset_code",
"provider_name",
"contract_type",
"start_date",
"end_date",
"cost",
"coverage_details",
"remarks",
]
# 1 valid, 1 invalid (invalid contract_type)
rows = [
[
asset.asset_code,
vendor.name,
"CMC",
"2026-01-01",
"2026-12-31",
85000,
"All parts included",
"Annual contract",
],
[
asset.asset_code,
vendor.name,
"INVALID_TYPE",
"2026-01-01",
"2026-12-31",
50000,
"Test",
"Test remarks",
],
]
xlsx_bytes = _make_xlsx_bytes("Contracts", headers, rows)
# Dry run
res = client.post(
"/api/contracts/bulk-import?dry_run=true",
headers=admin_headers,
files={"file": ("contracts_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
)
assert res.status_code == 200
data = res.json()
assert data["dry_run"] is True
assert data["total_rows"] == 2
assert data["valid_count"] == 1
assert data["error_count"] == 1
assert data["created_count"] == 0
# Fail commit without skip_invalid
res_fail = client.post(
"/api/contracts/bulk-import?dry_run=false&skip_invalid=false",
headers=admin_headers,
files={"file": ("contracts_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
)
assert res_fail.status_code == 400
# Commit with skip_invalid
res_commit = client.post(
"/api/contracts/bulk-import?dry_run=false&skip_invalid=true",
headers=admin_headers,
files={"file": ("contracts_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
)
assert res_commit.status_code == 200
commit_data = res_commit.json()
assert commit_data["created_count"] == 1
created_contract = (
db.query(Contract)
.filter(Contract.asset_id == asset.id, Contract.contract_type == "CMC")
.order_by(Contract.id.desc())
.first()
)
assert created_contract is not None
assert created_contract.provider_id == vendor.id
def test_calibration_bulk_import_lifecycle(client, db):
admin_headers = _auth_headers(client, "admin@poona.demo")
# Find asset without calibration plan
existing_plan_ids = [p.asset_id for p in db.query(CalibrationPlan.asset_id).all()]
asset = db.query(Asset).filter(Asset.id.notin_(existing_plan_ids)).first()
assert asset is not None
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
assert vendor is not None
headers = [
"asset_code",
"frequency_months",
"agency_name",
"scope",
"standards",
"remarks",
]
rows = [
[
asset.asset_code,
12,
vendor.name,
"Accuracy verification",
"ISO 17025",
"Imported plan",
],
]
xlsx_bytes = _make_xlsx_bytes("Calibration Plans", headers, rows)
# Dry run
res = client.post(
"/api/calibration/bulk-import?dry_run=true",
headers=admin_headers,
files={"file": ("cal_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
)
assert res.status_code == 200
data = res.json()
assert data["valid_count"] == 1
assert data["error_count"] == 0
# Commit
res_commit = client.post(
"/api/calibration/bulk-import?dry_run=false",
headers=admin_headers,
files={"file": ("cal_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
)
assert res_commit.status_code == 200
assert res_commit.json()["created_count"] == 1
plan = db.query(CalibrationPlan).filter(CalibrationPlan.asset_id == asset.id).first()
assert plan is not None
assert plan.frequency_months == 12
record = db.query(CalibrationRecord).filter(CalibrationRecord.plan_id == plan.id).first()
assert record is not None
def test_insurance_bulk_import_lifecycle(client, db):
admin_headers = _auth_headers(client, "admin@poona.demo")
asset = db.query(Asset).filter(Asset.asset_code.isnot(None)).first()
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
assert asset is not None
assert vendor is not None
headers = [
"asset_code",
"insurer_name",
"policy_number",
"start_date",
"end_date",
"insured_value",
"premium",
"remarks",
]
rows = [
[
asset.asset_code,
vendor.name,
"POL-TEST-9999",
"2026-04-01",
"2027-03-31",
1200000,
15000,
"Annual equipment insurance",
],
]
xlsx_bytes = _make_xlsx_bytes("Insurance Policies", headers, rows)
# Dry run
res = client.post(
"/api/insurance/bulk-import?dry_run=true",
headers=admin_headers,
files={"file": ("ins_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
)
assert res.status_code == 200
data = res.json()
assert data["valid_count"] == 1
assert data["error_count"] == 0
# Commit
res_commit = client.post(
"/api/insurance/bulk-import?dry_run=false",
headers=admin_headers,
files={"file": ("ins_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
)
assert res_commit.status_code == 200
assert res_commit.json()["created_count"] == 1
pol = db.query(InsurancePolicy).filter(InsurancePolicy.policy_no == "POL-TEST-9999").first()
assert pol is not None
assert pol.coverage_amount == 1200000
assert pol.asset_id == asset.id
+31
View File
@@ -242,3 +242,34 @@ def test_report_exports_xlsx_and_csv(client):
headers=mgmt_headers,
)
assert bad_fmt.status_code == 422
def test_all_eight_reports_export_xlsx_and_csv(client):
"""Verify that all 8 reports export cleanly as both XLSX and CSV without title/slash errors."""
admin_headers = _auth_headers(client, "admin@poona.demo")
for key in ALL_REPORT_KEYS:
# Test XLSX export
xlsx_res = client.get(
f"/api/reports/{key}/export?format=xlsx",
headers=admin_headers,
)
assert xlsx_res.status_code == 200, f"XLSX export failed for {key}: {xlsx_res.text}"
assert "spreadsheetml.sheet" in xlsx_res.headers["content-type"]
assert f'filename="{key}.xlsx"' in xlsx_res.headers["content-disposition"]
wb = openpyxl.load_workbook(BytesIO(xlsx_res.content))
ws = wb.active
assert ws is not None
assert "/" not in ws.title and "\\" not in ws.title
assert len(ws.title) <= 31
# Test CSV export
csv_res = client.get(
f"/api/reports/{key}/export?format=csv",
headers=admin_headers,
)
assert csv_res.status_code == 200, f"CSV export failed for {key}: {csv_res.text}"
assert "text/csv" in csv_res.headers["content-type"]
assert f'filename="{key}.csv"' in csv_res.headers["content-disposition"]