|
| 1 | +package auth_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "errors" |
| 6 | + "testing" |
| 7 | + |
| 8 | + "github.com/fastly/kingpin" |
| 9 | + |
| 10 | + authcmd "github.com/fastly/cli/pkg/commands/auth" |
| 11 | + "github.com/fastly/cli/pkg/config" |
| 12 | + fsterr "github.com/fastly/cli/pkg/errors" |
| 13 | + "github.com/fastly/cli/pkg/global" |
| 14 | +) |
| 15 | + |
| 16 | +func newTokenCommand(g *global.Data) *authcmd.TokenCommand { |
| 17 | + app := kingpin.New("fastly", "test") |
| 18 | + parent := app.Command("auth", "test auth") |
| 19 | + return authcmd.NewTokenCommand(parent, g) |
| 20 | +} |
| 21 | + |
| 22 | +func globalDataWithToken(token string) *global.Data { |
| 23 | + return &global.Data{ |
| 24 | + Config: config.File{ |
| 25 | + Auth: config.Auth{ |
| 26 | + Default: "user", |
| 27 | + Tokens: config.AuthTokens{ |
| 28 | + "user": &config.AuthToken{ |
| 29 | + Type: config.AuthTokenTypeStatic, |
| 30 | + Token: token, |
| 31 | + }, |
| 32 | + }, |
| 33 | + }, |
| 34 | + }, |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +func TestToken_NonTTY_Success(t *testing.T) { |
| 39 | + var buf bytes.Buffer |
| 40 | + cmd := newTokenCommand(globalDataWithToken("test-api-token-value")) |
| 41 | + err := cmd.Exec(nil, &buf) |
| 42 | + if err != nil { |
| 43 | + t.Fatalf("expected no error, got: %v", err) |
| 44 | + } |
| 45 | + if got := buf.String(); got != "test-api-token-value" { |
| 46 | + t.Errorf("expected token %q, got %q", "test-api-token-value", got) |
| 47 | + } |
| 48 | + if got := buf.Bytes(); got[len(got)-1] == '\n' { |
| 49 | + t.Error("output should not have a trailing newline") |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +func TestToken_NonTTY_NoToken(t *testing.T) { |
| 54 | + var buf bytes.Buffer |
| 55 | + g := &global.Data{ |
| 56 | + Config: config.File{}, |
| 57 | + } |
| 58 | + |
| 59 | + cmd := newTokenCommand(g) |
| 60 | + err := cmd.Exec(nil, &buf) |
| 61 | + if err == nil { |
| 62 | + t.Fatal("expected error for missing token") |
| 63 | + } |
| 64 | + var re fsterr.RemediationError |
| 65 | + if !errors.As(err, &re) { |
| 66 | + t.Fatalf("expected RemediationError, got %T: %v", err, err) |
| 67 | + } |
| 68 | + if re.Inner == nil || re.Inner.Error() != "no API token configured" { |
| 69 | + t.Errorf("unexpected inner error: %v", re.Inner) |
| 70 | + } |
| 71 | +} |
0 commit comments