-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonitoring_test.go
More file actions
366 lines (291 loc) · 10 KB
/
monitoring_test.go
File metadata and controls
366 lines (291 loc) · 10 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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
package main
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestEnhancedHealthEndpoint(t *testing.T) {
app := NewApp()
req, err := http.NewRequest("GET", "/health", nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
handler := http.HandlerFunc(app.handleHealth)
handler.ServeHTTP(rr, req)
// Check status code
if status := rr.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK)
}
// Debug: Print the actual response
t.Logf("Response body: %s", rr.Body.String())
// Parse JSON response - it's wrapped in the APIResponse structure
var response APIResponse
err = json.Unmarshal(rr.Body.Bytes(), &response)
if err != nil {
t.Fatalf("Failed to parse API response: %v", err)
}
// Extract the health check data from the response
healthData, ok := response.Data.(map[string]interface{})
if !ok {
t.Fatal("Response data is not a map")
}
// Check basic fields
if status, exists := healthData["status"]; !exists || status == "" {
t.Error("Health check status is missing or empty")
}
if components, exists := healthData["components"]; !exists {
t.Error("Health check components are missing")
} else {
componentsMap, ok := components.(map[string]interface{})
if !ok {
t.Error("Components is not a map")
} else if len(componentsMap) == 0 {
t.Error("Health check components are empty")
} else {
// Check that expected components are present
expectedComponents := []string{"filesystem", "memory", "disk_space"}
for _, component := range expectedComponents {
if _, exists := componentsMap[component]; !exists {
t.Errorf("Expected component %s not found in health check", component)
}
}
}
}
// Check system health
if system, exists := healthData["system"]; exists {
systemMap, ok := system.(map[string]interface{})
if ok {
if goroutines, exists := systemMap["goroutines"]; exists {
if g, ok := goroutines.(float64); !ok || g <= 0 {
t.Error("System goroutines count should be positive")
}
}
}
}
}
func TestEnhancedMetricsEndpoint(t *testing.T) {
app := NewApp()
t.Run("JSON format", func(t *testing.T) {
req, err := http.NewRequest("GET", "/metrics?format=json", nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
handler := http.HandlerFunc(app.handleMetrics)
handler.ServeHTTP(rr, req)
// Check status code
if status := rr.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK)
}
// Check content type
expected := "application/json"
if ct := rr.Header().Get("Content-Type"); ct != expected {
t.Errorf("handler returned wrong content type: got %v want %v", ct, expected)
}
// Debug: Print the actual response
t.Logf("Metrics response body: %s", rr.Body.String())
// Parse JSON response - it's wrapped in the APIResponse structure
var response APIResponse
err = json.Unmarshal(rr.Body.Bytes(), &response)
if err != nil {
t.Fatalf("Failed to parse API response: %v", err)
}
// Extract the metrics data from the response
metricsData, ok := response.Data.(map[string]interface{})
if !ok {
t.Fatal("Response data is not a map")
}
// Verify basic structure exists
if errorsByCode, exists := metricsData["errors_by_code"]; !exists {
t.Error("ErrorsByCode should be present")
} else if errorsByCode == nil {
t.Error("ErrorsByCode should not be nil")
}
if errorsByEndpoint, exists := metricsData["errors_by_endpoint"]; !exists {
t.Error("ErrorsByEndpoint should be present")
} else if errorsByEndpoint == nil {
t.Error("ErrorsByEndpoint should not be nil")
}
})
t.Run("Prometheus format", func(t *testing.T) {
req, err := http.NewRequest("GET", "/metrics", nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
handler := http.HandlerFunc(app.handleMetrics)
handler.ServeHTTP(rr, req)
// Check status code
if status := rr.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK)
}
// Check content type
expected := "text/plain; version=0.0.4"
if ct := rr.Header().Get("Content-Type"); ct != expected {
t.Errorf("handler returned wrong content type: got %v want %v", ct, expected)
}
// Check that response contains expected metrics
body := rr.Body.String()
expectedMetrics := []string{
"dalleserver_errors_total",
"dalleserver_retries_total",
"dalleserver_openai_requests_total",
"dalleserver_up",
}
for _, metric := range expectedMetrics {
if !strings.Contains(body, metric) {
t.Errorf("Expected metric %s not found in response", metric)
}
}
})
}
func TestReadinessEndpoint(t *testing.T) {
app := NewApp()
req, err := http.NewRequest("GET", "/health?check=readiness", nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
handler := http.HandlerFunc(app.handleHealth)
handler.ServeHTTP(rr, req)
// Check status code - should be OK for healthy service
if status := rr.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK)
}
// Check that response contains status
body := rr.Body.String()
if !strings.Contains(body, "ready") {
t.Error("Response should contain 'ready' status")
}
}
func TestLivenessEndpoint(t *testing.T) {
app := NewApp()
req, err := http.NewRequest("GET", "/health?check=liveness", nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
handler := http.HandlerFunc(app.handleHealth)
handler.ServeHTTP(rr, req)
// Check status code - should always be OK if server is running
if status := rr.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK)
}
// Check that response contains status
body := rr.Body.String()
if !strings.Contains(body, "alive") {
t.Error("Response should contain 'alive' status")
}
}
func TestMetricsCollection(t *testing.T) {
collector := NewMetricsCollector()
// Test error recording
collector.RecordError("TEST_ERROR", "test_endpoint", "test-request-123")
metrics := collector.GetMetrics()
if metrics.TotalErrors != 1 {
t.Errorf("Expected 1 total error, got %d", metrics.TotalErrors)
}
if metrics.ErrorsByCode["TEST_ERROR"] != 1 {
t.Errorf("Expected 1 TEST_ERROR, got %d", metrics.ErrorsByCode["TEST_ERROR"])
}
if metrics.ErrorsByEndpoint["test_endpoint"] != 1 {
t.Errorf("Expected 1 error for test_endpoint, got %d", metrics.ErrorsByEndpoint["test_endpoint"])
}
// Test retry recording
collector.RecordRetry("test_operation", "test-request-456")
metrics = collector.GetMetrics()
if metrics.TotalRetries != 1 {
t.Errorf("Expected 1 total retry, got %d", metrics.TotalRetries)
}
if metrics.RetriesByOperation["test_operation"] != 1 {
t.Errorf("Expected 1 retry for test_operation, got %d", metrics.RetriesByOperation["test_operation"])
}
// Test response time recording
collector.RecordResponseTime(150, "test-request-789")
metrics = collector.GetMetrics()
if metrics.ResponseTimes.Count != 1 {
t.Errorf("Expected 1 response time record, got %d", metrics.ResponseTimes.Count)
}
if metrics.ResponseTimes.Avg != 150.0 {
t.Errorf("Expected average response time 150.0, got %.2f", metrics.ResponseTimes.Avg)
}
// Test OpenAI request recording
collector.RecordOpenAIRequest(true, false, "test-request-openai")
metrics = collector.GetMetrics()
if metrics.OpenAIRequests != 1 {
t.Errorf("Expected 1 OpenAI request, got %d", metrics.OpenAIRequests)
}
if metrics.OpenAIErrors != 0 {
t.Errorf("Expected 0 OpenAI errors, got %d", metrics.OpenAIErrors)
}
// Test OpenAI error recording
collector.RecordOpenAIRequest(false, true, "test-request-openai-error")
metrics = collector.GetMetrics()
if metrics.OpenAIRequests != 2 {
t.Errorf("Expected 2 OpenAI requests, got %d", metrics.OpenAIRequests)
}
if metrics.OpenAIErrors != 1 {
t.Errorf("Expected 1 OpenAI error, got %d", metrics.OpenAIErrors)
}
if metrics.OpenAITimeouts != 1 {
t.Errorf("Expected 1 OpenAI timeout, got %d", metrics.OpenAITimeouts)
}
}
func TestHealthChecker(t *testing.T) {
hc := NewHealthChecker()
// Test health check without circuit breaker
health := hc.CheckHealth("test-request-health")
if health.Status == "" {
t.Error("Health status should not be empty")
}
if len(health.Components) == 0 {
t.Error("Health components should not be empty")
}
// Test that filesystem component is present
if _, exists := health.Components["filesystem"]; !exists {
t.Error("Filesystem component should be present")
}
// Test system health
if health.System.Goroutines <= 0 {
t.Error("System goroutines should be positive")
}
if health.System.GOMAXPROCS <= 0 {
t.Error("GOMAXPROCS should be positive")
}
// Test with circuit breaker
cb := NewCircuitBreaker(3, 10*time.Second)
hc.SetCircuitBreaker(cb)
healthWithCB := hc.CheckHealth("test-request-health-cb")
// Should now include OpenAI component
if _, exists := healthWithCB.Components["openai"]; !exists {
t.Error("OpenAI component should be present when circuit breaker is set")
}
}
func TestPrometheusMetrics(t *testing.T) {
collector := NewMetricsCollector()
// Record some test data
collector.RecordError("TEST_ERROR", "test_endpoint", "test-123")
collector.RecordError("ANOTHER_ERROR", "other_endpoint", "test-456")
collector.RecordRetry("test_operation", "test-456")
collector.RecordResponseTime(200, "test-789")
prometheus := collector.PrometheusMetrics()
// Check for expected metrics
expectedMetrics := []string{
"dalleserver_errors_total 2",
"dalleserver_retries_total 1",
"dalleserver_up 1",
"dalleserver_error_code_total{code=\"TEST_ERROR\"} 1",
"dalleserver_error_code_total{code=\"ANOTHER_ERROR\"} 1",
"dalleserver_error_endpoint_total{endpoint=\"test_endpoint\"} 1",
"dalleserver_error_endpoint_total{endpoint=\"other_endpoint\"} 1",
}
for _, expected := range expectedMetrics {
if !strings.Contains(prometheus, expected) {
t.Errorf("Expected metric '%s' not found in Prometheus output", expected)
}
}
}