Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(notifications): test chat connections

Marcos Paulo Diniz017795ba0884
diff --git a/backend/app/api/notifications.py b/backend/app/api/notifications.py
index 705b9635..289b3491 100644
--- a/backend/app/api/notifications.py
+++ b/backend/app/api/notifications.py
@@ -438,6 +438,18 @@ def update_chat_connection(conn_id):
return jsonify({'success': True, 'connection': conn.to_dict()}), 200
+@notifications_bp.route('/admin/chat-connections/<int:conn_id>/test', methods=['POST'])
+@jwt_required()
+@admin_required
+def test_chat_connection(conn_id):
+ """Send a synchronous test through one chat connection."""
+ from app.services.chat_webhook_service import ChatWebhookService
+ result = ChatWebhookService.test(conn_id)
+ if result is None:
+ return jsonify({'error': 'Connection not found'}), 404
+ return jsonify(result), 200 if result.get('success') else 400
+
+
@notifications_bp.route('/admin/chat-connections/<int:conn_id>', methods=['DELETE'])
@jwt_required()
@admin_required
diff --git a/backend/app/services/chat_webhook_service.py b/backend/app/services/chat_webhook_service.py
index f2e77fd8..142149e2 100644
--- a/backend/app/services/chat_webhook_service.py
+++ b/backend/app/services/chat_webhook_service.py
@@ -235,6 +235,60 @@ class ChatWebhookService:
.all())
return [c for c in conns if c.matches_category(category)]
+ # ------------------------------------------------------------------
+ # Connection testing
+ # ------------------------------------------------------------------
+ @classmethod
+ def test(cls, conn_id):
+ """Synchronously send a test through a connection's real formatter.
+
+ Inactive connections remain testable so an administrator can validate
+ a destination before enabling it. The transient notification is never
+ persisted; only the connection's latest test outcome is recorded.
+ """
+ conn = db.session.get(ChatWebhookConnection, conn_id)
+ if conn is None:
+ return None
+
+ from app.notifications.models import Notification
+
+ message = 'This is a test notification from ServerKit.'
+ notification = Notification(
+ event_key='notification.test',
+ category='system',
+ severity=Notification.SEVERITY_TEST,
+ title='ServerKit test notification',
+ body=message,
+ audience=f'chat connection:{conn.id}',
+ created_at=datetime.utcnow(),
+ )
+ notification.set_data({'message': message})
+
+ try:
+ credentials = conn.credentials()
+ if conn.kind == 'webhook':
+ delivery_result = cls._deliver_webhook(
+ conn, credentials, notification)
+ else:
+ delivery_result = cls._deliver_chat(
+ conn, credentials, notification)
+ success = delivery_result.ok
+ error = delivery_result.error
+ except Exception as exc: # pragma: no cover - defensive formatter guard
+ success = False
+ error = str(exc)
+
+ conn.last_tested_at = datetime.utcnow()
+ conn.last_test_ok = success
+ db.session.commit()
+
+ if success:
+ return {'success': True, 'message': 'Test notification sent'}
+ return {
+ 'success': False,
+ 'error': str(error or 'test notification failed')[:300],
+ }
+
# ------------------------------------------------------------------
# Delivery (called by the chat channel adapter for ``conn:<id>`` targets)
# ------------------------------------------------------------------
diff --git a/backend/tests/test_notification_chat_connections.py b/backend/tests/test_notification_chat_connections.py
index f422a445..c50db373 100644
--- a/backend/tests/test_notification_chat_connections.py
+++ b/backend/tests/test_notification_chat_connections.py
@@ -255,6 +255,74 @@ class TestSigningAndDelivery:
assert seen['cfg']['webhook_url'] == 'https://discord/webhook'
+class TestConnectionTesting:
+ def test_inactive_connection_can_send_test_through_real_formatter(self, app, monkeypatch):
+ captured = {}
+
+ class _Resp:
+ status_code = 204
+ text = ''
+
+ def fake_post(url, json=None, timeout=None, **kwargs):
+ captured.update({'url': url, 'json': json, 'timeout': timeout})
+ return _Resp()
+
+ monkeypatch.setattr('app.services.notification_service.requests.post', fake_post)
+ conn = ChatWebhookService.add({
+ 'kind': 'discord',
+ 'name': 'Disabled room',
+ 'url': 'https://discord.example/webhook',
+ 'is_active': False,
+ })
+
+ result = ChatWebhookService.test(conn.id)
+
+ assert result == {'success': True, 'message': 'Test notification sent'}
+ assert captured['url'] == 'https://discord.example/webhook'
+ assert captured['json']['embeds'][0]['description'] == (
+ 'This is a test notification from ServerKit.'
+ )
+ assert conn.last_tested_at is not None
+ assert conn.last_test_ok is True
+
+ def test_failed_connection_test_persists_failure(self, app, monkeypatch):
+ class _Resp:
+ ok = False
+ status_code = 503
+
+ monkeypatch.setattr(
+ 'app.services.chat_webhook_service.requests.post',
+ lambda *args, **kwargs: _Resp(),
+ )
+ conn = ChatWebhookService.add({
+ 'kind': 'webhook', 'name': 'Ops', 'url': 'https://hooks.example/failing',
+ })
+
+ result = ChatWebhookService.test(conn.id)
+
+ assert result == {'success': False, 'error': 'webhook returned 503'}
+ assert conn.last_tested_at is not None
+ assert conn.last_test_ok is False
+
+ def test_connection_test_bounds_transport_errors(self, app, monkeypatch):
+ def fail_post(*args, **kwargs):
+ raise RuntimeError('x' * 500)
+
+ monkeypatch.setattr('app.services.notification_service.requests.post', fail_post)
+ conn = ChatWebhookService.add({
+ 'kind': 'discord', 'name': 'Ops', 'url': 'https://discord.example/webhook',
+ })
+
+ result = ChatWebhookService.test(conn.id)
+
+ assert result['success'] is False
+ assert result['error'] == 'x' * 300
+ assert conn.last_test_ok is False
+
+ def test_connection_test_returns_none_for_unknown_id(self, app):
+ assert ChatWebhookService.test(999999) is None
+
+
class TestImport:
def test_import_is_idempotent(self, app, monkeypatch):
from app.services.notification_service import NotificationService
@@ -335,3 +403,65 @@ class TestApi:
assert resp.status_code == 400
assert 'kind cannot be changed' in resp.get_json()['error']
+
+ def test_test_connection_returns_200_on_delivery(self, app, client, auth_headers,
+ monkeypatch):
+ class _Resp:
+ status_code = 204
+ text = ''
+
+ monkeypatch.setattr(
+ 'app.services.notification_service.requests.post',
+ lambda *args, **kwargs: _Resp(),
+ )
+ conn = ChatWebhookService.add({
+ 'kind': 'discord',
+ 'name': 'Disabled room',
+ 'url': 'https://discord.example/webhook',
+ 'is_active': False,
+ })
+
+ resp = client.post(
+ f'/api/v1/notifications/admin/chat-connections/{conn.id}/test',
+ headers=auth_headers,
+ )
+
+ assert resp.status_code == 200
+ assert resp.get_json() == {
+ 'success': True, 'message': 'Test notification sent',
+ }
+ db.session.refresh(conn)
+ assert conn.last_test_ok is True
+
+ def test_test_connection_returns_400_on_delivery_failure(self, app, client,
+ auth_headers, monkeypatch):
+ class _Resp:
+ ok = False
+ status_code = 503
+
+ monkeypatch.setattr(
+ 'app.services.chat_webhook_service.requests.post',
+ lambda *args, **kwargs: _Resp(),
+ )
+ conn = ChatWebhookService.add({
+ 'kind': 'webhook', 'name': 'Ops', 'url': 'https://hooks.example/failing',
+ })
+
+ resp = client.post(
+ f'/api/v1/notifications/admin/chat-connections/{conn.id}/test',
+ headers=auth_headers,
+ )
+
+ assert resp.status_code == 400
+ assert resp.get_json() == {
+ 'success': False, 'error': 'webhook returned 503',
+ }
+
+ def test_test_connection_returns_404_for_unknown_id(self, app, client, auth_headers):
+ resp = client.post(
+ '/api/v1/notifications/admin/chat-connections/999999/test',
+ headers=auth_headers,
+ )
+
+ assert resp.status_code == 404
+ assert resp.get_json() == {'error': 'Connection not found'}