github.com/cli/cli@v1.14.1-0.20210902173923-1af6a669e342/pkg/cmd/config/get/get_test.go (about) 1 package get 2 3 import ( 4 "bytes" 5 "testing" 6 7 "github.com/cli/cli/internal/config" 8 "github.com/cli/cli/pkg/cmdutil" 9 "github.com/cli/cli/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.ConfigStub{}, 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: config.ConfigStub{ 90 "editor": "ed", 91 }, 92 }, 93 stdout: "ed\n", 94 }, 95 { 96 name: "get key scoped by host", 97 input: &GetOptions{ 98 Hostname: "github.com", 99 Key: "editor", 100 Config: config.ConfigStub{ 101 "editor": "ed", 102 "github.com:editor": "vim", 103 }, 104 }, 105 stdout: "vim\n", 106 }, 107 } 108 109 for _, tt := range tests { 110 io, _, stdout, stderr := iostreams.Test() 111 tt.input.IO = io 112 113 t.Run(tt.name, func(t *testing.T) { 114 err := getRun(tt.input) 115 assert.NoError(t, err) 116 assert.Equal(t, tt.stdout, stdout.String()) 117 assert.Equal(t, tt.stderr, stderr.String()) 118 _, err = tt.input.Config.Get("", "_written") 119 assert.Error(t, err) 120 }) 121 } 122 }