- Add error checks for unchecked return values (errcheck) - Remove unused struct fields (unused) - Fix gofmt formatting issues
78 lines
1.8 KiB
Go
78 lines
1.8 KiB
Go
package health
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func TestHealthEndpoint(t *testing.T) {
|
|
srv := New(18080, "/health", "/ready", nil)
|
|
srv.Start()
|
|
defer srv.Stop(context.Background())
|
|
time.Sleep(50 * time.Millisecond)
|
|
|
|
resp, err := http.Get("http://localhost:18080/health")
|
|
if err != nil {
|
|
t.Fatalf("health request failed: %v", err)
|
|
}
|
|
defer func() { _ = resp.Body.Close() }()
|
|
|
|
if resp.StatusCode != 200 {
|
|
t.Errorf("expected 200, got %d", resp.StatusCode)
|
|
}
|
|
body, _ := io.ReadAll(resp.Body)
|
|
var data map[string]string
|
|
_ = json.Unmarshal(body, &data)
|
|
if data["status"] != "healthy" {
|
|
t.Errorf("expected status 'healthy', got %q", data["status"])
|
|
}
|
|
}
|
|
|
|
func TestReadyEndpointDefault(t *testing.T) {
|
|
srv := New(18081, "/health", "/ready", nil)
|
|
srv.Start()
|
|
defer srv.Stop(context.Background())
|
|
time.Sleep(50 * time.Millisecond)
|
|
|
|
resp, err := http.Get("http://localhost:18081/ready")
|
|
if err != nil {
|
|
t.Fatalf("ready request failed: %v", err)
|
|
}
|
|
defer func() { _ = resp.Body.Close() }()
|
|
|
|
if resp.StatusCode != 200 {
|
|
t.Errorf("expected 200, got %d", resp.StatusCode)
|
|
}
|
|
}
|
|
|
|
func TestReadyEndpointNotReady(t *testing.T) {
|
|
ready := false
|
|
srv := New(18082, "/health", "/ready", func() bool { return ready })
|
|
srv.Start()
|
|
defer srv.Stop(context.Background())
|
|
time.Sleep(50 * time.Millisecond)
|
|
|
|
resp, err := http.Get("http://localhost:18082/ready")
|
|
if err != nil {
|
|
t.Fatalf("ready request failed: %v", err)
|
|
}
|
|
_ = resp.Body.Close()
|
|
if resp.StatusCode != 503 {
|
|
t.Errorf("expected 503 when not ready, got %d", resp.StatusCode)
|
|
}
|
|
|
|
ready = true
|
|
resp2, err := http.Get("http://localhost:18082/ready")
|
|
if err != nil {
|
|
t.Fatalf("ready request failed: %v", err)
|
|
}
|
|
_ = resp2.Body.Close()
|
|
if resp2.StatusCode != 200 {
|
|
t.Errorf("expected 200 when ready, got %d", resp2.StatusCode)
|
|
}
|
|
}
|