package table import ( "bytes" "fmt" "strings" "testing" "github.com/pkg/errors" "gitlab.com/wpetit/goweb/cli/format" ) type dummyItem struct { MyString string MyInt int MySub subItem MySubPtr *subItem MyPointStr *string } func (d *dummyItem) MyMethod() string { return fmt.Sprintf("myMethod: %s | %d", d.MyString, d.MyInt) } type subItem struct { MyBool bool } var dummyItems = []any{ dummyItem{ MyString: "Foo", MyInt: 1, MySub: subItem{ MyBool: false, }, }, dummyItem{ MyString: "Bar", MyInt: 0, MySub: subItem{ MyBool: true, }, MySubPtr: &subItem{ MyBool: false, }, MyPointStr: strPtr("Test"), }, } func TestWriterNoHints(t *testing.T) { var buf bytes.Buffer writer := NewWriter(DefaultCompactModeMaxColumnWidth) if err := writer.Write(&buf, format.Hints{}, dummyItems...); err != nil { t.Fatalf("%+v", errors.WithStack(err)) } expected := `+----------+-------+------------------+------------------+------------+ | MYSTRING | MYINT | MYSUB | MYSUBPTR | MYPOINTSTR | +----------+-------+------------------+------------------+------------+ | Foo | 1 | {"MyBool":false} | | | | Bar | 0 | {"MyBool":true} | {"MyBool":false} | Test | +----------+-------+------------------+------------------+------------+` if e, g := strings.TrimSpace(expected), strings.TrimSpace(buf.String()); e != g { t.Errorf("buf.String(): expected \n%v\ngot\n%v", e, g) } } func TestWriterWithPropHints(t *testing.T) { var buf bytes.Buffer writer := NewWriter(DefaultCompactModeMaxColumnWidth) hints := format.Hints{ Props: []format.Prop{ format.NewProp("MyString", "MyString"), format.NewProp("MyInt", "MyInt"), }, } if err := writer.Write(&buf, hints, dummyItems...); err != nil { t.Fatalf("%+v", errors.WithStack(err)) } expected := `+----------+-------+ | MYSTRING | MYINT | +----------+-------+ | Foo | 1 | | Bar | 0 | +----------+-------+` if e, g := strings.TrimSpace(expected), strings.TrimSpace(buf.String()); e != g { t.Errorf("buf.String(): expected \n%v\ngot\n%v", e, g) } } func strPtr(str string) *string { return &str }