github.com/panekj/cli@v0.0.0-20230304125325-467dd2f3797e/cli/command/formatter/formatter_test.go (about) 1 package formatter 2 3 import ( 4 "bytes" 5 "testing" 6 7 "gotest.tools/v3/assert" 8 ) 9 10 func TestFormat(t *testing.T) { 11 f := Format("json") 12 assert.Assert(t, f.IsJSON()) 13 assert.Assert(t, !f.IsTable()) 14 15 f = Format("table") 16 assert.Assert(t, !f.IsJSON()) 17 assert.Assert(t, f.IsTable()) 18 19 f = Format("other") 20 assert.Assert(t, !f.IsJSON()) 21 assert.Assert(t, !f.IsTable()) 22 } 23 24 type fakeSubContext struct { 25 Name string 26 } 27 28 func (f fakeSubContext) FullHeader() interface{} { 29 return map[string]string{"Name": "NAME"} 30 } 31 32 func TestContext(t *testing.T) { 33 testCases := []struct { 34 name string 35 format string 36 expected string 37 }{ 38 { 39 name: "json format", 40 format: JSONFormatKey, 41 expected: `{"Name":"test"} 42 `, 43 }, 44 { 45 name: "table format", 46 format: `table {{.Name}}`, 47 expected: `NAME 48 test 49 `, 50 }, 51 } 52 for _, tc := range testCases { 53 t.Run(tc.name, func(t *testing.T) { 54 buf := bytes.NewBuffer(nil) 55 ctx := Context{ 56 Format: Format(tc.format), 57 Output: buf, 58 } 59 subContext := fakeSubContext{Name: "test"} 60 subFormat := func(f func(sub SubContext) error) error { 61 return f(subContext) 62 } 63 err := ctx.Write(&subContext, subFormat) 64 assert.NilError(t, err) 65 assert.Equal(t, buf.String(), tc.expected) 66 }) 67 } 68 }