goweb/cli/format/table/writer_test.go

102 lines
2.2 KiB
Go
Raw Permalink Normal View History

2023-12-15 20:01:37 +01:00
package table
import (
"bytes"
"fmt"
2023-12-15 20:01:37 +01:00
"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)
2023-12-15 20:01:37 +01:00
}
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"),
2023-12-15 20:01:37 +01:00
},
}
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} | <nil> | <nil> |
| Bar | 0 | {"MyBool":true} | {"MyBool":false} | Test |
+----------+-------+------------------+------------------+------------+`
2023-12-15 20:01:37 +01:00
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
}