1package admin
2
3import (
4 "encoding/json"
5 "net/http"
6 "testing"
7
8 "github.com/stretchr/testify/assert"
9 "github.com/stretchr/testify/require"
10
11 "github.com/bnema/gordon/internal/adapters/dto"
12 inmocks "github.com/bnema/gordon/internal/boundaries/in/mocks"
13 "github.com/bnema/gordon/internal/domain"
14)
15
16func TestHandler_TrafficStatus(t *testing.T) {
17 trafficSvc := inmocks.NewMockTrafficStatusService(t)
18 trafficSvc.EXPECT().Status().Return(domain.TrafficStatus{
19 LastReloadStatus: "ok",
20 EntryPoints: []domain.EntryPointStatus{{
21 Name: "edge", Address: "127.0.0.1:8443", Protocol: domain.EntryPointProtocolSmartTCP,
22 Active: true, ActiveTCPConnections: 2, TotalAccepted: 3, BytesIn: 11, BytesOut: 22,
23 SmartTCP: domain.SmartTCPCounters{HTTPAccepted: 1, PROXYRefused: 1},
24 }},
25 Counters: domain.TrafficCounters{ActiveTCPConnections: 2, TotalAccepted: 3, BytesIn: 11, BytesOut: 22, SmartTCP: domain.SmartTCPCounters{HTTPAccepted: 1, PROXYRefused: 1}},
26 })
27 handler := newTestHandler(t, func(d *HandlerDeps) {
28 d.TrafficSvc = trafficSvc
29 })
30 server := newScopedTestServer(t, handler, "admin:status:read")
31
32 resp, err := http.Get(server.URL + "/admin/traffic/status")
33 require.NoError(t, err)
34 defer resp.Body.Close()
35 require.Equal(t, http.StatusOK, resp.StatusCode)
36
37 var body dto.TrafficStatusResponse
38 require.NoError(t, json.NewDecoder(resp.Body).Decode(&body))
39 assert.Equal(t, "ok", body.LastReloadStatus)
40 require.Len(t, body.EntryPoints, 1)
41 assert.Equal(t, "edge", body.EntryPoints[0].Name)
42 assert.Equal(t, int64(2), body.Counters.ActiveTCPConnections)
43 assert.Equal(t, int64(22), body.Counters.BytesOut)
44 assert.Equal(t, int64(1), body.EntryPoints[0].SmartTCP.HTTPAccepted)
45 assert.Equal(t, int64(1), body.Counters.SmartTCP.PROXYRefused)
46}
47
48func TestHandler_TrafficStatusRequiresStatusRead(t *testing.T) {
49 trafficSvc := inmocks.NewMockTrafficStatusService(t)
50 handler := newTestHandler(t, func(d *HandlerDeps) { d.TrafficSvc = trafficSvc })
51 server := newScopedTestServer(t, handler, "admin:config:read")
52
53 resp, err := http.Get(server.URL + "/admin/traffic/status")
54 require.NoError(t, err)
55 defer resp.Body.Close()
56 assert.Equal(t, http.StatusForbidden, resp.StatusCode)
57}
58
59func TestHandler_TrafficStatusUnavailableWithoutService(t *testing.T) {
60 handler := newTestHandler(t, func(d *HandlerDeps) { d.TrafficSvc = nil })
61 server := newScopedTestServer(t, handler, "admin:status:read")
62
63 resp, err := http.Get(server.URL + "/admin/traffic/status")
64 require.NoError(t, err)
65 defer resp.Body.Close()
66 require.Equal(t, http.StatusOK, resp.StatusCode)
67
68 var body dto.TrafficStatusResponse
69 require.NoError(t, json.NewDecoder(resp.Body).Decode(&body))
70 assert.Equal(t, "unavailable", body.LastReloadStatus)
71 assert.NotNil(t, body.EntryPoints)
72 assert.NotNil(t, body.Routers)
73 assert.NotNil(t, body.Services)
74}