-
Notifications
You must be signed in to change notification settings - Fork 139
Expand file tree
/
Copy pathclient_test.go
More file actions
198 lines (177 loc) · 5.7 KB
/
Copy pathclient_test.go
File metadata and controls
198 lines (177 loc) · 5.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package prometheus
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
"github.com/skyhook-io/radar/internal/errorlog"
)
func TestProbe(t *testing.T) {
tests := []struct {
name string
statusCode int
body string
want bool
wantEmptyEntry bool // expect the empty-instance warning to be recorded
}{
{
name: "healthy prometheus with targets",
statusCode: http.StatusOK,
body: `{"status":"success","data":{"resultType":"vector","result":[{"metric":{"job":"prometheus"},"value":[1700000000,"1"]}]}}`,
want: true,
},
{
name: "empty instance returns success with zero results",
statusCode: http.StatusOK,
body: `{"status":"success","data":{"resultType":"vector","result":[]}}`,
want: false,
wantEmptyEntry: true,
},
{
name: "non-prometheus 200 response (html)",
statusCode: http.StatusOK,
body: `<html><body>Login</body></html>`,
want: false,
},
{
name: "prometheus error body with 200",
statusCode: http.StatusOK,
body: `{"status":"error","errorType":"bad_data","error":"invalid query"}`,
want: false,
},
{
name: "non-200 status",
statusCode: http.StatusInternalServerError,
body: `oops`,
want: false,
},
{
name: "401 unauthorized",
statusCode: http.StatusUnauthorized,
body: ``,
want: false,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
errorlog.Reset()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(tc.statusCode)
_, _ = w.Write([]byte(tc.body))
}))
defer srv.Close()
c := &Client{httpClient: &http.Client{Timeout: 5 * time.Second}}
got := c.probe(context.Background(), srv.URL)
if got != tc.want {
t.Fatalf("probe() = %v, want %v", got, tc.want)
}
gotEmptyEntry := false
for _, e := range errorlog.GetEntries() {
if e.Source == "prometheus" && e.Level == "warning" {
gotEmptyEntry = true
}
}
if gotEmptyEntry != tc.wantEmptyEntry {
t.Fatalf("empty-instance warning recorded = %v, want %v", gotEmptyEntry, tc.wantEmptyEntry)
}
})
}
}
func TestHeadersOnProbe(t *testing.T) {
var gotAuth, gotOrg atomic.Value
gotAuth.Store("")
gotOrg.Store("")
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotAuth.Store(r.Header.Get("Authorization"))
gotOrg.Store(r.Header.Get("X-Scope-OrgID"))
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"status":"success","data":{"resultType":"vector","result":[{"metric":{"job":"prometheus"},"value":[1700000000,"1"]}]}}`))
}))
defer srv.Close()
c := &Client{
httpClient: &http.Client{Timeout: 5 * time.Second},
headers: map[string]string{
"Authorization": "Bearer test-token",
"X-Scope-OrgID": "tenant-7",
},
}
if !c.probe(context.Background(), srv.URL) {
t.Fatal("probe() returned false for healthy server")
}
if got := gotAuth.Load().(string); got != "Bearer test-token" {
t.Errorf("Authorization header = %q, want %q", got, "Bearer test-token")
}
if got := gotOrg.Load().(string); got != "tenant-7" {
t.Errorf("X-Scope-OrgID header = %q, want %q", got, "tenant-7")
}
}
func TestHeadersNoneWhenUnset(t *testing.T) {
var sawAuth atomic.Bool
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, ok := r.Header["Authorization"]; ok {
sawAuth.Store(true)
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"status":"success","data":{"resultType":"vector","result":[{"metric":{"job":"prometheus"},"value":[1700000000,"1"]}]}}`))
}))
defer srv.Close()
c := &Client{httpClient: &http.Client{Timeout: 5 * time.Second}}
if !c.probe(context.Background(), srv.URL) {
t.Fatal("probe() returned false for healthy server")
}
if sawAuth.Load() {
t.Error("Authorization header sent when none configured")
}
}
func TestEnsureConnectedReturnsRecentDiscoveryError(t *testing.T) {
wantErr := errors.New("cached discovery failure")
c := &Client{
httpClient: &http.Client{Timeout: 5 * time.Second},
lastDiscoverErr: wantErr,
lastDiscoverAt: time.Now(),
}
_, _, gotErr := c.EnsureConnected(context.Background())
if !errors.Is(gotErr, wantErr) {
t.Fatalf("EnsureConnected error = %v, want cached error %v", gotErr, wantErr)
}
}
func TestEnsureConnectedIgnoresExpiredDiscoveryError(t *testing.T) {
wantErr := errors.New("cached discovery failure")
c := &Client{
httpClient: &http.Client{Timeout: 5 * time.Second},
lastDiscoverErr: wantErr,
lastDiscoverAt: time.Now().Add(-failedDiscoveryCacheTTL - time.Second),
}
_, _, gotErr := c.EnsureConnected(context.Background())
if errors.Is(gotErr, wantErr) {
t.Fatalf("EnsureConnected returned expired cached error: %v", gotErr)
}
if gotErr == nil || gotErr.Error() != "no Kubernetes client available for discovery" {
t.Fatalf("EnsureConnected error = %v, want fresh discovery error", gotErr)
}
}
func TestEnsureConnectedDoesNotClearCachedConnectionOnCanceledProbe(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
<-r.Context().Done()
}))
defer srv.Close()
c := &Client{
baseURL: srv.URL,
httpClient: &http.Client{Timeout: 5 * time.Second},
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, _, gotErr := c.EnsureConnected(ctx)
if !errors.Is(gotErr, context.Canceled) {
t.Fatalf("EnsureConnected error = %v, want context.Canceled", gotErr)
}
c.mu.RLock()
gotBase := c.baseURL
c.mu.RUnlock()
if gotBase != srv.URL {
t.Fatalf("baseURL = %q, want cached connection preserved %q", gotBase, srv.URL)
}
}