github.com/cycloidio/terraform@v1.1.10-0.20220513142504-76d5c768dc63/command/logout_test.go (about) 1 package command 2 3 import ( 4 "io/ioutil" 5 "os" 6 "path/filepath" 7 "testing" 8 9 "github.com/mitchellh/cli" 10 11 svchost "github.com/hashicorp/terraform-svchost" 12 svcauth "github.com/hashicorp/terraform-svchost/auth" 13 "github.com/hashicorp/terraform-svchost/disco" 14 "github.com/cycloidio/terraform/command/cliconfig" 15 ) 16 17 func TestLogout(t *testing.T) { 18 workDir, err := ioutil.TempDir("", "terraform-test-command-logout") 19 if err != nil { 20 t.Fatalf("cannot create temporary directory: %s", err) 21 } 22 defer os.RemoveAll(workDir) 23 24 ui := cli.NewMockUi() 25 credsSrc := cliconfig.EmptyCredentialsSourceForTests(filepath.Join(workDir, "credentials.tfrc.json")) 26 27 c := &LogoutCommand{ 28 Meta: Meta{ 29 Ui: ui, 30 Services: disco.NewWithCredentialsSource(credsSrc), 31 }, 32 } 33 34 testCases := []struct { 35 // Hostname to associate a pre-stored token 36 hostname string 37 // Command-line arguments 38 args []string 39 // true iff the token at hostname should be removed by the command 40 shouldRemove bool 41 }{ 42 // If no command-line arguments given, should remove app.terraform.io token 43 {"app.terraform.io", []string{}, true}, 44 45 // Can still specify app.terraform.io explicitly 46 {"app.terraform.io", []string{"app.terraform.io"}, true}, 47 48 // Can remove tokens for other hostnames 49 {"tfe.example.com", []string{"tfe.example.com"}, true}, 50 51 // Logout does not remove tokens for other hostnames 52 {"tfe.example.com", []string{"other-tfe.acme.com"}, false}, 53 } 54 for _, tc := range testCases { 55 host := svchost.Hostname(tc.hostname) 56 token := svcauth.HostCredentialsToken("some-token") 57 err = credsSrc.StoreForHost(host, token) 58 if err != nil { 59 t.Fatalf("unexpected error storing credentials: %s", err) 60 } 61 62 status := c.Run(tc.args) 63 if status != 0 { 64 t.Fatalf("unexpected error code %d\nstderr:\n%s", status, ui.ErrorWriter.String()) 65 } 66 67 creds, err := credsSrc.ForHost(host) 68 if err != nil { 69 t.Errorf("failed to retrieve credentials: %s", err) 70 } 71 if tc.shouldRemove { 72 if creds != nil { 73 t.Errorf("wrong token %q; should have no token", creds.Token()) 74 } 75 } else { 76 if got, want := creds.Token(), "some-token"; got != want { 77 t.Errorf("wrong token %q; want %q", got, want) 78 } 79 } 80 } 81 }