|
| 1 | +package add |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + "testing" |
| 6 | + |
| 7 | + "github.com/cli/cli/v2/internal/ghrepo" |
| 8 | + "github.com/cli/cli/v2/pkg/httpmock" |
| 9 | + "github.com/cli/cli/v2/pkg/iostreams" |
| 10 | +) |
| 11 | + |
| 12 | +func Test_addRun(t *testing.T) { |
| 13 | + tests := []struct { |
| 14 | + name string |
| 15 | + opts AddOptions |
| 16 | + isTTY bool |
| 17 | + stdin string |
| 18 | + httpStubs func(t *testing.T, reg *httpmock.Registry) |
| 19 | + wantStdout string |
| 20 | + wantStderr string |
| 21 | + wantErr bool |
| 22 | + }{ |
| 23 | + { |
| 24 | + name: "add from stdin", |
| 25 | + isTTY: true, |
| 26 | + opts: AddOptions{ |
| 27 | + KeyFile: "-", |
| 28 | + Title: "my sacred key", |
| 29 | + AllowWrite: false, |
| 30 | + }, |
| 31 | + stdin: "PUBKEY\n", |
| 32 | + httpStubs: func(t *testing.T, reg *httpmock.Registry) { |
| 33 | + reg.Register( |
| 34 | + httpmock.REST("POST", "repos/OWNER/REPO/keys"), |
| 35 | + httpmock.RESTPayload(200, `{}`, func(payload map[string]interface{}) { |
| 36 | + if title := payload["title"].(string); title != "my sacred key" { |
| 37 | + t.Errorf("POST title %q, want %q", title, "my sacred key") |
| 38 | + } |
| 39 | + if key := payload["key"].(string); key != "PUBKEY\n" { |
| 40 | + t.Errorf("POST key %q, want %q", key, "PUBKEY\n") |
| 41 | + } |
| 42 | + if isReadOnly := payload["read_only"].(bool); !isReadOnly { |
| 43 | + t.Errorf("POST read_only %v, want %v", isReadOnly, true) |
| 44 | + } |
| 45 | + })) |
| 46 | + }, |
| 47 | + wantStdout: "✓ Deploy key added to OWNER/REPO\n", |
| 48 | + wantStderr: "", |
| 49 | + wantErr: false, |
| 50 | + }, |
| 51 | + } |
| 52 | + |
| 53 | + for _, tt := range tests { |
| 54 | + t.Run(tt.name, func(t *testing.T) { |
| 55 | + io, stdin, stdout, stderr := iostreams.Test() |
| 56 | + stdin.WriteString(tt.stdin) |
| 57 | + io.SetStdinTTY(tt.isTTY) |
| 58 | + io.SetStdoutTTY(tt.isTTY) |
| 59 | + io.SetStderrTTY(tt.isTTY) |
| 60 | + |
| 61 | + reg := &httpmock.Registry{} |
| 62 | + if tt.httpStubs != nil { |
| 63 | + tt.httpStubs(t, reg) |
| 64 | + } |
| 65 | + |
| 66 | + opts := tt.opts |
| 67 | + opts.IO = io |
| 68 | + opts.BaseRepo = func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil } |
| 69 | + opts.HTTPClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } |
| 70 | + |
| 71 | + err := addRun(&opts) |
| 72 | + if (err != nil) != tt.wantErr { |
| 73 | + t.Errorf("addRun() return error: %v", err) |
| 74 | + return |
| 75 | + } |
| 76 | + |
| 77 | + if stdout.String() != tt.wantStdout { |
| 78 | + t.Errorf("wants stdout %q, got %q", tt.wantStdout, stdout.String()) |
| 79 | + } |
| 80 | + if stderr.String() != tt.wantStderr { |
| 81 | + t.Errorf("wants stderr %q, got %q", tt.wantStderr, stderr.String()) |
| 82 | + } |
| 83 | + }) |
| 84 | + } |
| 85 | +} |
0 commit comments