From 84fa8454a31285c0181fcba02ef16c0a881868c5 Mon Sep 17 00:00:00 2001 From: "Mike JS. Choi" Date: Sun, 20 May 2018 13:56:31 -0500 Subject: [PATCH] Test: Add tests for color.go --- color/color.go | 10 --------- color/color_test.go | 54 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 10 deletions(-) create mode 100644 color/color_test.go diff --git a/color/color.go b/color/color.go index 7814665..9866049 100644 --- a/color/color.go +++ b/color/color.go @@ -45,17 +45,7 @@ func Green(style int, format string, a ...interface{}) string { return colorString(FgGreen, style, format, a...) } -// Yellow returns a string with yellow foreground -func Yellow(style int, format string, a ...interface{}) string { - return colorString(FgYellow, style, format, a...) -} - // Blue returns a string with blue foreground func Blue(style int, format string, a ...interface{}) string { return colorString(FgBlue, style, format, a...) } - -// Purple returns a string with purple foreground -func Purple(style int, format string, a ...interface{}) string { - return colorString(FgPurple, style, format, a...) -} diff --git a/color/color_test.go b/color/color_test.go new file mode 100644 index 0000000..c612088 --- /dev/null +++ b/color/color_test.go @@ -0,0 +1,54 @@ +package color + +import ( + "os" + "testing" +) + +// Setup tests +var tests = []struct { + color func(style int, format string, a ...interface{}) string + input []string + expected string +}{ + {Black, []string{"%s", "foobar"}, "\033[30;1mfoobar"}, + {Red, []string{"%s %s", "foobar", "hey"}, "\033[31;1mfoobar hey"}, + {Green, []string{"%s", ""}, "\033[32;1m"}, + {Blue, []string{"foobar"}, "\033[34;1mfoobar"}, +} + +func TestColors(t *testing.T) { + // Redirect stdout + oldStdout := os.Stdout + _, w, err := os.Pipe() + if err != nil { + t.Fatalf("ColorString failed to redirect stdout because %s", err.Error()) + } + os.Stdout = w + + // Restore old stdout + defer func() { + w.Close() + os.Stdout = oldStdout + }() + + // Check output + var out string + for _, test := range tests { + if len(test.input) == 1 { + // With formatter + out = test.color(Regular, test.input[0]) + } else { + // Without formatter + s := make([]interface{}, len(test.input)-1) + for i, v := range test.input[1:] { + s[i] = v + } + out = test.color(Regular, test.input[0], s...) + } + + if test.expected != out { + t.Errorf("Color failed: got %s, want %s", out, test.expected) + } + } +}