get.porter.sh/porter@v1.3.0/pkg/printer/printer_test.go (about) 1 package printer 2 3 import ( 4 "testing" 5 6 "get.porter.sh/porter/tests" 7 "github.com/stretchr/testify/assert" 8 "github.com/stretchr/testify/require" 9 ) 10 11 func TestParseFormat(t *testing.T) { 12 testcases := []struct { 13 rawFormat string 14 wantFormat Format 15 wantErr string 16 }{ 17 {rawFormat: "plaintext", wantFormat: FormatPlaintext}, 18 {rawFormat: "json", wantFormat: FormatJson}, 19 {rawFormat: "yaml", wantFormat: FormatYaml}, 20 {rawFormat: "", wantFormat: FormatPlaintext}, 21 {rawFormat: "human", wantErr: "invalid format"}, 22 } 23 24 for _, tc := range testcases { 25 t.Run(tc.rawFormat, func(t *testing.T) { 26 opts := PrintOptions{ 27 RawFormat: tc.rawFormat, 28 } 29 30 err := opts.ParseFormat() 31 if tc.wantErr == "" { 32 require.NoError(t, err) 33 require.Equal(t, tc.wantFormat, opts.Format, "incorrect format was returned by ParseFormat") 34 } else { 35 tests.RequireErrorContains(t, err, tc.wantErr, "unexpected error returned by ParseFormat") 36 } 37 }) 38 } 39 } 40 41 func TestPrintOptions_Validate(t *testing.T) { 42 t.Run("default format", func(t *testing.T) { 43 allowed := Formats{FormatPlaintext, FormatJson} 44 opts := PrintOptions{} 45 err := opts.Validate(FormatJson, allowed) 46 require.NoError(t, err, "Validate should succeed for a defaulted value") 47 assert.Equal(t, FormatJson, opts.Format, "Validate should set the Format field to the default format") 48 }) 49 50 t.Run("allowed format", func(t *testing.T) { 51 allowed := Formats{FormatPlaintext, FormatJson} 52 opts := PrintOptions{RawFormat: "plaintext"} 53 err := opts.Validate("", allowed) 54 require.NoError(t, err, "Validate should succeed for an allowed value") 55 assert.Equal(t, FormatPlaintext, opts.Format, "Validate should set the Format field to the parsed format") 56 }) 57 58 t.Run("unallowed format", func(t *testing.T) { 59 allowed := Formats{FormatPlaintext, FormatJson} 60 opts := PrintOptions{RawFormat: "yaml"} 61 err := opts.Validate("", allowed) 62 require.EqualError(t, err, "invalid format: yaml", "Validate should fail for an unallowed value") 63 }) 64 } 65 66 func TestFormats_String(t *testing.T) { 67 t.Run("zero length", func(t *testing.T) { 68 f := Formats{} 69 assert.Equal(t, "", f.String()) 70 }) 71 72 t.Run("single length", func(t *testing.T) { 73 f := Formats{FormatPlaintext} 74 assert.Equal(t, "plaintext", f.String()) 75 }) 76 77 t.Run("multi length", func(t *testing.T) { 78 f := Formats{FormatPlaintext, FormatJson} 79 assert.Equal(t, "plaintext, json", f.String()) 80 }) 81 }