Skip to content

Commit

Permalink
Miscellaneous test coverage improvements (#719)
Browse files Browse the repository at this point in the history
Co-authored-by: Will Vedder <[email protected]>
Co-authored-by: Sergiu Ghitea <[email protected]>
  • Loading branch information
3 people authored Apr 12, 2023
1 parent 437ce7d commit ac090d1
Show file tree
Hide file tree
Showing 14 changed files with 256 additions and 112 deletions.
3 changes: 2 additions & 1 deletion internal/cli/apps_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,5 +117,6 @@ func TestTypeFor(t *testing.T) {
}

func TestCommaSeparatedStringToSlice(t *testing.T) {
assert.Equal(t, []string{"foo"}, commaSeparatedStringToSlice("foo"))
assert.Equal(t, []string{}, commaSeparatedStringToSlice(""))
assert.Equal(t, []string{"foo", "bar", "baz"}, commaSeparatedStringToSlice(" foo , bar , baz "))
}
5 changes: 1 addition & 4 deletions internal/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -256,10 +256,7 @@ func (c *cli) prepareTenant(ctx context.Context) (Tenant, error) {
if err := t.regenerateAccessToken(ctx); err != nil {
if t.authenticatedWithClientCredentials() {
errorMessage := fmt.Errorf(
"failed to fetch access token using client credentials: %w\n\n"+
"This may occur if the designated Auth0 application has been deleted, "+
"the client secret has been rotated or previous failure to store client secret in the keyring.\n\n"+
"Please re-authenticate by running: %s",
"failed to fetch access token using client credentials: %w\n\nThis may occur if the designated Auth0 application has been deleted, the client secret has been rotated or previous failure to store client secret in the keyring.\n\nPlease re-authenticate by running: %s",
err,
ansi.Bold("auth0 login --domain <tenant-domain --client-id <client-id> --client-secret <client-secret>"),
)
Expand Down
21 changes: 21 additions & 0 deletions internal/cli/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,3 +174,24 @@ func TestGetAccessToken(t *testing.T) {
assert.Equal(t, strings.Join(accessTokenChunks, ""), getAccessToken(Tenant{Domain: mockTenantDomain, AccessToken: "even if this is set for some reason"}))
})
}

func TestAuthenticatedWithClientCredentials(t *testing.T) {
mockTenantClientCredentials := Tenant{ClientID: "some-valid-client-id"}
assert.True(t, mockTenantClientCredentials.authenticatedWithClientCredentials())

mockTenantDeviceFlow := Tenant{ClientID: ""}
assert.False(t, mockTenantDeviceFlow.authenticatedWithClientCredentials())
}

func TestHasAllRequiredScopes(t *testing.T) {
mockTenantWithNoScopes := Tenant{Scopes: []string{}}
assert.False(t, hasAllRequiredScopes(mockTenantWithNoScopes))

mockTenantWithAllRequiredScopes := Tenant{Scopes: auth.RequiredScopes}
assert.True(t, hasAllRequiredScopes(mockTenantWithAllRequiredScopes))

requiredScopesAndMore := auth.RequiredScopes
requiredScopesAndMore = append(requiredScopesAndMore, "read:foo", "update:foo", "delete:foo")
mockTenantWithAllRequiredScopesAndMore := Tenant{Scopes: requiredScopesAndMore}
assert.True(t, hasAllRequiredScopes(mockTenantWithAllRequiredScopesAndMore))
}
4 changes: 1 addition & 3 deletions internal/cli/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -267,9 +267,7 @@ func RunLoginAsMachine(ctx context.Context, inputs LoginInputs, cli *cli, cmd *c
},
)
if err != nil {
return fmt.Errorf(
"failed to fetch access token using client credentials. \n\n"+
"Ensure that the provided client-id, client-secret and domain are correct. \n\nerror: %w\n", err)
return fmt.Errorf("failed to fetch access token using client credentials. \n\nEnsure that the provided client-id, client-secret and domain are correct. \n\nerror: %w\n", err)
}

t := Tenant{
Expand Down
6 changes: 3 additions & 3 deletions internal/cli/logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ func tailLogsCmd(cli *cli) *cobra.Command {
//
// Create a `set` to detect duplicates clientside.
set := make(map[string]struct{})
list = dedupLogs(list, set)
list = dedupeLogs(list, set)

if len(list) > 0 {
lastLogID = list[len(list)-1].GetLogID()
Expand Down Expand Up @@ -142,7 +142,7 @@ func tailLogsCmd(cli *cli) *cobra.Command {
}

if len(list) > 0 {
logsCh <- dedupLogs(list, set)
logsCh <- dedupeLogs(list, set)
lastLogID = list[len(list)-1].GetLogID()
}

Expand Down Expand Up @@ -186,7 +186,7 @@ func getLatestLogs(cli *cli, n int, filter string) ([]*management.Log, error) {
return cli.api.Log.List(queryParams...)
}

func dedupLogs(list []*management.Log, set map[string]struct{}) []*management.Log {
func dedupeLogs(list []*management.Log, set map[string]struct{}) []*management.Log {
res := make([]*management.Log, 0, len(list))

for _, l := range list {
Expand Down
8 changes: 4 additions & 4 deletions internal/cli/logs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
"github.com/auth0/auth0-cli/internal/auth0"
)

func TestDedupLogs(t *testing.T) {
func TestDedupeLogs(t *testing.T) {
t.Run("removes duplicate logs and sorts by date asc", func(t *testing.T) {
logs := []*management.Log{
{
Expand All @@ -28,7 +28,7 @@ func TestDedupLogs(t *testing.T) {
},
}
set := map[string]struct{}{"some-id-3": {}}
result := dedupLogs(logs, set)
result := dedupeLogs(logs, set)

assert.Len(t, result, 2)
assert.Equal(t, "some-id-2", result[0].GetID())
Expand All @@ -51,7 +51,7 @@ func TestDedupLogs(t *testing.T) {
},
}
set := map[string]struct{}{}
result := dedupLogs(logs, set)
result := dedupeLogs(logs, set)

assert.Len(t, logs, 3)
assert.Equal(t, "some-id-2", result[0].GetID())
Expand Down Expand Up @@ -79,7 +79,7 @@ func TestDedupLogs(t *testing.T) {
"some-id-2": {},
"some-id-3": {},
}
result := dedupLogs(logs, set)
result := dedupeLogs(logs, set)

assert.Len(t, result, 0)
})
Expand Down
43 changes: 0 additions & 43 deletions internal/cli/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"strings"

"github.com/spf13/cobra"
"github.com/spf13/pflag"
"golang.org/x/term"

"github.com/auth0/auth0-cli/internal/ansi"
Expand All @@ -14,8 +13,6 @@ import (
func init() {
cobra.AddTemplateFunc("WrappedInheritedFlagUsages", WrappedInheritedFlagUsages)
cobra.AddTemplateFunc("WrappedLocalFlagUsages", WrappedLocalFlagUsages)
cobra.AddTemplateFunc("WrappedRequestParamsFlagUsages", WrappedRequestParamsFlagUsages)
cobra.AddTemplateFunc("WrappedNonRequestParamsFlagUsages", WrappedNonRequestParamsFlagUsages)
cobra.AddTemplateFunc("WrappedAliases", WrappedAliases)
}

Expand All @@ -33,46 +30,6 @@ func WrappedLocalFlagUsages(cmd *cobra.Command) string {
return cmd.LocalFlags().FlagUsagesWrapped(getTerminalWidth())
}

// WrappedRequestParamsFlagUsages returns a string containing the usage
// information for all request parameters flags, i.e. flags used in operation
// commands to set values for request parameters. The string is wrapped to the
// terminal's width.
func WrappedRequestParamsFlagUsages(cmd *cobra.Command) string {
var sb strings.Builder

// We're cheating a little bit in thie method: we're not actually wrapping
// anything, just printing out the flag names and assuming that no name
// will be long enough to go over the terminal's width.
// We do this instead of using pflag's `FlagUsagesWrapped` function because
// we don't want to print the types (all request parameters flags are
// defined as strings in the CLI, but it would be confusing to print that
// out as a lot of them are not strings in the API).
// If/when we do add help strings for request parameters flags, we'll have
// to do actual wrapping.
cmd.LocalFlags().VisitAll(func(flag *pflag.Flag) {
if _, ok := flag.Annotations["request"]; ok {
sb.WriteString(fmt.Sprintf(" --%s\n", flag.Name))
}
})

return sb.String()
}

// WrappedNonRequestParamsFlagUsages returns a string containing the usage
// information for all non-request parameters flags. The string is wrapped to
// the terminal's width.
func WrappedNonRequestParamsFlagUsages(cmd *cobra.Command) string {
nonRequestParamsFlags := pflag.NewFlagSet("request", pflag.ExitOnError)

cmd.LocalFlags().VisitAll(func(flag *pflag.Flag) {
if _, ok := flag.Annotations["request"]; !ok {
nonRequestParamsFlags.AddFlag(flag)
}
})

return nonRequestParamsFlags.FlagUsagesWrapped(getTerminalWidth())
}

// WrappedAliases returns a formatted string containing the command aliases if defined, otherwise an empty string.
func WrappedAliases(cmd *cobra.Command) string {
if len(cmd.Aliases) > 0 {
Expand Down
1 change: 0 additions & 1 deletion internal/cli/tenants.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,6 @@ func (c *cli) tenantPickerOptions() (pickerOptions, error) {
for _, tenant := range tenants {
opt := pickerOption{value: tenant.Domain, label: tenant.Domain}

// Check if this is currently the default tenant.
if tenant.Domain == c.config.DefaultTenant {
priorityOpts = append(priorityOpts, opt)
} else {
Expand Down
22 changes: 5 additions & 17 deletions internal/cli/universal_login_templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,11 +149,7 @@ func updateBrandingTemplateCmd(cli *cli) *cobra.Command {
}

if templateData.Experience == "classic" {
cli.renderer.Warnf(
"The tenant is configured to use the classic Universal Login Experience instead of the new. " +
"The template changes won't apply until you select the new Universal Login Experience. " +
"You can do so by running: \"auth0 api patch prompts --data '{\"universal_login_experience\":\"new\"}'\"",
)
cli.renderer.Warnf("The tenant is configured to use the classic Universal Login Experience instead of the new. The template changes won't apply until you select the new Universal Login Experience. You can do so by running: \"auth0 api patch prompts --data '{\"universal_login_experience\":\"new\"}'\"")
}

if templateData.Body == "" {
Expand Down Expand Up @@ -200,7 +196,6 @@ func updateBrandingTemplateCmd(cli *cli) *cobra.Command {

func (cli *cli) fetchTemplateData(ctx context.Context) (*TemplateData, error) {
group, ctx := errgroup.WithContext(ctx)

group.Go(func() (err error) {
return ensureCustomDomainIsEnabled(ctx, cli.api)
})
Expand All @@ -213,8 +208,7 @@ func (cli *cli) fetchTemplateData(ctx context.Context) (*TemplateData, error) {

var clientList *management.ClientList
group.Go(func() (err error) {
// Capping the clients retrieved to 100 for now.
clientList, err = cli.api.Client.List(management.Context(ctx), management.PerPage(100))
clientList, err = cli.api.Client.List(management.Context(ctx), management.PerPage(100)) // Capping the clients retrieved to 100 for now.
return err
})

Expand Down Expand Up @@ -263,9 +257,8 @@ func (cli *cli) fetchTemplateData(ctx context.Context) (*TemplateData, error) {
func ensureCustomDomainIsEnabled(ctx context.Context, api *auth0.API) error {
domains, err := api.CustomDomain.List(management.Context(ctx))
if err != nil {
// 403 is a valid response for free tenants that don't have custom domains enabled
if mErr, ok := err.(management.Error); ok && mErr.Status() == http.StatusForbidden {
return errNotAllowed
return errNotAllowed // 403 is a valid response for free tenants that don't have custom domains enabled
}

return err
Expand All @@ -284,8 +277,7 @@ func ensureCustomDomainIsEnabled(ctx context.Context, api *auth0.API) error {
func fetchBrandingSettingsOrUseDefaults(ctx context.Context, api *auth0.API) *management.Branding {
brandingSettings, err := api.Branding.Read(management.Context(ctx))
if err != nil {
// If we error we'll provide defaults.
brandingSettings = &management.Branding{}
brandingSettings = &management.Branding{} // If we error we'll provide defaults.
}

if brandingSettings.GetColors() == nil {
Expand All @@ -312,10 +304,7 @@ func fetchBrandingTemplateOrUseEmpty(ctx context.Context, api *auth0.API) *manag

func (cli *cli) editTemplateAndPreviewChanges(ctx context.Context, cmd *cobra.Command, templateData *TemplateData) error {
onInfo := func() {
cli.renderer.Infof(
"%s Once you close the editor, you'll be prompted to save your changes. To cancel, press CTRL+C.",
ansi.Faint("Hint:"),
)
cli.renderer.Infof("%s Once you close the editor, you'll be prompted to save your changes. To cancel, press CTRL+C.", ansi.Faint("Hint:"))
}

onFileCreated := func(filename string) {
Expand Down Expand Up @@ -423,7 +412,6 @@ func buildRoutes(
})

router.Handle("/", http.FileServer(http.FS(templatePreviewAssets)))

return router
}

Expand Down
65 changes: 65 additions & 0 deletions internal/display/apis_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package display

import (
"fmt"
"testing"

"github.com/auth0/go-auth0/management"
"github.com/stretchr/testify/assert"
)

func TestGetScopes(t *testing.T) {
t.Run("no scopes should not truncate", func(t *testing.T) {
mockScopes := []management.ResourceServerScope{}

scopes, didTruncate := getScopes(mockScopes)
assert.Equal(t, "", scopes)
assert.False(t, didTruncate)
})

t.Run("few scopes should not truncate", func(t *testing.T) {
mockScopes := []management.ResourceServerScope{}

for i := 0; i < 3; i++ {
v := fmt.Sprintf("scope%d", i)
d := fmt.Sprintf("Description for scope%d", i)

mockScopes = append(mockScopes, management.ResourceServerScope{
Value: &v,
Description: &d,
})
}

scopes, didTruncate := getScopes(mockScopes)
assert.Equal(t, "scope0 scope1 scope2", scopes)
assert.False(t, didTruncate)
})

t.Run("should truncate", func(t *testing.T) {
mockScopes := []management.ResourceServerScope{}

for i := 0; i < 100; i++ {
v := fmt.Sprintf("scope%d", i)
d := fmt.Sprintf("Description for scope%d", i)

mockScopes = append(mockScopes, management.ResourceServerScope{
Value: &v,
Description: &d,
})
}

scopes, didTruncate := getScopes(mockScopes)
assert.Equal(t, "scope0 scope1 scope2 scope3 scope4 scope5 scope6...", scopes)
assert.True(t, didTruncate)
})
}

func TestApiView_AsTableHeader(t *testing.T) {
mockAPIView := apiView{}
assert.Equal(t, []string{}, mockAPIView.AsTableHeader())
}

func TestApiView_AsTableRow(t *testing.T) {
mockAPIView := apiView{}
assert.Equal(t, []string{}, mockAPIView.AsTableRow())
}
23 changes: 23 additions & 0 deletions internal/display/custom_domain_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package display

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestCustomDomainView_AsTableHeader(t *testing.T) {
mockCustomDomainView := customDomainView{}

assert.Equal(t, []string{"ID", "Domain", "Status"}, mockCustomDomainView.AsTableHeader())
}

func TestCustomDomainView_AsTableRow(t *testing.T) {
mockCustomDomainView := customDomainView{
ID: "custom-domain-id",
Domain: "example.com",
Status: "verified",
}

assert.Equal(t, []string{"custom-domain-id", "example.com", "verified"}, mockCustomDomainView.AsTableRow())
}
Loading

0 comments on commit ac090d1

Please sign in to comment.