From e9ce24ff2884b81b75c74c87c94931833e081338 Mon Sep 17 00:00:00 2001 From: Markus Opolka Date: Mon, 23 Dec 2024 09:51:49 +0100 Subject: [PATCH] Add helper function to transform string states into int states --- status.go | 23 +++++++++++++++++++++++ status_test.go | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/status.go b/status.go index 9c43e44..b51babf 100644 --- a/status.go +++ b/status.go @@ -1,5 +1,9 @@ package check +import ( + "strings" +) + const ( // OK means everything is fine OK = 0 @@ -29,3 +33,22 @@ func StatusText(status int) string { return UnknownString } + +// StatusText returns a state corresponding to its +// common string representation +func StatusInt(status string) int { + status = strings.ToUpper(status) + + switch status { + case OKString, "0": + return OK + case WarningString, "1": + return Warning + case CriticalString, "2": + return Critical + case UnknownString, "3": + return Unknown + default: + return Unknown + } +} diff --git a/status_test.go b/status_test.go index d2f2377..e2f555a 100644 --- a/status_test.go +++ b/status_test.go @@ -37,3 +37,41 @@ func TestStatusText(t *testing.T) { }) } } + +func TestStatusInt(t *testing.T) { + testcases := map[string]struct { + input string + expected int + }{ + "OK": { + expected: 0, + input: "OK", + }, + "WARNING": { + expected: 1, + input: "warning", + }, + "CRITICAL": { + expected: 2, + input: "Critical", + }, + "UNKNOWN": { + expected: 3, + input: "unknown", + }, + "Invalid-Input": { + expected: 3, + input: "Something else", + }, + } + + for name, tc := range testcases { + t.Run(name, func(t *testing.T) { + actual := StatusInt(tc.input) + + if actual != tc.expected { + t.Error("\nActual: ", actual, "\nExpected: ", tc.expected) + } + }) + } +}