From 553b89f30c84d5f96fd4a63b7654827cb86d70db Mon Sep 17 00:00:00 2001 From: William Martin Date: Mon, 4 Dec 2023 12:12:22 +0100 Subject: [PATCH] Add tests for AuthConfig TokenForUser --- internal/config/auth_config_test.go | 41 +++++++++++++++++++++++++++++ internal/config/config.go | 3 +-- 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/internal/config/auth_config_test.go b/internal/config/auth_config_test.go index cb673f27d..a6595e112 100644 --- a/internal/config/auth_config_test.go +++ b/internal/config/auth_config_test.go @@ -553,6 +553,47 @@ func TestUsersForHostWithUsers(t *testing.T) { require.Equal(t, []string{"test-user-1", "test-user-2"}, users) } +func TestTokenForUserSecureLogin(t *testing.T) { + // Given a user has logged in securely + authCfg := newTestAuthConfig(t) + _, err := authCfg.Login("github.com", "test-user-1", "test-token", "ssh", true) + require.NoError(t, err) + + // When we get the token + token, source, err := authCfg.TokenForUser("github.com", "test-user-1") + + // Then it returns the token and the source as keyring + require.NoError(t, err) + require.Equal(t, "test-token", token) + require.Equal(t, "keyring", source) +} + +func TestTokenForUserInsecureLogin(t *testing.T) { + // Given a user has logged in insecurely + authCfg := newTestAuthConfig(t) + _, err := authCfg.Login("github.com", "test-user-1", "test-token", "ssh", false) + require.NoError(t, err) + + // When we get the token + token, source, err := authCfg.TokenForUser("github.com", "test-user-1") + + // Then it returns the token and the source as oauth_token + require.NoError(t, err) + require.Equal(t, "test-token", token) + require.Equal(t, "oauth_token", source) +} + +func TestTokenForUserNotFoundErrors(t *testing.T) { + // Given a user has not logged in + authCfg := newTestAuthConfig(t) + + // When we get the token + _, _, err := authCfg.TokenForUser("github.com", "test-user-1") + + // Then it returns an error + require.EqualError(t, err, "no token found for 'test-user-1'") +} + func requireKeyWithValue(t *testing.T, cfg *ghConfig.Config, keys []string, value string) { t.Helper() diff --git a/internal/config/config.go b/internal/config/config.go index 7d30623be..eefc76868 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -417,7 +417,6 @@ func (c *AuthConfig) UsersForHost(hostname string) ([]string, error) { return users, nil } -// TODO: Write tests and explore implementation and return value more func (c *AuthConfig) TokenForUser(hostname, user string) (string, string, error) { if token, err := keyring.Get(keyringServiceName(hostname), user); err == nil { return token, "keyring", nil @@ -428,7 +427,7 @@ func (c *AuthConfig) TokenForUser(hostname, user string) (string, string, error) return token, "oauth_token", nil } - return "", "default", fmt.Errorf("no token found for: %s", user) + return "", "default", fmt.Errorf("no token found for '%s'", user) } func keyringServiceName(hostname string) string {