-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsvstat_test.go
More file actions
657 lines (568 loc) · 15.1 KB
/
Copy pathsvstat_test.go
File metadata and controls
657 lines (568 loc) · 15.1 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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
package main_test
import (
"context"
"encoding/json"
"html/template"
"net"
"net/http"
"net/http/httptest"
"os"
"testing"
"time"
"github.com/afs-agentics/svstat/checker"
"github.com/afs-agentics/svstat/config"
"github.com/afs-agentics/svstat/handler"
)
// ---------------------------
// Config parsing tests
// ---------------------------
func TestConfigLoad_ValidYAML(t *testing.T) {
content := []byte(`
services:
- name: "Test API"
url: "https://example.com/health"
type: http
expected_code: 200
interval: 30
timeout: 10
- name: "Test TCP"
url: "localhost:5432"
type: tcp
interval: 60
timeout: 5
`)
tmpFile := writeTempFile(t, "services*.yaml", content)
defer os.Remove(tmpFile)
cfg, err := config.Load(tmpFile)
if err != nil {
t.Fatalf("expected no error, got: %v", err)
}
if len(cfg.Services) != 2 {
t.Fatalf("expected 2 services, got %d", len(cfg.Services))
}
s1 := cfg.Services[0]
if s1.Name != "Test API" {
t.Errorf("expected name 'Test API', got %q", s1.Name)
}
if s1.URL != "https://example.com/health" {
t.Errorf("expected url 'https://example.com/health', got %q", s1.URL)
}
if s1.Type != "http" {
t.Errorf("expected type 'http', got %q", s1.Type)
}
if s1.ExpectedCode != 200 {
t.Errorf("expected expected_code 200, got %d", s1.ExpectedCode)
}
if s1.Interval != 30*time.Second {
t.Errorf("expected interval 30s, got %v", s1.Interval)
}
if s1.Timeout != 10*time.Second {
t.Errorf("expected timeout 10s, got %v", s1.Timeout)
}
s2 := cfg.Services[1]
if s2.Name != "Test TCP" {
t.Errorf("expected name 'Test TCP', got %q", s2.Name)
}
if s2.Type != "tcp" {
t.Errorf("expected type 'tcp', got %q", s2.Type)
}
}
func TestConfigLoad_Defaults(t *testing.T) {
content := []byte(`
services:
- name: "Minimal"
url: "https://example.com"
type: http
`)
tmpFile := writeTempFile(t, "services*.yaml", content)
defer os.Remove(tmpFile)
cfg, err := config.Load(tmpFile)
if err != nil {
t.Fatalf("expected no error, got: %v", err)
}
s := cfg.Services[0]
if s.ExpectedCode != 200 {
t.Errorf("expected default expected_code 200, got %d", s.ExpectedCode)
}
if s.Interval != 30*time.Second {
t.Errorf("expected default interval 30s, got %v", s.Interval)
}
if s.Timeout != 10*time.Second {
t.Errorf("expected default timeout 10s, got %v", s.Timeout)
}
}
func TestConfigLoad_Errors(t *testing.T) {
t.Run("missing file", func(t *testing.T) {
_, err := config.Load("/nonexistent/path/services.yaml")
if err == nil {
t.Fatal("expected error for missing file")
}
})
t.Run("empty name", func(t *testing.T) {
content := []byte(`
services:
- name: ""
url: "https://example.com"
type: http
`)
tmpFile := writeTempFile(t, "services*.yaml", content)
defer os.Remove(tmpFile)
_, err := config.Load(tmpFile)
if err == nil {
t.Fatal("expected error for empty name")
}
})
t.Run("invalid type", func(t *testing.T) {
content := []byte(`
services:
- name: "Bad"
url: "https://example.com"
type: grpc
`)
tmpFile := writeTempFile(t, "services*.yaml", content)
defer os.Remove(tmpFile)
_, err := config.Load(tmpFile)
if err == nil {
t.Fatal("expected error for invalid type")
}
})
t.Run("invalid yaml", func(t *testing.T) {
content := []byte(`services: [invalid yaml: `)
tmpFile := writeTempFile(t, "services*.yaml", content)
defer os.Remove(tmpFile)
_, err := config.Load(tmpFile)
if err == nil {
t.Fatal("expected error for invalid yaml")
}
})
}
func TestConfigLoad_JSON(t *testing.T) {
// JSON is also valid YAML (YAML is a superset)
content := []byte(`{
"services": [
{
"name": "JSON Service",
"url": "https://json-service.com/health",
"type": "http",
"expected_code": 200,
"interval": 15,
"timeout": 5
}
]
}`)
tmpFile := writeTempFile(t, "services*.json", content)
defer os.Remove(tmpFile)
cfg, err := config.Load(tmpFile)
if err != nil {
t.Fatalf("expected no error, got: %v", err)
}
if len(cfg.Services) != 1 {
t.Fatalf("expected 1 service, got %d", len(cfg.Services))
}
if cfg.Services[0].Name != "JSON Service" {
t.Errorf("expected name 'JSON Service', got %q", cfg.Services[0].Name)
}
}
// ---------------------------
// Checker tests
// ---------------------------
func TestChecker_CheckHTTP_Up(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"status":"ok"}`))
}))
defer ts.Close()
cfg := &config.Config{
Services: []config.ServiceConfig{
{
Name: "Test Server",
URL: ts.URL,
Type: "http",
ExpectedCode: 200,
Interval: 60 * time.Second,
Timeout: 5 * time.Second,
},
},
}
chk := checker.New(cfg)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
chk.Start(ctx)
time.Sleep(200 * time.Millisecond)
result := chk.GetResult("Test Server")
if result == nil {
t.Fatal("expected result, got nil")
}
if result.Status != checker.StatusUp {
t.Errorf("expected status 'up', got %q; error: %s", result.Status, result.Error)
}
if result.ResponseTimeMs <= 0 {
t.Errorf("expected positive response time, got %d", result.ResponseTimeMs)
}
if result.LastChecked.IsZero() {
t.Error("expected non-zero last_checked")
}
}
func TestChecker_CheckHTTP_ExpectedCode(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}))
defer ts.Close()
cfg := &config.Config{
Services: []config.ServiceConfig{
{
Name: "Bad Status",
URL: ts.URL,
Type: "http",
ExpectedCode: 200,
Interval: 60 * time.Second,
Timeout: 5 * time.Second,
},
},
}
chk := checker.New(cfg)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
chk.Start(ctx)
time.Sleep(200 * time.Millisecond)
result := chk.GetResult("Bad Status")
if result == nil {
t.Fatal("expected result, got nil")
}
if result.Status != checker.StatusDown {
t.Errorf("expected status 'down' for 500, got %q", result.Status)
}
if result.Error == "" {
t.Error("expected error message for bad status code")
}
}
func TestChecker_CheckHTTP_Down(t *testing.T) {
cfg := &config.Config{
Services: []config.ServiceConfig{
{
Name: "Unreachable",
URL: "http://127.0.0.1:19998",
Type: "http",
ExpectedCode: 200,
Interval: 60 * time.Second,
Timeout: 1 * time.Second,
},
},
}
chk := checker.New(cfg)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
chk.Start(ctx)
time.Sleep(1500 * time.Millisecond)
result := chk.GetResult("Unreachable")
if result == nil {
t.Fatal("expected result, got nil")
}
if result.Status != checker.StatusDown {
t.Errorf("expected status 'down', got %q", result.Status)
}
}
func TestChecker_CheckTCP(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("failed to start TCP listener: %v", err)
}
defer ln.Close()
addr := ln.Addr().String()
cfg := &config.Config{
Services: []config.ServiceConfig{
{
Name: "TCP Server",
URL: addr,
Type: "tcp",
Interval: 60 * time.Second,
Timeout: 5 * time.Second,
},
},
}
chk := checker.New(cfg)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
chk.Start(ctx)
time.Sleep(200 * time.Millisecond)
result := chk.GetResult("TCP Server")
if result == nil {
t.Fatal("expected result, got nil")
}
if result.Status != checker.StatusUp {
t.Errorf("expected status 'up', got %q; error: %s", result.Status, result.Error)
}
}
func TestChecker_CheckTCP_Down(t *testing.T) {
cfg := &config.Config{
Services: []config.ServiceConfig{
{
Name: "TCP Unreachable",
URL: "127.0.0.1:19997",
Type: "tcp",
Interval: 60 * time.Second,
Timeout: 1 * time.Second,
},
},
}
chk := checker.New(cfg)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
chk.Start(ctx)
time.Sleep(1500 * time.Millisecond)
result := chk.GetResult("TCP Unreachable")
if result == nil {
t.Fatal("expected result, got nil")
}
if result.Status != checker.StatusDown {
t.Errorf("expected status 'down', got %q", result.Status)
}
}
func TestChecker_GetAllResults(t *testing.T) {
cfg := &config.Config{
Services: []config.ServiceConfig{
{
Name: "Alpha",
URL: "http://127.0.0.1:19996",
Type: "http",
Interval: 3600 * time.Second,
Timeout: 1 * time.Second,
},
{
Name: "Beta",
URL: "127.0.0.1:19995",
Type: "tcp",
Interval: 3600 * time.Second,
Timeout: 1 * time.Second,
},
},
}
chk := checker.New(cfg)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
chk.Start(ctx)
time.Sleep(1500 * time.Millisecond)
results := chk.GetAllResults()
if len(results) != 2 {
t.Errorf("expected 2 results, got %d", len(results))
}
found := make(map[string]bool)
for _, r := range results {
found[r.Name] = true
}
if !found["Alpha"] || !found["Beta"] {
t.Error("expected both service names in results")
}
}
func TestChecker_UnknownType(t *testing.T) {
cfg := &config.Config{
Services: []config.ServiceConfig{
{
Name: "Weird Type",
URL: "http://example.com",
Type: "unknown",
Interval: 60 * time.Second,
Timeout: 5 * time.Second,
},
},
}
chk := checker.New(cfg)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
chk.Start(ctx)
time.Sleep(200 * time.Millisecond)
result := chk.GetResult("Weird Type")
if result == nil {
t.Fatal("expected result, got nil")
}
if result.Status != checker.StatusDown {
t.Errorf("expected status 'down' for unknown type, got %q", result.Status)
}
if result.Error == "" {
t.Error("expected error message for unknown type")
}
}
// ---------------------------
// Handler tests
// ---------------------------
func TestHandler_Health(t *testing.T) {
cfg := &config.Config{Services: []config.ServiceConfig{}}
chk := checker.New(cfg)
h := handler.New(chk, nil, nil)
req := httptest.NewRequest(http.MethodGet, "/health", nil)
w := httptest.NewRecorder()
h.Health(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected 200, got %d", w.Code)
}
var body map[string]string
if err := json.NewDecoder(w.Body).Decode(&body); err != nil {
t.Fatalf("failed to decode response: %v", err)
}
if body["status"] != "ok" {
t.Errorf("expected status 'ok', got %q", body["status"])
}
}
func TestHandler_APIStatus_Empty(t *testing.T) {
cfg := &config.Config{Services: []config.ServiceConfig{}}
chk := checker.New(cfg)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
chk.Start(ctx)
time.Sleep(100 * time.Millisecond)
h := handler.New(chk, nil, nil)
req := httptest.NewRequest(http.MethodGet, "/api/status", nil)
w := httptest.NewRecorder()
h.APIStatus(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected 200, got %d", w.Code)
}
var results []interface{}
if err := json.NewDecoder(w.Body).Decode(&results); err != nil {
t.Fatalf("failed to decode response: %v", err)
}
if len(results) != 0 {
t.Errorf("expected empty array, got %d items", len(results))
}
}
func TestHandler_APIServiceStatus(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer ts.Close()
cfg := &config.Config{
Services: []config.ServiceConfig{
{
Name: "MyAPI",
URL: ts.URL,
Type: "http",
ExpectedCode: 200,
Interval: 60 * time.Second,
Timeout: 5 * time.Second,
},
},
}
chk := checker.New(cfg)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
chk.Start(ctx)
time.Sleep(200 * time.Millisecond)
h := handler.New(chk, nil, nil)
t.Run("existing service", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/api/status/MyAPI", nil)
w := httptest.NewRecorder()
h.APIServiceStatus(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected 200, got %d", w.Code)
}
var result checker.Result
if err := json.NewDecoder(w.Body).Decode(&result); err != nil {
t.Fatalf("failed to decode response: %v", err)
}
if result.Name != "MyAPI" {
t.Errorf("expected name 'MyAPI', got %q", result.Name)
}
})
t.Run("nonexistent service", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/api/status/Nope", nil)
w := httptest.NewRecorder()
h.APIServiceStatus(w, req)
if w.Code != http.StatusNotFound {
t.Errorf("expected 404, got %d", w.Code)
}
})
t.Run("empty name", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/api/status/", nil)
w := httptest.NewRecorder()
h.APIServiceStatus(w, req)
if w.Code != http.StatusBadRequest {
t.Errorf("expected 400, got %d", w.Code)
}
})
}
func TestHandler_Dashboard_Renders(t *testing.T) {
tmpl := template.Must(template.New("test").Parse(`
<!DOCTYPE html>
<html>
<head><title>svstat</title></head>
<body>
<h1>Services</h1>
{{range .Results}}
<div class="service">{{.Name}} - {{.Status}}</div>
{{else}}
<p>No services</p>
{{end}}
</body>
</html>`))
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer ts.Close()
cfg := &config.Config{
Services: []config.ServiceConfig{
{
Name: "Dashboard Test",
URL: ts.URL,
Type: "http",
ExpectedCode: 200,
Interval: 3600 * time.Second,
Timeout: 5 * time.Second,
},
},
}
chk := checker.New(cfg)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
chk.Start(ctx)
time.Sleep(200 * time.Millisecond)
h := handler.New(chk, tmpl, []string{"Dashboard Test"})
req := httptest.NewRequest(http.MethodGet, "/", nil)
w := httptest.NewRecorder()
h.Dashboard(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected 200, got %d", w.Code)
}
body := w.Body.String()
if body == "" {
t.Error("expected non-empty body")
}
if !contains(body, "Dashboard Test") {
t.Error("expected service name in dashboard HTML")
}
}
func TestHandler_NotFound(t *testing.T) {
chk := checker.New(&config.Config{})
h := handler.New(chk, nil, nil)
req := httptest.NewRequest(http.MethodGet, "/nonexistent-path", nil)
w := httptest.NewRecorder()
h.Dashboard(w, req)
if w.Code != http.StatusNotFound {
t.Errorf("expected 404, got %d", w.Code)
}
}
// ---------------------------
// Helpers
// ---------------------------
func writeTempFile(t *testing.T, pattern string, content []byte) string {
t.Helper()
tmpFile, err := os.CreateTemp("", pattern)
if err != nil {
t.Fatalf("failed to create temp file: %v", err)
}
if _, err := tmpFile.Write(content); err != nil {
t.Fatalf("failed to write temp file: %v", err)
}
tmpFile.Close()
return tmpFile.Name()
}
func contains(s, substr string) bool {
return len(s) >= len(substr) && containsStr(s, substr)
}
func containsStr(s, substr string) bool {
for i := 0; i <= len(s)-len(substr); i++ {
if s[i:i+len(substr)] == substr {
return true
}
}
return false
}