from datetime import date, timedelta import io from pathlib import Path from PIL import Image import pytest from app.core.config import settings from app.models import Asset, AuditLog, Category, Complaint, Department, Location from app.seed.seed import _make_minimal_pdf, seed_database from app.services.calculations import alert_state, compute_schedule_status, coverage_status @pytest.fixture(scope="module", autouse=True) def seeded_assets_db(db, tmp_path_factory): upload_dir = tmp_path_factory.mktemp("asset_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_png_bytes() -> bytes: buf = io.BytesIO() Image.new("RGB", (32, 32), color=(10, 120, 200)).save(buf, format="PNG") return buf.getvalue() def _make_jpeg_bytes() -> bytes: buf = io.BytesIO() Image.new("RGB", (32, 32), color=(200, 50, 50)).save(buf, format="JPEG") return buf.getvalue() def test_alert_state_and_coverage_status(): today = date(2026, 5, 1) assert alert_state(None, today, lead_days=30, red_days=7) == "ok" assert alert_state(today - timedelta(days=1), today, 30, 7) == "red" assert alert_state(today, today, 30, 7) == "red" assert alert_state(today + timedelta(days=7), today, 30, 7) == "red" assert alert_state(today + timedelta(days=8), today, 30, 7) == "yellow" assert alert_state(today + timedelta(days=30), today, 30, 7) == "yellow" assert alert_state(today + timedelta(days=31), today, 30, 7) == "ok" assert coverage_status(None, None, today, 30, 7) == ("none", "none") assert coverage_status(today - timedelta(days=100), today - timedelta(days=1), today, 30, 7) == ("expired", "red") assert coverage_status(today - timedelta(days=100), today + timedelta(days=5), today, 30, 7) == ("expiring", "red") assert coverage_status(today - timedelta(days=100), today + timedelta(days=20), today, 30, 7) == ("expiring", "yellow") assert coverage_status(today - timedelta(days=100), today + timedelta(days=45), today, 30, 7) == ("active", "ok") assert compute_schedule_status(today - timedelta(days=1), "completed", today, 15, 7) == ("completed", "ok") assert compute_schedule_status(today - timedelta(days=1), None, today, 15, 7) == ("overdue", "red") assert compute_schedule_status(today + timedelta(days=10), None, today, 15, 7) == ("due", "yellow") assert compute_schedule_status(today + timedelta(days=30), None, today, 15, 7) == ("upcoming", "ok") def test_asset_crud_and_duplicate_code(client, db): bio_headers = _auth_headers(client, "bio@xyz.demo") dept_headers = _auth_headers(client, "dept@xyz.demo") icu = db.query(Department).filter(Department.code == "ICU").first() loc = db.query(Location).filter(Location.department_id == icu.id).first() cat = db.query(Category).first() # department_user cannot create assets forbidden_create = client.post( "/api/assets", headers=dept_headers, json={ "asset_code": "PHRC-ICU-9998", "serial_no": "SN-9998", "name": "Unauthorized Asset", "category_id": cat.id, "department_id": icu.id, "location_id": loc.id, }, ) assert forbidden_create.status_code == 403 # biomedical creates asset create_res = client.post( "/api/assets", headers=bio_headers, json={ "asset_code": "PHRC-ICU-9999", "serial_no": "SN-TEST-9999", "name": "Test Cardiac Monitor", "category_id": cat.id, "department_id": icu.id, "location_id": loc.id, "purchase_value": 250000.0, "status": "in_service", "criticality": "critical", "requires_calibration": True, "insurance_applicable": True, "remarks": "Phase 2 test asset", }, ) assert create_res.status_code == 201, create_res.text created = create_res.json() assert created["asset_code"] == "PHRC-ICU-9999" assert created["department_name"] == icu.name # Duplicate asset_code -> 409 DUPLICATE_ASSET_CODE dup_res = client.post( "/api/assets", headers=bio_headers, json={ "asset_code": "PHRC-ICU-9999", "serial_no": "SN-DUP", "name": "Duplicate Asset", "category_id": cat.id, "department_id": icu.id, "location_id": loc.id, }, ) assert dup_res.status_code == 409 assert dup_res.json()["code"] == "DUPLICATE_ASSET_CODE" # Audit log written on create audit = ( db.query(AuditLog) .filter(AuditLog.entity_type == "asset", AuditLog.entity_id == created["id"], AuditLog.action == "create") .first() ) assert audit is not None # Overview returns structured data ov_res = client.get(f"/api/assets/{created['id']}/overview", headers=bio_headers) assert ov_res.status_code == 200 ov = ov_res.json() assert ov["asset"]["id"] == created["id"] assert "warranties" in ov assert "contracts" in ov assert "attachments" in ov def test_department_user_scoping_on_assets(client, db): dept_headers = _auth_headers(client, "dept@xyz.demo") icu = db.query(Department).filter(Department.code == "ICU").first() ot = db.query(Department).filter(Department.code == "OT").first() other_asset = db.query(Asset).filter(Asset.department_id == ot.id).first() assert other_asset is not None # List returns only ICU assets even if another department_id is requested list_res = client.get(f"/api/assets?department_id={ot.id}&page_size=200", headers=dept_headers) assert list_res.status_code == 200 items = list_res.json()["items"] assert len(items) > 0 assert all(item["department_id"] == icu.id for item in items) # Lookup returns only ICU assets lookup_res = client.get(f"/api/assets/lookup?department_id={ot.id}", headers=dept_headers) assert lookup_res.status_code == 200 lookup_items = lookup_res.json()["items"] assert all(item["department_id"] == icu.id for item in lookup_items) # Direct access to another department's asset & overview -> 403 assert client.get(f"/api/assets/{other_asset.id}", headers=dept_headers).status_code == 403 assert client.get(f"/api/assets/{other_asset.id}/overview", headers=dept_headers).status_code == 403 def test_coordinator_field_level_patch_restrictions(client, db): coord_headers = _auth_headers(client, "coord@xyz.demo") asset = db.query(Asset).first() ok_patch = client.patch( f"/api/assets/{asset.id}", headers=coord_headers, json={"insurance_applicable": not asset.insurance_applicable, "remarks": "Updated by coordinator"}, ) assert ok_patch.status_code == 200 assert ok_patch.json()["remarks"] == "Updated by coordinator" bad_name = client.patch( f"/api/assets/{asset.id}", headers=coord_headers, json={"name": "Unauthorized Rename"}, ) assert bad_name.status_code == 403 assert bad_name.json()["code"] == "FORBIDDEN" bad_status = client.patch( f"/api/assets/{asset.id}", headers=coord_headers, json={"status": "condemned"}, ) assert bad_status.status_code == 403 assert bad_status.json()["code"] == "FORBIDDEN" def test_attachments_upload_download_delete_and_security(client, db, tmp_path, monkeypatch): monkeypatch.setattr(settings, "UPLOAD_DIR", str(tmp_path)) bio_headers = _auth_headers(client, "bio@xyz.demo") dept_headers = _auth_headers(client, "dept@xyz.demo") mgmt_headers = _auth_headers(client, "mgmt@xyz.demo") icu = db.query(Department).filter(Department.code == "ICU").first() ot = db.query(Department).filter(Department.code == "OT").first() icu_asset = db.query(Asset).filter(Asset.department_id == icu.id).first() ot_asset = db.query(Asset).filter(Asset.department_id == ot.id).first() icu_complaint = ( db.query(Complaint) .join(Asset, Complaint.asset_id == Asset.id) .filter(Asset.department_id == icu.id) .first() ) assert icu_complaint is not None # 1. Valid PNG upload & download exact bytes png_bytes = _make_png_bytes() up_png = client.post( "/api/attachments", headers=bio_headers, data={"entity_type": "asset", "entity_id": str(icu_asset.id)}, files={"file": ("panel.png", png_bytes, "image/png")}, ) assert up_png.status_code == 201, up_png.text att_id = up_png.json()["id"] assert up_png.json()["mime_type"] == "image/png" dl_res = client.get(f"/api/attachments/{att_id}/download", headers=bio_headers) assert dl_res.status_code == 200 assert dl_res.content == png_bytes # 2. Valid JPG and PDF uploads jpg_bytes = _make_jpeg_bytes() up_jpg = client.post( "/api/attachments", headers=bio_headers, data={"entity_type": "asset", "entity_id": str(icu_asset.id)}, files={"file": ("photo.jpg", jpg_bytes, "image/jpeg")}, ) assert up_jpg.status_code == 201 pdf_bytes = _make_minimal_pdf("Asset Service Manual") up_pdf = client.post( "/api/attachments", headers=bio_headers, data={"entity_type": "asset", "entity_id": str(icu_asset.id)}, files={"file": ("manual.pdf", pdf_bytes, "application/pdf")}, ) assert up_pdf.status_code == 201 # 3. Reject .exe / .txt and spoofed magic bytes -> 400 INVALID_FILE_TYPE bad_exe = client.post( "/api/attachments", headers=bio_headers, data={"entity_type": "asset", "entity_id": str(icu_asset.id)}, files={"file": ("malware.exe", b"MZ\x90\x00", "application/octet-stream")}, ) assert bad_exe.status_code == 400 assert bad_exe.json()["code"] == "INVALID_FILE_TYPE" bad_spoof = client.post( "/api/attachments", headers=bio_headers, data={"entity_type": "asset", "entity_id": str(icu_asset.id)}, files={"file": ("fake.jpg", b"not really a jpeg", "image/jpeg")}, ) assert bad_spoof.status_code == 400 assert bad_spoof.json()["code"] == "INVALID_FILE_TYPE" # 4. Reject >10 MB -> 413 FILE_TOO_LARGE oversized = b"%PDF-" + (b"0" * (10 * 1024 * 1024 + 100)) too_big = client.post( "/api/attachments", headers=bio_headers, data={"entity_type": "asset", "entity_id": str(icu_asset.id)}, files={"file": ("huge.pdf", oversized, "application/pdf")}, ) assert too_big.status_code == 413 assert too_big.json()["code"] == "FILE_TOO_LARGE" # 5. department_user cannot upload to or download from another department's asset ot_up = client.post( "/api/attachments", headers=bio_headers, data={"entity_type": "asset", "entity_id": str(ot_asset.id)}, files={"file": ("ot.png", png_bytes, "image/png")}, ) assert ot_up.status_code == 201 ot_att_id = ot_up.json()["id"] assert client.get(f"/api/attachments/{ot_att_id}/download", headers=dept_headers).status_code == 403 assert ( client.post( "/api/attachments", headers=dept_headers, data={"entity_type": "asset", "entity_id": str(ot_asset.id)}, files={"file": ("unauth.png", png_bytes, "image/png")}, ).status_code == 403 ) # department_user cannot upload to own-dept asset (only complaint), CAN upload to own-dept complaint assert ( client.post( "/api/attachments", headers=dept_headers, data={"entity_type": "asset", "entity_id": str(icu_asset.id)}, files={"file": ("icu.png", png_bytes, "image/png")}, ).status_code == 403 ) dept_cmp_up = client.post( "/api/attachments", headers=dept_headers, data={"entity_type": "complaint", "entity_id": str(icu_complaint.id)}, files={"file": ("fault.jpg", jpg_bytes, "image/jpeg")}, ) assert dept_cmp_up.status_code == 201 # management cannot upload or delete assert ( client.post( "/api/attachments", headers=mgmt_headers, data={"entity_type": "asset", "entity_id": str(icu_asset.id)}, files={"file": ("mgmt.png", png_bytes, "image/png")}, ).status_code == 403 ) assert client.delete(f"/api/attachments/{att_id}", headers=mgmt_headers).status_code == 403 # Delete removes DB row and disk file stored_files_before = list(Path(tmp_path).iterdir()) del_res = client.delete(f"/api/attachments/{att_id}", headers=bio_headers) assert del_res.status_code == 204 stored_files_after = list(Path(tmp_path).iterdir()) assert len(stored_files_after) == len(stored_files_before) - 1 assert client.get(f"/api/attachments/{att_id}/download", headers=bio_headers).status_code == 404