package gobang import ( "encoding/json" "errors" "fmt" "log/slog" "os" "strings" "time" "guuid" ) func test_ValidateSQLTablePrefix() { TestStart("ValidateSQLTablePrefix()") Testing("simple identifiers are good", func() { input := []string{ "simple", "id", "g00d", "VERY_GOOD", } for _, given := range input { TAssertEqual(ValidateSQLTablePrefix(given), nil) } }) Testing("nothing fancy is allowed", func() { input := []string{ "a-table", "0t", "", "thing\"", "*symbol", "symbol*", } for _, given := range input { TAssertEqual( ValidateSQLTablePrefix(given), ErrBadSQLTablePrefix, ) } }) } func test_WrapErrors() { TestStart("WrapErrors()") Testing("nil for empty args", func() { TAssertEqual(WrapErrors(), nil) }) Testing("nil when all args are nil", func() { TAssertEqual(WrapErrors(nil, nil, nil), nil) }) Testing("if only 1 is an error, return it", func() { err := errors.New("my error") TAssertEqual(WrapErrors(nil, nil, err), err) }) Testing("otherwise wrap them, from right to left", func() { err1 := errors.New("error 1") err2 := errors.New("error 2") expected1 := fmt.Errorf("error %w on top of %w", err1, err2) expected2 := fmt.Errorf("error %w on top of %w", err2, err1) TAssertEqual(WrapErrors(nil, err1, nil, err2), expected1) TAssertEqual(WrapErrors(err2, nil, nil, err1), expected2) }) } func test_SomeError() { TestStart("SomeError()") Testing("an empty array is nil", func() { TAssertEqual(SomeError(), nil) }) Testing("only nil values is nil", func() { TAssertEqual(SomeError(nil, nil, nil), nil) }) Testing("we get the first non-nil value", func() { err1 := errors.New("error 1") err2 := errors.New("error 2") TAssertEqual(SomeError(nil, err1, err2), err1) }) } func test_SomeFnError() { TestStart("SomeFnError()") Testing("an empty arrays is also nil", func() { TAssertEqual(SomeFnError(), nil) }) Testing("all functions are called", func() { i := 0 fn := func() error { i++ return nil } TAssertEqual(SomeFnError(fn, fn, fn), nil) TAssertEqual(i, 3) }) Testing("we call all functions even if we get an error", func() { i := 0 errs := []error{ nil, nil, errors.New("fn error 2"), errors.New("fn error 3"), nil, } fn := func() error { i++ return errs[i] } TAssertEqual(SomeFnError(fn, fn, fn, fn), errs[2]) TAssertEqual(i, 4) }) } func test_Random() { TestStart("Random()") Testing("we get the desired output size", func() { for i := 0; i < 100; i++ { buffer := Random(i) TAssertEqual(len(buffer), i) } }) } func test_sourceInfo() { TestStart("sourceInfo()") Testing("sourceInfo() is defined at...", func() { const FILENAME = "src/gobang.go" info := sourceInfo(1) TAssertEqual(info.Key, "src") TAssertEqual(len(info.Value.Group()), 3) TAssertEqual(info.Value.Group()[0].Key, "file") file := info.Value.Group()[0].Value.String() TAssertEqual(file[len(file) - len(FILENAME):], FILENAME) TAssertEqual(info.Value.Group()[1].Key, "function") TAssertEqual( info.Value.Group()[1].Value.String(), "gobang.sourceInfo", ) TAssertEqual(info.Value.Group()[2].Key, "line") TAssertEqual(info.Value.Group()[2].Value.Kind(), slog.KindInt64) }) Testing("we're calling it from...", func() { const FILENAME = "tests/gobang.go" info := sourceInfo(2) TAssertEqual(info.Key, "src") TAssertEqual(len(info.Value.Group()), 3) TAssertEqual(info.Value.Group()[0].Key, "file") file := info.Value.Group()[0].Value.String() TAssertEqual(file[len(file) - len(FILENAME):], FILENAME) TAssertEqual(info.Value.Group()[1].Key, "function") TAssertEqual( info.Value.Group()[1].Value.String(), "gobang.test_sourceInfo.func2", ) TAssertEqual(info.Value.Group()[2].Key, "line") TAssertEqual(info.Value.Group()[2].Value.Kind(), slog.KindInt64) }) } func test_logArgs() { TestStart("logArgs()") Testing("direct string array return", func() { args := logArgs("the-type") TAssertEqual(len(args), 6) TAssertEqual(args[0], "id") _, err := guuid.FromString(args[1]) TErrorIf(err) expected := []string { "kind", "log", "type", "the-type" } TAssertEqual(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" } TAssertEqual(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) TErrorIf(err) _, err = time.Parse(time.RFC3339, data["time"].(string)) TErrorIf(err) TAssertEqual(data["level"].(string), levelName) TAssertEqual(data["kind" ].(string), "log") TAssertEqual(data["msg" ].(string), "a-message") TAssertEqual(data["type" ].(string), "a-type") TAssertEqual(data["a-key"].(string), "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") TAssertEqual(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("", "") TAssertEqual(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) TErrorIf(err) timeStr := data["time"].(string) _, err = time.Parse(time.RFC3339, timeStr) TErrorIf(err) _, err = guuid.FromString(data["id"].(string)) TErrorIf(err) TAssertEqual(data["level"].(string), "INFO") TAssertEqual(data["msg" ].(string), "_") TAssertEqual(data["kind" ].(string), "metric") TAssertEqual(data["type" ].(string), "a-type") TAssertEqual(data["label"].(string), "a-label") TAssertEqual(int(data["count-something"].(float64)), 123) slog.SetDefault(savedLogger) emitMetric = savedFlag }) } func test_Timed() { TestStart("Timed()") Testing("we can use a noop thunk", func() { savedLogger := slog.Default() savedFlag := emitMetric s := new(strings.Builder) SetLoggerOutput(s) emitMetric = true Timed("timer-label", func() {}, "key-1", "value-1") var data map[string]interface{} err := json.Unmarshal([]byte(s.String()), &data) TErrorIf(err) TAssertEqual(data["type"].(string), "timer") TAssertEqual(data["label"].(string), "timer-label") TAssertEqual(data["key-1"].(string), "value-1") var ok bool _, ok = data["start"].(string) TAssertEqual(ok, true) _, ok = data["end"].(string) TAssertEqual(ok, true) _, ok = data["duration"].(float64) TAssertEqual(ok, true) 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) TErrorIf(err) TAssertEqual(data["type" ].(string), "counter") TAssertEqual(data["label"].(string), "emit-tcp-error") TAssertEqual(int(data["value" ].(float64)), 1) TAssertEqual(int(data["more-data"].(float64)), 555) slog.SetDefault(savedLogger) emitMetric = savedFlag }) Testing("we have static and dynamic args", func() { savedLogger := slog.Default() savedFlag := emitMetric s := new(strings.Builder) SetLoggerOutput(s) emitMetric = true emitTCPError := MakeCounter("label-1", "key-1", "value-1") emitTCPError("key-2", "value-2") var data map[string]interface{} err := json.Unmarshal([]byte(s.String()), &data) TErrorIf(err) TAssertEqual(data["type"].(string), "counter") TAssertEqual(data["label"].(string), "label-1") TAssertEqual(data["key-1"].(string), "value-1") TAssertEqual(data["key-2"].(string), "value-2") 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) TErrorIf(err) TAssertEqual(data["level"].(string), "ERROR") TAssertEqual(data["msg" ].(string), "Gauge went negative") TAssertEqual(data["kind" ].(string), "log") TAssertEqual(data["type" ].(string), "process-metric") TAssertEqual(int(data["value"].(float64)), -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") TAssertEqual(len(strs), 6) TAssertEqual(strs[5], "") var data map[string]interface{} err := json.Unmarshal([]byte(strs[len(strs) - 2]), &data) TErrorIf(err) TAssertEqual(data["type" ].(string), "gauge") TAssertEqual(data["label"].(string), "active-tcp-connections") TAssertEqual(int(data["value" ].(float64)), 3) TAssertEqual(int(data["more-data"].(float64)), 999) slog.SetDefault(savedLogger) emitMetric = savedFlag }) } func test_showColour() { TestStart("showColour()") const NAME = "NO_COLOUR" savedEnvvar := os.Getenv(NAME) defer os.Setenv(NAME, savedEnvvar) Testing("true when envvar is unset", func() { TErrorIf(os.Unsetenv(NAME)) TAssertEqual(showColour(), true) }) Testing("true when envvar is empty", func() { TErrorIf(os.Setenv(NAME, "")) TAssertEqual(showColour(), true) }) Testing("false otherwise", func() { TErrorIf(os.Setenv(NAME, "1")) TAssertEqual(showColour(), false) }) } func test_TestStart() { TestStart("TestStart()") Testing("simply writes the given name to `testOutput`", func() { w := new(strings.Builder) savedOutput := testOutput testOutput = w TestStart("theFunctionName()") TestStart("typeT.Method()") TestStart("variable") testOutput = savedOutput const expected = "theFunctionName():\n" + "typeT.Method():\n" + "variable:\n" TAssertEqual(w.String(), expected) }) } func withSavedColour() func() { println("antes") const NAME = "NO_COLOUR" savedEnvvar := os.Getenv(NAME) return func() { println("depois") os.Setenv(NAME, savedEnvvar) } } func test_Testing() { TestStart("Testing()") Testing("tries to write a successful report of the test", func() { defer withSavedColour()() w := new(strings.Builder) savedOutput := testOutput testOutput = w TErrorIf(os.Unsetenv("NO_COLOUR")) Testing("colored description goes here", func() {}) TErrorIf(os.Setenv("NO_COLOUR", "true")) Testing("uncolored description goes here", func() {}) testOutput = savedOutput const expected = "\033[0;33mtesting\033[0m: " + "colored description goes here... " + "\033[0;32mOK\033[0m.\n" + "testing: uncolored description goes here... OK.\n" TAssertEqual(w.String(), expected) }) } func test_terr() { TestStart("terr()") Testing("emits a failure string report", func() { defer withSavedColour()() w1 := new(strings.Builder) w2 := new(strings.Builder) savedOutput := testOutput TErrorIf(os.Unsetenv("NO_COLOUR")) testOutput = w1 terr() TErrorIf(os.Setenv("NO_COLOUR", "1")) testOutput = w2 terr() testOutput = savedOutput const expected1 = "\033[0;31mERR\033[0m (" const expected2 = "ERR (" const suffix = ").\n" TAssertEqual(strings.HasPrefix(w1.String(), expected1), true) TAssertEqual(strings.HasPrefix(w2.String(), expected2), true) TAssertEqual(strings.HasSuffix(w1.String(), suffix), true) TAssertEqual(strings.HasSuffix(w2.String(), suffix), true) }) } func test_TAssertEqual() { // FIXME } func test_TAssertEqualS() { // FIXME } func test_TAssertEqualI() { // FIXME } func test_TErrorIf() { TestStart("TErrorIf()") Testing("noop on nil value", func() { exitFn := func(val int) { panic(val) } w := new(strings.Builder) savedExitFn := testExitFn savedOutput := testOutput testExitFn = exitFn testOutput = w TErrorIf(nil) testExitFn = savedExitFn testOutput = savedOutput TAssertEqual(w.String(), "") }) Testing("simple dynamic message plus exit code", func() { myErr := errors.New("unexpected error") myStr := fmt.Sprintf("%#v", myErr) var n int exitFn := func(val int) { n = val } w := new(strings.Builder) savedExitFn := testExitFn savedOutput := testOutput testExitFn = exitFn testOutput = w TErrorIf(myErr) testExitFn = savedExitFn testOutput = savedOutput given := strings.Split(w.String(), "\n")[1] TAssertEqual(n, 100) TAssertEqual(given, "Unexpected error: " + myStr) }) } func test_TErrorNil() { TestStart("TErrorNil()") Testing("noop on thruthy value", func() { exitFn := func(val int) { panic(val) } w := new(strings.Builder) savedExitFn := testExitFn savedOutput := testOutput testExitFn = exitFn testOutput = w TErrorNil(errors.New("some error")) testExitFn = savedExitFn testOutput = savedOutput TAssertEqual(w.String(), "") }) Testing("simple message with special exit code", func() { var n int exitFn := func(val int) { n = val } w := new(strings.Builder) savedExitFn := testExitFn savedOutput := testOutput testExitFn = exitFn testOutput = w TErrorNil(nil) testExitFn = savedExitFn testOutput = savedOutput given := strings.Split(w.String(), "\n")[1] TAssertEqual(n, 100) TAssertEqual(given, "Expected error, got nil") }) } func test_SetLoggerOutput() { TestStart("SetLoggerOutput()") savedLogger := slog.Default() Testing("the output JSON has data under \"src\"", func() { saved := SourceInfoSkip SourceInfoSkip = 3 s := new(strings.Builder) SetLoggerOutput(s) Info("", "") var data map[string]interface{} err := json.Unmarshal([]byte(s.String()), &data) TErrorIf(err) src := data["src"].(map[string]interface{}) file := src["file"].(string) const FILENAME = "tests/gobang.go" TAssertEqual(file[len(file) - len(FILENAME):], FILENAME) TAssertEqual(src["function"].(string), "gobang.test_SetLoggerOutput.func1") line := src["line"].(float64) TAssertEqual(line > 0, true) SourceInfoSkip = saved }) 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) TErrorIf(err) info := data["info"].(map[string]interface{}) TAssertEqual(int(info["pid" ].(float64)), os.Getpid()) TAssertEqual(int(info["ppid"].(float64)), os.Getppid()) _, err = guuid.FromString(info["puuid"].(string)) TErrorIf(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) TErrorIf(err) TAssertEqual(data["one"].(map[string]interface{})["key"].(string), "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") TAssertEqual(len(strs), 3) TAssertEqual(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) TErrorIf(err) return data["info"].(map[string]interface{})["puuid"].(string) } puuid1 := puuidFromString(log1) puuid2 := puuidFromString(log2) TAssertEqual(puuid1, puuid2) uuid1, err := guuid.FromString(puuid1) TErrorIf(err) uuid2, err := guuid.FromString(puuid2) TErrorIf(err) TAssertEqual(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 TAssertEqual(notFallback, true) } }) Testing("fallback for unexpected values", func() { var fallback LogLevel = 123 theLevel := levelFromString(string(Random(10)), fallback) TAssertEqual(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() { TErrorIf(os.Unsetenv(NAME)) level = fallbackValue setLogLevel() TAssertEqual(level, fallbackValue) }) Testing("noop when envvar is empty", func() { TErrorIf(os.Setenv(NAME, "")) level = fallbackValue setLogLevel() TAssertEqual(level, fallbackValue) }) Testing("update variable otherwise", func() { TErrorIf(os.Setenv(NAME, "DEBUG")) level = fallbackValue setLogLevel() TAssertEqual(level, LevelDebug) }) TErrorIf(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) TAssertEqual(l, level) } }) level = savedValue } func test_setMetric() { TestStart("setMetric()") const NAME = "NO_METRIC" savedEnvvar := os.Getenv(NAME) savedValue := emitMetric defer func() { TErrorIf(os.Setenv(NAME, savedEnvvar)) emitMetric = savedValue }() Testing("noop when envvar is unset", func() { TErrorIf(os.Unsetenv(NAME)) emitMetric = true setMetric() TAssertEqual(emitMetric, true) }) Testing("noop when envvar is empty", func() { TErrorIf(os.Setenv(NAME, "")) emitMetric = true setMetric() TAssertEqual(emitMetric, true) }) Testing("make variable false otherwise", func() { TErrorIf(os.Setenv(NAME, "1")) emitMetric = true setMetric() TAssertEqual(emitMetric, false) }) } func test_setHostname() { TestStart("setHostname()") Testing("it assigns the value to the global variable", func() { name, _ := os.Hostname() hostname = "" setHostname() TAssertEqual(hostname, name) }) } func MainTest() { test_ValidateSQLTablePrefix() test_WrapErrors() test_SomeError() test_SomeFnError() test_Random() test_sourceInfo() test_logArgs() test_anyArr() test_Debug() test_Info() test_Warning() test_Error() test_metric() test_Timed() test_MakeCounter() test_MakeGauge() test_showColour() test_TestStart() test_Testing() test_terr() test_TAssertEqual() test_TAssertEqualS() test_TAssertEqualI() test_TErrorIf() test_TErrorNil() test_SetLoggerOutput() test_levelFromString() test_setLogLevel() test_SetLevel() test_setMetric() test_setHostname() }