From f19107d9a80a0cc15a9c5920fadba5b0a7dcb6fe Mon Sep 17 00:00:00 2001 From: Paul Buetow Date: Mon, 6 May 2024 19:20:32 +0300 Subject: add health unit test --- health.go | 35 ++++++++++++++++++++++++++++++++--- health_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 3 deletions(-) create mode 100644 health_test.go 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) +} -- cgit v1.2.3