github.com/cli/cli@v1.14.1-0.20210902173923-1af6a669e342/pkg/cmdutil/auth_check_test.go (about)

     1  package cmdutil
     2  
     3  import (
     4  	"os"
     5  	"testing"
     6  
     7  	"github.com/cli/cli/internal/config"
     8  	"github.com/stretchr/testify/assert"
     9  )
    10  
    11  func Test_CheckAuth(t *testing.T) {
    12  	orig_GITHUB_TOKEN := os.Getenv("GITHUB_TOKEN")
    13  	t.Cleanup(func() {
    14  		os.Setenv("GITHUB_TOKEN", orig_GITHUB_TOKEN)
    15  	})
    16  
    17  	tests := []struct {
    18  		name     string
    19  		cfg      func(config.Config)
    20  		envToken bool
    21  		expected bool
    22  	}{
    23  		{
    24  			name:     "no hosts",
    25  			cfg:      func(c config.Config) {},
    26  			envToken: false,
    27  			expected: false,
    28  		},
    29  		{name: "no hosts, env auth token",
    30  			cfg:      func(c config.Config) {},
    31  			envToken: true,
    32  			expected: true,
    33  		},
    34  		{
    35  			name: "host, no token",
    36  			cfg: func(c config.Config) {
    37  				_ = c.Set("github.com", "oauth_token", "")
    38  			},
    39  			envToken: false,
    40  			expected: false,
    41  		},
    42  		{
    43  			name: "host, token",
    44  			cfg: func(c config.Config) {
    45  				_ = c.Set("github.com", "oauth_token", "a token")
    46  			},
    47  			envToken: false,
    48  			expected: true,
    49  		},
    50  	}
    51  
    52  	for _, tt := range tests {
    53  		t.Run(tt.name, func(t *testing.T) {
    54  			if tt.envToken {
    55  				os.Setenv("GITHUB_TOKEN", "TOKEN")
    56  			} else {
    57  				os.Setenv("GITHUB_TOKEN", "")
    58  			}
    59  
    60  			cfg := config.NewBlankConfig()
    61  			tt.cfg(cfg)
    62  			result := CheckAuth(cfg)
    63  			assert.Equal(t, tt.expected, result)
    64  		})
    65  	}
    66  }