From 13f4c5fb0f85c9153b35452d2d36967095250971 Mon Sep 17 00:00:00 2001 From: Eduard Urbach Date: Tue, 5 Mar 2024 19:10:27 +0100 Subject: [PATCH] Improved tests --- Color.go | 3 +++ Color_test.go | 20 ++++++++++++-------- README.md | 6 +++--- Terminal.go | 2 +- 4 files changed, 19 insertions(+), 12 deletions(-) diff --git a/Color.go b/Color.go index dfd67c0..81b7e32 100644 --- a/Color.go +++ b/Color.go @@ -24,6 +24,7 @@ func RGB(r Component, g Component, b Component) Color { func (c Color) Fprint(writer io.Writer, text string) { if !Terminal { fmt.Fprint(writer, text) + return } fmt.Fprintf(writer, format, byte(c.R*255), byte(c.G*255), byte(c.B*255), text) @@ -33,6 +34,7 @@ func (c Color) Fprint(writer io.Writer, text string) { func (c Color) Print(text string) { if !Terminal { fmt.Print(text) + return } fmt.Printf(format, byte(c.R*255), byte(c.G*255), byte(c.B*255), text) @@ -42,6 +44,7 @@ func (c Color) Print(text string) { func (c Color) Println(text string) { if !Terminal { fmt.Println(text) + return } fmt.Printf(formatLine, byte(c.R*255), byte(c.G*255), byte(c.B*255), text) diff --git a/Color_test.go b/Color_test.go index 12c21d9..c61fcaa 100644 --- a/Color_test.go +++ b/Color_test.go @@ -1,7 +1,7 @@ package color_test import ( - "os" + "io" "testing" "git.akyoto.dev/go/assert" @@ -9,6 +9,16 @@ import ( ) func TestColors(t *testing.T) { + color.Terminal = true + testColors(t) +} + +func TestNoColors(t *testing.T) { + color.Terminal = false + testColors(t) +} + +func testColors(t *testing.T) { colors := map[string]color.Color{ "black": color.RGB(0.0, 0.0, 0.0), "white": color.RGB(1.0, 1.0, 1.0), @@ -26,14 +36,8 @@ func TestColors(t *testing.T) { assert.True(t, value.G <= 1.0) assert.True(t, value.B <= 1.0) - color.Terminal = true - value.Fprint(os.Stdout, name) + value.Fprint(io.Discard, name) value.Print(name) value.Println(name) - - color.Terminal = false - value.Fprint(os.Stdout, "-") - value.Print("-") - value.Println("-") } } diff --git a/README.md b/README.md index 20759ff..2a72784 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ go get git.akyoto.dev/go/color ```go red := color.RGB(1.0, 0.0, 0.0) -fmt.Println(red.Format("red text")) +red.Println("red text") ``` ## Tests @@ -29,8 +29,8 @@ coverage: 100.0% of statements ## Benchmarks ``` -BenchmarkRGB-12 1000000000 0.3131 ns/op 0 B/op 0 allocs/op -BenchmarkFprint-12 6455497 186.2 ns/op 0 B/op 0 allocs/op +BenchmarkRGB-12 1000000000 0.3139 ns/op 0 B/op 0 allocs/op +BenchmarkFprint-12 25758495 45.38 ns/op 0 B/op 0 allocs/op ``` ## License diff --git a/Terminal.go b/Terminal.go index f7c2d78..e2a73d8 100644 --- a/Terminal.go +++ b/Terminal.go @@ -7,7 +7,7 @@ import ( // These constants represent the escape codes needed to display color in terminals. const ( format = "\x1b[38;2;%d;%d;%dm%s\x1b[0m" - formatLine = format + "\n" + formatLine = "\x1b[38;2;%d;%d;%dm%s\n\x1b[0m" ) // Terminal is a boolean that indicates if we're in a terminal with truecolor support.