package util_test import ( "io" "nonsense-time/util" "strings" "testing" ) type stringReadCloser struct { *strings.Reader } func newStringReadCloser(s string) stringReadCloser { rc := stringReadCloser{} rc.Reader = strings.NewReader(s) return rc } func (stringReadCloser) Close() error { return nil } func testAnsiFilterReadCloser(t *testing.T, input string, expected string) { reader := newStringReadCloser(input) cleanReader := util.NewAnsiFilterReadCloser(reader) defer cleanReader.Close() buf := new(strings.Builder) n, err := io.Copy(buf, cleanReader) if err != nil { t.Fatal("Error while copying cleaned text to output", err) } result := buf.String() if n != int64(len(expected)) { t.Errorf("Expected to read %d bytes but read %d\n", len(expected), n) } if result != expected { t.Errorf("Expected string `%s` but read `%s`\n", "abc", result) } } func testAnsiFilterWriter(t *testing.T, input string, expected string) { writer := new(strings.Builder) w := util.NewAnsiFilterWriter(writer) n, err := w.Write([]byte(input)) if err != nil { t.Fatal("Error while writting input", err) } if n != len(expected) { t.Errorf("Expected to write %d bytes but read %d\n", len(expected), n) } result := writer.String() if result != expected { t.Errorf("Expected to write `%s` but wrote `%s`\n", expected, result) } } func TestAnsiFilterColorsReadCloser(t *testing.T) { testAnsiFilterReadCloser(t, "a\x1b[31mbc", "abc") testAnsiFilterReadCloser(t, "[\x1b[32minfo\x1b[39m]", "[info]") testAnsiFilterReadCloser(t, "FoundryVTT | 2024-10-06 20:11:14 | [\x1b[32minfo\x1b[39m] Running on Node.js - Version 20.17.0\n"+ "FoundryVTT | 2024-10-06 20:11:14 | [\x1b[32minfo\x1b[39m] Foundry Virtual Tabletop - Version 12 Build 331\n", "FoundryVTT | 2024-10-06 20:11:14 | [info] Running on Node.js - Version 20.17.0\n"+ "FoundryVTT | 2024-10-06 20:11:14 | [info] Foundry Virtual Tabletop - Version 12 Build 331\n") } func TestAnsiFilterColorsWriter(t *testing.T) { testAnsiFilterWriter(t, "a\x1b[31mbc", "abc") testAnsiFilterWriter(t, "[\x1b[32minfo\x1b[39m]", "[info]") testAnsiFilterWriter(t, "FoundryVTT | 2024-10-06 20:11:14 | [\x1b[32minfo\x1b[39m] Running on Node.js - Version 20.17.0\n"+ "FoundryVTT | 2024-10-06 20:11:14 | [\x1b[32minfo\x1b[39m] Foundry Virtual Tabletop - Version 12 Build 331\n", "FoundryVTT | 2024-10-06 20:11:14 | [info] Running on Node.js - Version 20.17.0\n"+ "FoundryVTT | 2024-10-06 20:11:14 | [info] Foundry Virtual Tabletop - Version 12 Build 331\n") }