summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPaul Buetow <paul@buetow.org>2024-05-06 19:20:32 +0300
committerPaul Buetow <paul@buetow.org>2024-05-06 19:20:32 +0300
commitf19107d9a80a0cc15a9c5920fadba5b0a7dcb6fe (patch)
tree5101191dd4ee84d1a2a6ae87ebc2e109c3d9f5e6
parente36a175fa09a983d3438212be8ca116adfa2b4ec (diff)
add health unit test
-rw-r--r--health.go35
-rw-r--r--health_test.go24
2 files changed, 56 insertions, 3 deletions
diff --git a/health.go b/health.go
index 39685b1..2dd2322 100644
--- a/health.go
+++ b/health.go
@@ -1,6 +1,10 @@
package main
-import "strings"
+import (
+ "fmt"
+ "strings"
+ "sync"
+)
type alertSeverity int
@@ -31,8 +35,13 @@ type alert struct {
severity alertSeverity
}
+func (a alert) String() string {
+ return fmt.Sprintf("%s: %s", a.severity, a.text)
+}
+
type healthStatus struct {
alerts map[string]alert
+ mu sync.Mutex
}
func newHealthStatus() healthStatus {
@@ -41,17 +50,37 @@ func newHealthStatus() healthStatus {
}
}
+func (hs healthStatus) set(s alertSeverity, what, text string) {
+ hs.mu.Lock()
+ defer hs.mu.Unlock()
+
+ hs.alerts[what] = alert{
+ text: text,
+ severity: s,
+ }
+}
+
+func (hs healthStatus) clear(what string) {
+ hs.mu.Lock()
+ defer hs.mu.Unlock()
+
+ delete(hs.alerts, what)
+}
+
func (hs healthStatus) String() string {
var (
alertsBySeverity [4][]string
sb strings.Builder
)
+ hs.mu.Lock()
+ defer hs.mu.Unlock()
+
for _, alert := range hs.alerts {
- alertsBySeverity[alert.severity] = append(alertsBySeverity[alert.severity], alert.text)
+ alertsBySeverity[alert.severity] = append(alertsBySeverity[alert.severity], alert.String())
}
- possible := [4]alertSeverity{ok, warning, critical, unknown}
+ possible := [4]alertSeverity{unknown, critical, warning, ok}
for _, severity := range possible {
if len(alertsBySeverity[severity]) == 0 {
continue
diff --git a/health_test.go b/health_test.go
new file mode 100644
index 0000000..8dc35bc
--- /dev/null
+++ b/health_test.go
@@ -0,0 +1,24 @@
+package main
+
+import "testing"
+
+func TestHealthStatus(t *testing.T) {
+ t.Parallel()
+
+ h := newHealthStatus()
+ h.set(warning, "fooService", "this is not good")
+ h.set(critical, "barService", "this is not good either")
+ h.set(warning, "bazService", "urgh!")
+ h.set(unknown, "bazService", "don't know what happened here!")
+ h.clear("fooService")
+
+ result := h.String()
+ expected := `UNKNOWN: don't know what happened here!
+CRITICAL: this is not good either
+`
+
+ if result != expected {
+ t.Error("expected", expected, "but got", result)
+ }
+ t.Log("got as expexted", result)
+}