github.com/kevinklinger/open_terraform@v1.3.6/noninternal/command/logout_test.go (about)

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