package gobang import ( "encoding/json" "errors" "fmt" "log/slog" "os" "slices" "strings" "time" "guuid" ) func test_SetOf() { TestStart("SetOf()") Testing("empty set", func() { expected := SetT[int]{ data: map[int]struct{}{ }, } TAssertEqual(SetOf[int](), expected) }) Testing("equal sets", func() { expected := SetT[int]{ data: map[int]struct{}{ 1: struct{}{}, 2: struct{}{}, 3: struct{}{}, }, } TAssertEqual(SetOf(1, 2, 3), expected) }) } func test_Contains() { TestStart("Contains()") Testing("trivial example usage", func() { s := SetOf(1, 2, 3, 4, 5) TAssertEqual(Contains(s, 0), false) TAssertEqual(Contains(s, 1), true) TAssertEqual(Contains(s, 5), true) TAssertEqual(Contains(s, 6), false) }) } func test_MapIndexed() { TestStart("MapIndexed()") Testing("empty array", func() { noop := func(s string, i int) string { return s } arr := []string{} TAssertEqual(MapIndexed(noop, arr), arr) }) Testing("replace content with index", func() { index := func(s string, i int) int { return i } TAssertEqual( MapIndexed(index, []string{"a", "b", "c"}), []int{0, 1, 2}, ) }) Testing("a computed value", func() { fn := func(x int, i int) int { return x + i } TAssertEqual( MapIndexed(fn, []int{1, 2, 3, 4, 5}), []int{1, 3, 5, 7, 9}, ) }) } func test_Map() { TestStart("Map()") Testing("empty array", func() { noop := func(s string) string { return s } arr := []string{} TAssertEqual(Map(noop, arr), arr) }) Testing("a derived value", func() { appendBang := func(s string) string { return s + "!" } TAssertEqual( Map(appendBang, []string{"a", "b", "c"}), []string{"a!", "b!", "c!"}, ) }) } func test_Filter() { TestStart("Filter()") fn := func(i int) bool { return i < 10 } Testing("empty array", func() { arr := []int{} TAssertEqual(Filter(fn, arr), arr) }) Testing("filters everything", func() { arr := []int{10, 11, 12, 13, 14, 15} TAssertEqual(Filter(fn, arr), []int{}) }) Testing("filters nothing", func() { arr := []int{1, 2, 3, 4, 5} TAssertEqual(Filter(fn, arr), arr) }) Testing("filters some", func() { TAssertEqual( Filter(fn, []int{8, 9, 10, 11, 12, 0, 13}), []int{8, 9, 0}, ) }) } func test_PanicIf() { TestStart("PanicIf()") myErr := errors.New("test error") Testing("noop when error is nil", func() { var err error PanicIf(err) PanicIf(nil) }) Testing("panic when we have an error", func() { defer func() { TAssertEqual(recover(), myErr) }() PanicIf(myErr) TErrorNil(nil) }) } func test_Must() { TestStart("Must()") myErr := errors.New("test error") f := func(shouldError bool) (string, error) { if shouldError { return "UNSEEN", myErr } return "no error", nil } Testing("value when error is nil", func() { TAssertEqual(Must(f(false)), "no error") }) Testing("panic when we have an error", func() { defer func() { TAssertEqual(recover(), myErr) }() Must(f(true)) TErrorNil(nil) }) } func test_Clamp() { TestStart("Clamp()") Testing("equal values", func() { TAssertEqual(Clamp(0, 0, 0), 0) TAssertEqual(Clamp(1, 1, 1), 1) TAssertEqual(Clamp(1.0, 1.0, 1.0), 1.0) }) Testing("within range", func() { TAssertEqual(Clamp(5, 0, 10), 5) TAssertEqual(Clamp(1.1, 1.0, 1.2), 1.1) TAssertEqual(Clamp(0, 0, 10), 0) TAssertEqual(Clamp(10, 0, 10), 10) }) Testing("lower than min", func() { TAssertEqual(Clamp(1, 2, 3), 2) TAssertEqual(Clamp(1.0, 1.1, 1.2), 1.1) }) Testing("greater than max", func() { TAssertEqual(Clamp(1, 11, 10), 10) TAssertEqual(Clamp(1.2, 1.0, 1.1), 1.1) }) } 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) }) Testing("no error if some function is nil", func() { myErr := errors.New("the expected result") TAssertEqual(SomeFnError( func() error { return nil }, nil, func() error { return nil }, func() error { return myErr }, func() error { return nil }, ), myErr) }) } func test_Random() { TestStart("Random()") Testing("we get the desired output size", func() { for i := 0; i < 100; i++ { buffer, err := Random(i) TErrorIf(err) TAssertEqual(len(buffer), i) } }) Testing("error on bad randomReader value", func() { savedReader := randomReader randomReader = strings.NewReader("abc") rand1, err1 := Random(3) rand2, err2 := Random(3) TErrorIf(err1) TErrorNil(err2) TAssertEqual(rand1, []byte{ 0x61, 0x62, 0x63 }) TAssertEqual(rand2, []byte(nil)) randomReader = savedReader }) } 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() { const NAME = "NO_COLOUR" savedEnvvar := os.Getenv(NAME) return func() { 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() { TestStart("TAssertEqual()") Testing("noop on equal things", func() { TAssertEqual(1, 1) TAssertEqual("s", "s") TAssertEqual([]byte{ 0x12 }, []byte{ 0x12 }) }) Testing("fail on unequal", func() { var n int exitFn := func(val int) { n = val } w := new(strings.Builder) savedExitFn := testExitFn savedOutput := testOutput testExitFn = exitFn testOutput = w TAssertEqual([]byte(nil), nil) testExitFn = savedExitFn testOutput = savedOutput given := strings.Split(w.String(), "\n")[1:] TAssertEqual(n, 100) TAssertEqual(given, []string{ "given != expected", "given: []byte(nil)", "expected: ", "", }) }) } func test_TAssertEqualS() { TestStart("TAssertEqualS()") Testing("noop for equal things", func() { TAssertEqualS(true, true, "ignored") }) Testing("fail with message on unequal", func() { var n int exitFn := func(val int) { n = val } w := new(strings.Builder) savedExitFn := testExitFn savedOutput := testOutput testExitFn = exitFn testOutput = w TAssertEqualS("a", []byte("a"), "custom string") testExitFn = savedExitFn testOutput = savedOutput given := strings.Split(w.String(), "\n")[1:] TAssertEqual(n, 100) TAssertEqual(given, []string{ "message: custom string", "given != expected", "given: \"a\"", "expected: []byte{0x61}", "", }) }) } func test_TAssertEqualI() { TestStart("TAssertEqualI()") Testing("noop for equal slices", func() { TAssertEqualI([]string{}, []string{}) TAssertEqualI([]string{"", "a", "b"}, []string{"", "a", "b"}) }) Testing("fail when `given` has less elements", func() { var n int exitFn := func(val int) { n = val } w := new(strings.Builder) savedExitFn := testExitFn savedOutput := testOutput testExitFn = exitFn testOutput = w TAssertEqualI([]string{"a"}, []string{"a", "b", "c"}) testExitFn = savedExitFn testOutput = savedOutput given := strings.Split(w.String(), "\n")[1:] TAssertEqual(n, 100) TAssertEqual(given, []string{ "expected has 2 more elements:", `[]string{"b", "c"}`, "", }) }) Testing("fail when `given` has more elements", func() { var n int exitFn := func(val int) { n = val } w := new(strings.Builder) savedExitFn := testExitFn savedOutput := testOutput testExitFn = exitFn testOutput = w TAssertEqualI([]int{1, 2, 3, 4}, []int{5, 6, 7}) testExitFn = savedExitFn testOutput = savedOutput given := strings.Split(w.String(), "\n")[1:] TAssertEqual(n, 100) TAssertEqual(given, []string{ "given has 1 more elements:", "[]int{4}", "", }) }) Testing("fail when nth element is different", func() { var n int exitFn := func(val int) { n = val } w := new(strings.Builder) savedExitFn := testExitFn savedOutput := testOutput testExitFn = exitFn testOutput = w TAssertEqualI([]int{1, 2, 10, 4, 100}, []int{1, 2, 3, 4, 5}) testExitFn = savedExitFn testOutput = savedOutput given := strings.Split(w.String(), "\n") given = slices.Concat(given[1:4], given[5:]) TAssertEqual(n, 100) TAssertEqual(given, []string{ "given != expected (i = 2)", "given: 10", "expected: 3", "given != expected (i = 4)", "given: 100", "expected: 5", "", }) }) } 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 rand, err := Random(10) TErrorIf(err) theLevel := levelFromString(string(rand), 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_Fatal() { TestStart("Fatal()") Testing("error and panic", func() { savedLogger := slog.Default() savedLevel := level w := new(strings.Builder) SetLoggerOutput(w) level = LevelError defer func() { r := recover() TAssertEqual(r == nil, false) slog.SetDefault(savedLogger) level = savedLevel TAssertEqual(len(w.String()) == 0, false) }() Fatal(nil) TErrorNil(nil) }) } func test_FatalIf() { TestStart("FatalIf()") Testing("noop on nil", func() { FatalIf(nil) }) Testing("error and panic otherwise", func() { savedLogger := slog.Default() savedLevel := level w := new(strings.Builder) SetLoggerOutput(w) level = LevelError myErr := errors.New("the error") defer func() { r := recover() TAssertEqual(r, myErr) slog.SetDefault(savedLogger) level = savedLevel TAssertEqual(len(w.String()) == 0, false) }() FatalIf(myErr) TErrorNil(nil) }) } func test_Assert() { TestStart("Assert()") Testing("noop if true", func() { Assert(true, "ignored") }) Testing("error and panic if false", func() { savedLogger := slog.Default() savedLevel := level w := new(strings.Builder) SetLoggerOutput(w) level = LevelError const errMsg = "assert error message" defer func() { r := recover() TAssertEqual( r.(error).Error(), "assertion failed: assert error message", ) slog.SetDefault(savedLogger) level = savedLevel TAssertEqual(len(w.String()) == 0, false) }() Assert(1 == 2, errMsg) TErrorNil(nil) }) } func test_Unreachable() { TestStart("Unreachable()") Testing("always has error and panic", func() { savedLogger := slog.Default() savedLevel := level w := new(strings.Builder) SetLoggerOutput(w) level = LevelError defer func() { r := recover() TAssertEqual( r.(error).Error(), "assertion failed: Unreachable code was reached", ) slog.SetDefault(savedLogger) level = savedLevel TAssertEqual(len(w.String()) == 0, false) }() Unreachable() TErrorNil(nil) }) } 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() { Init() test_SetOf() test_Contains() test_MapIndexed() test_Map() test_Filter() test_PanicIf() test_Must() test_Clamp() 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_Fatal() test_FatalIf() test_Assert() test_Unreachable() test_setHostname() }