fix: include escape codes in byte counts from Print, Printf
Color.Print and Color.Printf return the number of bytes written, but only counted the bytes of the formatted operands. The SGR escape sequence written before them and the reset sequence written after were silently dropped from the count, so the returned n was always short whenever color output was active. Fprint and Fprintf had the identical bug and were already fixed in cbda2c3d by switching from the void Set/unset() pair to setWriter/unsetWriter, which return the byte counts of the escape sequences so they can be accumulated. That fix was never applied to Print and Printf, which still call Set() and unset() and discard what they write. Give Print and Printf the same setWriter/unsetWriter treatment as Fprint and Fprintf. The private unset() method has no remaining callers after this change and is removed. Add TestColor_Print and TestColor_Printf, mirroring the existing TestColor_Fprint/TestColor_Fprintf byte-count assertions.
This commit is contained in:
1 parent
baec7b1239
commit
c92652a003
2 files changed
+71
-14
No files matched your search
@@ -555,6 +555,51 @@ func TestColor_Fprintf(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestColor_Print(t *testing.T) {
|
||||
rb := new(strings.Builder)
|
||||
oldOutput, oldNoColor := Output, NoColor
|
||||
Output, NoColor = rb, false
|
||||
t.Cleanup(func() { Output, NoColor = oldOutput, oldNoColor })
|
||||
|
||||
c := New(FgRed)
|
||||
n, err := c.Print("foo", "bar")
|
||||
if err != nil {
|
||||
t.Errorf("Print error: %v", err)
|
||||
}
|
||||
got := rb.String()
|
||||
want := "\x1b[31mfoobar\x1b[0m"
|
||||
|
||||
if want != got {
|
||||
t.Errorf("Print error\n\nwant: %q\n got: %q", want, got)
|
||||
}
|
||||
if n != len(got) {
|
||||
t.Errorf("Print byte count does not match actual bytes written\n\nwant: %d\n got: %d", len(got), n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestColor_Printf(t *testing.T) {
|
||||
rb := new(strings.Builder)
|
||||
oldOutput, oldNoColor := Output, NoColor
|
||||
Output, NoColor = rb, false
|
||||
t.Cleanup(func() { Output, NoColor = oldOutput, oldNoColor })
|
||||
|
||||
c := New(FgRed)
|
||||
n, err := c.Printf("%-7s %-7s %5d\n", "hello", "world", 123)
|
||||
if err != nil {
|
||||
t.Errorf("Printf error: %v", err)
|
||||
}
|
||||
|
||||
want := "\x1b[31mhello world 123\n\x1b[0m"
|
||||
|
||||
got := rb.String()
|
||||
if want != got {
|
||||
t.Errorf("Printf error\n\nwant: %q\n got: %q", want, got)
|
||||
}
|
||||
if n != len(got) {
|
||||
t.Errorf("Printf byte count does not match actual bytes written\n\nwant: %d\n got: %d", len(got), n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestColor_Fprintln_Newline(t *testing.T) {
|
||||
rb := new(bytes.Buffer)
|
||||
c := New(FgRed)
|
||||
|
||||
Reference in new issue
Block a user