github.com/ungtb10d/cli/v2@v2.0.0-20221110210412-98537dd9d6a1/pkg/cmd/config/get/get_test.go (about) 1 package get 2 3 import ( 4 "bytes" 5 "testing" 6 7 "github.com/ungtb10d/cli/v2/internal/config" 8 "github.com/ungtb10d/cli/v2/pkg/cmdutil" 9 "github.com/ungtb10d/cli/v2/pkg/iostreams" 10 "github.com/google/shlex" 11 "github.com/stretchr/testify/assert" 12 ) 13 14 func TestNewCmdConfigGet(t *testing.T) { 15 tests := []struct { 16 name string 17 input string 18 output GetOptions 19 wantsErr bool 20 }{ 21 { 22 name: "no arguments", 23 input: "", 24 output: GetOptions{}, 25 wantsErr: true, 26 }, 27 { 28 name: "get key", 29 input: "key", 30 output: GetOptions{Key: "key"}, 31 wantsErr: false, 32 }, 33 { 34 name: "get key with host", 35 input: "key --host test.com", 36 output: GetOptions{Hostname: "test.com", Key: "key"}, 37 wantsErr: false, 38 }, 39 } 40 41 for _, tt := range tests { 42 t.Run(tt.name, func(t *testing.T) { 43 f := &cmdutil.Factory{ 44 Config: func() (config.Config, error) { 45 return config.NewBlankConfig(), nil 46 }, 47 } 48 49 argv, err := shlex.Split(tt.input) 50 assert.NoError(t, err) 51 52 var gotOpts *GetOptions 53 cmd := NewCmdConfigGet(f, func(opts *GetOptions) error { 54 gotOpts = opts 55 return nil 56 }) 57 cmd.Flags().BoolP("help", "x", false, "") 58 59 cmd.SetArgs(argv) 60 cmd.SetIn(&bytes.Buffer{}) 61 cmd.SetOut(&bytes.Buffer{}) 62 cmd.SetErr(&bytes.Buffer{}) 63 64 _, err = cmd.ExecuteC() 65 if tt.wantsErr { 66 assert.Error(t, err) 67 return 68 } 69 70 assert.NoError(t, err) 71 assert.Equal(t, tt.output.Hostname, gotOpts.Hostname) 72 assert.Equal(t, tt.output.Key, gotOpts.Key) 73 }) 74 } 75 } 76 77 func Test_getRun(t *testing.T) { 78 tests := []struct { 79 name string 80 input *GetOptions 81 stdout string 82 stderr string 83 wantErr bool 84 }{ 85 { 86 name: "get key", 87 input: &GetOptions{ 88 Key: "editor", 89 Config: func() config.Config { 90 cfg := config.NewBlankConfig() 91 cfg.Set("", "editor", "ed") 92 return cfg 93 }(), 94 }, 95 stdout: "ed\n", 96 }, 97 { 98 name: "get key scoped by host", 99 input: &GetOptions{ 100 Hostname: "github.com", 101 Key: "editor", 102 Config: func() config.Config { 103 cfg := config.NewBlankConfig() 104 cfg.Set("", "editor", "ed") 105 cfg.Set("github.com", "editor", "vim") 106 return cfg 107 }(), 108 }, 109 stdout: "vim\n", 110 }, 111 } 112 113 for _, tt := range tests { 114 ios, _, stdout, stderr := iostreams.Test() 115 tt.input.IO = ios 116 117 t.Run(tt.name, func(t *testing.T) { 118 err := getRun(tt.input) 119 assert.NoError(t, err) 120 assert.Equal(t, tt.stdout, stdout.String()) 121 assert.Equal(t, tt.stderr, stderr.String()) 122 }) 123 } 124 }