github.1git.de/docker/cli@v26.1.3+incompatible/cli/command/formatter/formatter_test.go (about)

     1  // FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16:
     2  //go:build go1.19
     3  
     4  package formatter
     5  
     6  import (
     7  	"bytes"
     8  	"testing"
     9  
    10  	"gotest.tools/v3/assert"
    11  )
    12  
    13  func TestFormat(t *testing.T) {
    14  	f := Format("json")
    15  	assert.Assert(t, f.IsJSON())
    16  	assert.Assert(t, !f.IsTable())
    17  
    18  	f = Format("table")
    19  	assert.Assert(t, !f.IsJSON())
    20  	assert.Assert(t, f.IsTable())
    21  
    22  	f = Format("other")
    23  	assert.Assert(t, !f.IsJSON())
    24  	assert.Assert(t, !f.IsTable())
    25  }
    26  
    27  type fakeSubContext struct {
    28  	Name string
    29  }
    30  
    31  func (f fakeSubContext) FullHeader() any {
    32  	return map[string]string{"Name": "NAME"}
    33  }
    34  
    35  func TestContext(t *testing.T) {
    36  	testCases := []struct {
    37  		name     string
    38  		format   string
    39  		expected string
    40  	}{
    41  		{
    42  			name:   "json format",
    43  			format: JSONFormatKey,
    44  			expected: `{"Name":"test"}
    45  `,
    46  		},
    47  		{
    48  			name:   "table format",
    49  			format: `table {{.Name}}`,
    50  			expected: `NAME
    51  test
    52  `,
    53  		},
    54  	}
    55  	for _, tc := range testCases {
    56  		t.Run(tc.name, func(t *testing.T) {
    57  			buf := bytes.NewBuffer(nil)
    58  			ctx := Context{
    59  				Format: Format(tc.format),
    60  				Output: buf,
    61  			}
    62  			subContext := fakeSubContext{Name: "test"}
    63  			subFormat := func(f func(sub SubContext) error) error {
    64  				return f(subContext)
    65  			}
    66  			err := ctx.Write(&subContext, subFormat)
    67  			assert.NilError(t, err)
    68  			assert.Equal(t, buf.String(), tc.expected)
    69  		})
    70  	}
    71  }