import os import sys import werkzeug if not hasattr(werkzeug, "__version__"): werkzeug.__version__ = "3.0.0" os.environ["N8N_APPROVED_WEBHOOK_URL"] = "" import app as aiinvoice_app from unittest.mock import patch, MagicMock print("Testing e:\\aiinvoice test-webhook endpoint with empty URL...", flush=True) with aiinvoice_app.app.test_request_context(): res = aiinvoice_app.pharmacy_test_webhook() resp_obj, status = res assert status == 400 assert resp_obj.json.get("configured") is False print("Passed: returns 400 and configured=False when empty.", flush=True) test_invoice = { "invoice_id": "INV-TEST-999", "invoice_number": "TEST/2026/01", "supplier": "TEST PHARMA", "items": [ {"description": "PARACETAMOL 500MG", "item_code": "PARA-500", "quantity": 10} ] } print("Testing dispatch_n8n_approval_webhook with mocked n8n...", flush=True) with patch.dict(os.environ, {"N8N_APPROVED_WEBHOOK_URL": "https://n8n.example.com/webhook/invoice-approved", "N8N_WEBHOOK_SECRET": "my-secret-123"}): with patch("requests.post") as mock_post: mock_resp = MagicMock() mock_resp.status_code = 200 mock_resp.text = '{"status":"received"}' mock_post.return_value = mock_resp result = aiinvoice_app.dispatch_n8n_approval_webhook( extraction_id=999, invoice_data=test_invoice, approver_username="pharmacy_lead" ) print("Webhook result:", result, flush=True) assert result["status"] == "delivered", f"Expected delivered, got {result}" assert mock_post.called call_args = mock_post.call_args payload = call_args[1]["json"] headers = call_args[1]["headers"] assert payload["event"] == "invoice_approved" assert payload["extraction_id"] == 999 assert payload["status"] == "approved" assert payload["approved_by"] == "pharmacy_lead" assert payload["invoice_data"]["invoice_id"] == "INV-TEST-999" assert headers.get("X-Webhook-Secret") == "my-secret-123" print("Passed: webhook payload structured accurately with event, status, approver, headers, and invoice_data.", flush=True) print("\nAIINVOICE TEST PASSED SUCCESSFULLY!", flush=True)