1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
|
package tableprinter
import (
"bytes"
"log"
"os"
"testing"
)
func ExampleTablePrinter() {
// information about the terminal can be obtained using the [pkg/term] package
isTTY := true
termWidth := 14
red := func(s string) string {
return "\x1b[31m" + s + "\x1b[m"
}
t := New(os.Stdout, isTTY, termWidth)
t.AddField("9", WithTruncate(nil))
t.AddField("hello")
t.EndRow()
t.AddField("10", WithTruncate(nil))
t.AddField("long description", WithColor(red))
t.EndRow()
if err := t.Render(); err != nil {
log.Fatal(err)
}
// stdout now contains:
// 9 hello
// 10 long de...
}
func Test_ttyTablePrinter_autoTruncate(t *testing.T) {
buf := bytes.Buffer{}
tp := New(&buf, true, 5)
tp.AddField("1")
tp.AddField("hello")
tp.EndRow()
tp.AddField("2")
tp.AddField("world")
tp.EndRow()
err := tp.Render()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
expected := "1 he\n2 wo\n"
if buf.String() != expected {
t.Errorf("expected: %q, got: %q", expected, buf.String())
}
}
func Test_ttyTablePrinter_WithTruncate(t *testing.T) {
buf := bytes.Buffer{}
tp := New(&buf, true, 15)
tp.AddField("long SHA", WithTruncate(nil))
tp.AddField("hello")
tp.EndRow()
tp.AddField("another SHA", WithTruncate(nil))
tp.AddField("world")
tp.EndRow()
err := tp.Render()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
expected := "long SHA he\nanother SHA wo\n"
if buf.String() != expected {
t.Errorf("expected: %q, got: %q", expected, buf.String())
}
}
func Test_tsvTablePrinter(t *testing.T) {
buf := bytes.Buffer{}
tp := New(&buf, false, 0)
tp.AddField("1")
tp.AddField("hello")
tp.EndRow()
tp.AddField("2")
tp.AddField("world")
tp.EndRow()
err := tp.Render()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
expected := "1\thello\n2\tworld\n"
if buf.String() != expected {
t.Errorf("expected: %q, got: %q", expected, buf.String())
}
}
|