package gobang import ( "encoding/json" "errors" "log/slog" "os" "strings" "time" "guuid" ) func test_Random() { TestStart("Random()") Testing("we get the desired output size", func() { for i := 0; i < 100; i++ { buffer := Random(i) AssertEqual(len(buffer), i) } }) } func test_sourceInfo() { TestStart("sourceInfo()") Testing("sourceInfo() is defined at...", func() { const FILENAME = "src/gobang.go" info := sourceInfo(1) AssertEqual(info.Key, "src") AssertEqual(len(info.Value.Group()), 3) AssertEqual(info.Value.Group()[0].Key, "file") file := info.Value.Group()[0].Value.String() AssertEqual(file[len(file) - len(FILENAME):], FILENAME) AssertEqual(info.Value.Group()[1].Key, "function") AssertEqual( info.Value.Group()[1].Value.String(), "gobang.sourceInfo", ) AssertEqual(info.Value.Group()[2].Key, "line") AssertEqual(info.Value.Group()[2].Value.Kind(), slog.KindInt64) }) Testing("we're calling it from...", func() { const FILENAME = "tests/gobang.go" info := sourceInfo(2) AssertEqual(info.Key, "src") AssertEqual(len(info.Value.Group()), 3) AssertEqual(info.Value.Group()[0].Key, "file") file := info.Value.Group()[0].Value.String() AssertEqual(file[len(file) - len(FILENAME):], FILENAME) AssertEqual(info.Value.Group()[1].Key, "function") AssertEqual( info.Value.Group()[1].Value.String(), "gobang.test_sourceInfo.func2", ) AssertEqual(info.Value.Group()[2].Key, "line") AssertEqual(info.Value.Group()[2].Value.Kind(), slog.KindInt64) }) } func test_logArgs() { TestStart("logArgs()") Testing("direct string array return", func() { args := logArgs("the-type") AssertEqual(len(args), 6) AssertEqual(args[0], "id") _, err := guuid.FromString(args[1]) ErrorIf(err) expected := []string { "kind", "log", "type", "the-type" } AssertEqual(args[2:], expected) }) } func test_anyArr() { TestStart("anyArr()") Testing("we can turn []string into []any", func() { var input []string = []string { "one", "two", "three" } var given []any = anyArr(input) var expected []any = []any { "one", "two", "three" } AssertEqual(given, expected) }) } func testLog( levelName string, filterLevel LogLevel, fn func(string, string, ...any), ) { savedLogger := slog.Default() savedLevel := level s := new(strings.Builder) SetLoggerOutput(s) level = filterLevel fn("a-message", "a-type", "a-key", "a-value") { var data map[string]interface{} err := json.Unmarshal([]byte(s.String()), &data) ErrorIf(err) timeRaw, ok := data["time"] AssertEqual(ok, true) timeStr, ok := timeRaw.(string) AssertEqual(ok, true) _, err = time.Parse(time.RFC3339, timeStr) ErrorIf(err) levelRaw, ok := data["level"] AssertEqual(ok, true) level, ok := levelRaw.(string) AssertEqual(ok, true) AssertEqual(level, levelName) kindRaw, ok := data["kind"] AssertEqual(ok, true) kind, ok := kindRaw.(string) AssertEqual(ok, true) AssertEqual(kind, "log") msgRaw, ok := data["msg"] AssertEqual(ok, true) msg, ok := msgRaw.(string) AssertEqual(ok, true) AssertEqual(msg, "a-message") typeRaw, ok := data["type"] AssertEqual(ok, true) type_, ok := typeRaw.(string) AssertEqual(ok, true) AssertEqual(type_, "a-type") keyRaw, ok := data["a-key"] AssertEqual(ok, true) key, ok := keyRaw.(string) AssertEqual(ok, true) AssertEqual(key, "a-value") } slog.SetDefault(savedLogger) level = savedLevel } func testNoLog(filterLevel LogLevel, fn func(string, string, ...any)) { savedLogger := slog.Default() savedLevel := level s := new(strings.Builder) SetLoggerOutput(s) level = filterLevel fn("a-message", "a-type", "a-key", "a-value") AssertEqual(s.String(), "") slog.SetDefault(savedLogger) level = savedLevel } func test_Debug() { TestStart("Debug()") Testing("exists in LevelDebug", func() { testLog("DEBUG", LevelDebug, Debug) }) Testing("doesn't in lower levels", func() { testNoLog(LevelInfo, Debug) }) } func test_Info() { TestStart("Info()") Testing("exists in LevelInfo", func() { testLog("INFO", LevelInfo, Info) }) Testing("doesn't in lower levels", func() { testNoLog(LevelWarning, Info) }) } func test_Warning() { TestStart("Warning()") Testing("exists in LevelWarning", func() { testLog("WARN" /* WARNING */, LevelWarning, Warning) }) Testing("doesn't in lower levels", func() { testNoLog(LevelError, Warning) }) } func test_Error() { TestStart("Error()") Testing("exists in LevelError", func() { testLog("ERROR", LevelError, Error) }) Testing("doesn't in lower levels", func() { testNoLog(LevelNone, Error) }) } func test_metric() { TestStart("metric()") Testing("noop when emitMetric is false", func() { savedLogger := slog.Default() savedFlag := emitMetric s := new(strings.Builder) SetLoggerOutput(s) emitMetric = false metric("", "") AssertEqual(s.String(), "") slog.SetDefault(savedLogger) emitMetric = savedFlag }) Testing("JSON entry of kind \"metric\"", func() { savedLogger := slog.Default() savedFlag := emitMetric s := new(strings.Builder) SetLoggerOutput(s) emitMetric = true metric("a-type", "a-label", "count-something", 123) var data map[string]interface{} err := json.Unmarshal([]byte(s.String()), &data) ErrorIf(err) timeRaw, ok := data["time"] AssertEqual(ok, true) timeStr, ok := timeRaw.(string) AssertEqual(ok, true) _, err = time.Parse(time.RFC3339, timeStr) ErrorIf(err) levelRaw, ok := data["level"] AssertEqual(ok, true) level, ok := levelRaw.(string) AssertEqual(ok, true) AssertEqual(level, "INFO") msgRaw, ok := data["msg"] AssertEqual(ok, true) msg, ok := msgRaw.(string) AssertEqual(ok, true) AssertEqual(msg, "_") idRaw, ok := data["id"] AssertEqual(ok, true) id, ok := idRaw.(string) AssertEqual(ok, true) _, err = guuid.FromString(id) ErrorIf(err) kindRaw, ok := data["kind"] AssertEqual(ok, true) kind, ok := kindRaw.(string) AssertEqual(ok, true) AssertEqual(kind, "metric") typeRaw, ok := data["type"] AssertEqual(ok, true) type_, ok := typeRaw.(string) AssertEqual(ok, true) AssertEqual(type_, "a-type") labelRaw, ok := data["label"] AssertEqual(ok, true) label, ok := labelRaw.(string) AssertEqual(ok, true) AssertEqual(label, "a-label") keyRaw, ok := data["count-something"] AssertEqual(ok, true) key, ok := keyRaw.(float64) AssertEqual(ok, true) AssertEqual(int(key), 123) slog.SetDefault(savedLogger) emitMetric = savedFlag }) } func test_MakeCounter() { TestStart("MakeCounter()") Testing("\"value\" is always 1", func() { savedLogger := slog.Default() savedFlag := emitMetric s := new(strings.Builder) SetLoggerOutput(s) emitMetric = true emitTCPError := MakeCounter("emit-tcp-error") emitTCPError("more-data", 555) var data map[string]interface{} err := json.Unmarshal([]byte(s.String()), &data) ErrorIf(err) typeRaw, ok := data["type"] AssertEqual(ok, true) type_, ok := typeRaw.(string) AssertEqual(ok, true) AssertEqual(type_, "counter") labelRaw, ok := data["label"] AssertEqual(ok, true) label, ok := labelRaw.(string) AssertEqual(ok, true) AssertEqual(label, "emit-tcp-error") valueRaw, ok := data["value"] AssertEqual(ok, true) value, ok := valueRaw.(float64) AssertEqual(ok, true) AssertEqual(int(value), 1) keyRaw, ok := data["more-data"] AssertEqual(ok, true) key, ok := keyRaw.(float64) AssertEqual(ok, true) AssertEqual(int(key), 555) slog.SetDefault(savedLogger) emitMetric = savedFlag }) } func test_MakeGauge() { TestStart("MakeGauge()") Testing("errors on underflow", func() { savedLogger := slog.Default() savedLevel := level s := new(strings.Builder) SetLoggerOutput(s) level = LevelError activeTCPConnections := MakeGauge("active-tcp-connections") activeTCPConnections.Dec() { var data map[string]interface{} err := json.Unmarshal([]byte(s.String()), &data) ErrorIf(err) levelRaw, ok := data["level"] AssertEqual(ok, true) level, ok := levelRaw.(string) AssertEqual(ok, true) AssertEqual(level, "ERROR") msgRaw, ok := data["msg"] AssertEqual(ok, true) msg, ok := msgRaw.(string) AssertEqual(ok, true) AssertEqual(msg, "Gauge went negative") kindRaw, ok := data["kind"] AssertEqual(ok, true) kind, ok := kindRaw.(string) AssertEqual(ok, true) AssertEqual(kind, "log") typeRaw, ok := data["type"] AssertEqual(ok, true) type_, ok := typeRaw.(string) AssertEqual(ok, true) AssertEqual(type_, "process-metric") valueRaw, ok := data["value"] AssertEqual(ok, true) value, ok := valueRaw.(float64) AssertEqual(ok, true) AssertEqual(int(value), -1) } slog.SetDefault(savedLogger) level = savedLevel }) Testing("\"value\" grows monotonically", func() { savedLogger := slog.Default() savedFlag := emitMetric s := new(strings.Builder) SetLoggerOutput(s) emitMetric = true activeTCPConnections := MakeGauge("active-tcp-connections") activeTCPConnections.Inc() activeTCPConnections.Inc() activeTCPConnections.Dec() activeTCPConnections.Inc() activeTCPConnections.Inc("more-data", 999) strs := strings.Split(s.String(), "\n") AssertEqual(len(strs), 6) AssertEqual(strs[5], "") var data map[string]interface{} err := json.Unmarshal([]byte(strs[len(strs) - 2]), &data) ErrorIf(err) typeRaw, ok := data["type"] AssertEqual(ok, true) type_, ok := typeRaw.(string) AssertEqual(ok, true) AssertEqual(type_, "gauge") labelRaw, ok := data["label"] AssertEqual(ok, true) label, ok := labelRaw.(string) AssertEqual(ok, true) AssertEqual(label, "active-tcp-connections") valueRaw, ok := data["value"] AssertEqual(ok, true) value, ok := valueRaw.(float64) AssertEqual(ok, true) AssertEqual(int(value), 3) keyRaw, ok := data["more-data"] AssertEqual(ok, true) key, ok := keyRaw.(float64) AssertEqual(ok, true) AssertEqual(int(key), 999) slog.SetDefault(savedLogger) emitMetric = savedFlag }) } func test_ErrorIf() { TestStart("ErrorIf()") Testing("noop on nil value", func() { ErrorIf(nil) }) } func test_ErrorNil() { TestStart("ErrorNil()") Testing("noop on thruthy value", func() { ErrorNil(errors.New("some error")) }) } func test_showColour() { TestStart("showColour()") const NAME = "NO_COLOUR" savedEnvvar := os.Getenv(NAME) Testing("true when envvar is unset", func() { ErrorIf(os.Unsetenv(NAME)) AssertEqual(showColour(), true) }) Testing("true when envvar is empty", func() { ErrorIf(os.Setenv(NAME, "")) AssertEqual(showColour(), true) }) Testing("false otherwise", func() { ErrorIf(os.Setenv(NAME, "1")) AssertEqual(showColour(), false) }) ErrorIf(os.Setenv(NAME, savedEnvvar)) } func test_SetLoggerOutput() { TestStart("SetLoggerOutput()") savedLogger := slog.Default() Testing("the output JSON has data under \"src\"", func() { s := new(strings.Builder) SetLoggerOutput(s) Info("", "") var data map[string]interface{} err := json.Unmarshal([]byte(s.String()), &data) ErrorIf(err) srcRaw, ok := data["src"] AssertEqual(ok, true) src, ok := srcRaw.(map[string]interface{}) AssertEqual(ok, true) fileRaw, ok := src["file"] AssertEqual(ok, true) file, ok := fileRaw.(string) AssertEqual(ok, true) const FILENAME = "tests/gobang.go" AssertEqual(file[len(file) - len(FILENAME):], FILENAME) functionRaw, ok := src["function"] AssertEqual(ok, true) function, ok := functionRaw.(string) AssertEqual(ok, true) AssertEqual(function, "gobang.test_SetLoggerOutput.func1") lineRaw, ok := src["line"] AssertEqual(ok, true) _, ok = lineRaw.(float64) AssertEqual(ok, true) }) Testing("the output JSON has data under \"info\"", func() { s := new(strings.Builder) SetLoggerOutput(s) Info("", "") var data map[string]interface{} err := json.Unmarshal([]byte(s.String()), &data) ErrorIf(err) infoRaw, ok := data["info"] AssertEqual(ok, true) info, ok := infoRaw.(map[string]interface{}) AssertEqual(ok, true) pidRaw, ok := info["pid"] AssertEqual(ok, true) pid, ok := pidRaw.(float64) AssertEqual(ok, true) AssertEqual(int(pid), os.Getpid()) ppidRaw, ok := info["ppid"] AssertEqual(ok, true) ppid, ok := ppidRaw.(float64) AssertEqual(ok, true) AssertEqual(int(ppid), os.Getppid()) puuidRaw, ok := info["puuid"] AssertEqual(ok, true) puuid, ok := puuidRaw.(string) AssertEqual(ok, true) _, err = guuid.FromString(puuid) ErrorIf(err) }) Testing("we can add groups to the default logger", func() { s := new(strings.Builder) SetLoggerOutput(s, slog.Group("one", "key", "value")) Info("", "") var data map[string]interface{} err := json.Unmarshal([]byte(s.String()), &data) ErrorIf(err) oneRaw, ok := data["one"] AssertEqual(ok, true) one, ok := oneRaw.(map[string]interface{}) AssertEqual(ok, true) keyRaw, ok := one["key"] AssertEqual(ok, true) key, ok := keyRaw.(string) AssertEqual(key, "value") }) Testing("the puuid is the same across calls to the logger", func() { s := new(strings.Builder) SetLoggerOutput(s) Info("", "first") Info("", "second") strs := strings.Split(s.String(), "\n") AssertEqual(len(strs), 3) AssertEqual(strs[2], "") log1 := strs[0] log2 := strs[1] var puuidFromString = func(str string) string { var data map[string]interface{} err := json.Unmarshal([]byte(str), &data) ErrorIf(err) infoRaw, ok := data["info"] AssertEqual(ok, true) info, ok := infoRaw.(map[string]interface{}) AssertEqual(ok, true) puuidRaw, ok := info["puuid"] AssertEqual(ok, true) puuid, ok := puuidRaw.(string) AssertEqual(ok, true) return puuid } puuid1 := puuidFromString(log1) puuid2 := puuidFromString(log2) AssertEqual(puuid1, puuid2) uuid1, err := guuid.FromString(puuid1) ErrorIf(err) uuid2, err := guuid.FromString(puuid2) ErrorIf(err) AssertEqual(uuid1, uuid2) }) slog.SetDefault(savedLogger) } func test_levelFromString() { TestStart("levelFromString()") values := []string { "NONE", "ERROR", "WARNING", "INFO", "DEBUG" } Testing("ok for expected values", func() { for _, s := range values { var fallback LogLevel = 123 theLevel := levelFromString(s, fallback) notFallback := theLevel >= LevelNone && theLevel <= LevelDebug && theLevel != fallback AssertEqual(notFallback, true) } }) Testing("fallback for unexpected values", func() { var fallback LogLevel = 123 theLevel := levelFromString(string(Random(10)), fallback) AssertEqual(theLevel, fallback) }) } func test_setLogLevel() { TestStart("setLogLevel()") const NAME = "LOG_LEVEL" savedEnvvar := os.Getenv(NAME) savedValue := level var fallbackValue LogLevel = 123 Testing("noop when envvar is unset", func() { ErrorIf(os.Unsetenv(NAME)) level = fallbackValue setLogLevel() AssertEqual(level, fallbackValue) }) Testing("noop when envvar is empty", func() { ErrorIf(os.Setenv(NAME, "")) level = fallbackValue setLogLevel() AssertEqual(level, fallbackValue) }) Testing("update variable otherwise", func() { ErrorIf(os.Setenv(NAME, "DEBUG")) level = fallbackValue setLogLevel() AssertEqual(level, LevelDebug) }) ErrorIf(os.Setenv(NAME, savedEnvvar)) level = savedValue } func test_SetLevel() { TestStart("SetLevel()") savedValue := level Testing("the behaviour is a simple assignment", func() { levels := []LogLevel { LevelNone, LevelError, LevelWarning, LevelInfo, LevelDebug, } for _, l := range levels { SetLevel(l) AssertEqual(l, level) } }) level = savedValue } func test_setMetric() { TestStart("setMetric()") const NAME = "NO_METRIC" savedEnvvar := os.Getenv(NAME) savedValue := emitMetric Testing("noop when envvar is unset", func() { ErrorIf(os.Unsetenv(NAME)) emitMetric = true setMetric() AssertEqual(emitMetric, true) }) Testing("noop when envvar is empty", func() { ErrorIf(os.Setenv(NAME, "")) emitMetric = true setMetric() AssertEqual(emitMetric, true) }) Testing("make variable false otherwise", func() { ErrorIf(os.Setenv(NAME, "1")) emitMetric = true setMetric() AssertEqual(emitMetric, false) }) ErrorIf(os.Setenv(NAME, savedEnvvar)) emitMetric = savedValue } func test_FatalIf() { TestStart("FatalIf()") Testing("noop on nil value", func() { FatalIf(nil) }) } func test_Assert() { TestStart("Assert()") Testing("noop on true value", func() { Assert(true, "") }) } func test_setHostname() { TestStart("setHostname()") Testing("it assigns the value to the global variable", func() { name, _ := os.Hostname() hostname = "" setHostname() AssertEqual(hostname, name) }) } func MainTest() { test_Random() test_sourceInfo() test_logArgs() test_anyArr() test_Debug() test_Info() test_Warning() test_Error() test_metric() test_MakeCounter() test_MakeGauge() test_ErrorIf() test_ErrorNil() test_showColour() test_SetLoggerOutput() test_levelFromString() test_setLogLevel() test_SetLevel() test_setMetric() test_FatalIf() test_Assert() test_setHostname() }