Skip to content

Commit

Permalink
test: add command tests (#487)
Browse files Browse the repository at this point in the history
  • Loading branch information
zepatrik authored Mar 15, 2021
1 parent 40563cc commit 61c28e4
Show file tree
Hide file tree
Showing 14 changed files with 251 additions and 15 deletions.
4 changes: 2 additions & 2 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ jobs:
- go/save-cache

# Tests
- run: .bin/go-acc -o coverage.txt ./... -- -v -tags sqlite
- run: .bin/go-acc -o coverage.txt ./... -- -v -tags sqlite -p 1

# Submit coverage details
- run: test -z "$CIRCLE_PR_NUMBER" && .bin/goveralls -service=circle-ci -coverprofile=coverage.txt -repotoken=$COVERALLS_REPO_TOKEN || echo "forks are not allowed to push to coveralls"
Expand All @@ -57,7 +57,7 @@ jobs:
- go/mod-download
- run: go mod tidy
- go/save-cache
- run: go test -tags sqlite -race -short -v ./...
- run: go test -tags sqlite -race -short -v -p 1 ./...

validate:
docker:
Expand Down
2 changes: 1 addition & 1 deletion cmd/check/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ func newCheckCmd() *cobra.Command {
return err
}

cmdx.PrintJSONAble(cmd, &checkOutput{resp.Allowed})
cmdx.PrintJSONAble(cmd, &checkOutput{Allowed: resp.Allowed})
return nil
},
}
Expand Down
19 changes: 19 additions & 0 deletions cmd/check/root_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package check

import (
"testing"

"github.com/stretchr/testify/assert"

"github.com/ory/keto/cmd/client"
"github.com/ory/keto/internal/namespace"
)

func TestCheckCommand(t *testing.T) {
nspace := &namespace.Namespace{Name: t.Name()}
ts := client.NewTestServer(t, client.ReadServer, []*namespace.Namespace{nspace}, newCheckCmd)
defer ts.Shutdown(t)

stdOut := ts.Cmd.ExecNoErr(t, "subject", "access", nspace.Name, "object")
assert.Equal(t, "Denied\n", stdOut)
}
11 changes: 10 additions & 1 deletion cmd/client/grpc_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,16 @@ import (
"google.golang.org/grpc"
)

type contextKeys string

const (
FlagReadRemote = "read-remote"
FlagWriteRemote = "write-remote"

EnvReadRemote = "KETO_READ_REMOTE"
EnvWriteRemote = "KETO_WRITE_REMOTE"

ContextKeyTimeout contextKeys = "timeout"
)

func getRemote(cmd *cobra.Command, flagRemote, envRemote string) string {
Expand All @@ -43,7 +47,12 @@ func GetWriteConn(cmd *cobra.Command) (*grpc.ClientConn, error) {
}

func Conn(ctx context.Context, remote string) (*grpc.ClientConn, error) {
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
timeout := 3 * time.Second
if d, ok := ctx.Value(ContextKeyTimeout).(time.Duration); ok {
timeout = d
}

ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
return grpc.DialContext(ctx, remote, grpc.WithInsecure(), grpc.WithBlock(), grpc.WithDisableHealthCheck())
}
Expand Down
75 changes: 75 additions & 0 deletions cmd/client/test_helpers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package client

import (
"net"
"testing"

"github.com/ory/x/cmdx"
"github.com/spf13/cobra"
"github.com/stretchr/testify/require"
"golang.org/x/sync/errgroup"
"google.golang.org/grpc"

"github.com/ory/keto/internal/driver"
"github.com/ory/keto/internal/namespace"
)

type (
TestServer struct {
Reg driver.Registry
Namespace *namespace.Namespace
Addr, FlagRemote string
Cmd *cmdx.CommandExecuter
Server *grpc.Server
NewServer func() *grpc.Server

errG *errgroup.Group
}
ServerType string
)

const (
WriteServer ServerType = "write"
ReadServer ServerType = "read"
)

func NewTestServer(t *testing.T, rw ServerType, nspaces []*namespace.Namespace, newCmd func() *cobra.Command) *TestServer {
ts := &TestServer{
Reg: driver.NewMemoryTestRegistry(t, nspaces),
}

switch rw {
case ReadServer:
ts.NewServer = ts.Reg.ReadGRPCServer
ts.FlagRemote = FlagReadRemote
case WriteServer:
ts.NewServer = ts.Reg.WriteGRPCServer
ts.FlagRemote = FlagWriteRemote
default:
t.Logf("Got unknown server type %s", rw)
t.FailNow()
}

ts.Server = ts.NewServer()

l, err := net.Listen("tcp", "127.0.0.1:0")
require.NoError(t, err)
ts.Addr = l.Addr().String()

ts.errG = &errgroup.Group{}
ts.errG.Go(func() error {
return ts.Server.Serve(l)
})

ts.Cmd = &cmdx.CommandExecuter{
New: newCmd,
PersistentArgs: []string{"--" + ts.FlagRemote, ts.Addr},
}

return ts
}

func (ts *TestServer) Shutdown(t *testing.T) {
ts.Server.GracefulStop()
require.NoError(t, ts.errG.Wait())
}
21 changes: 21 additions & 0 deletions cmd/expand/root_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package expand

import (
"testing"

"github.com/ory/x/cmdx"
"github.com/stretchr/testify/assert"

"github.com/ory/keto/cmd/client"
"github.com/ory/keto/internal/namespace"
)

func TestExpandCommand(t *testing.T) {
nspace := &namespace.Namespace{Name: t.Name()}
ts := client.NewTestServer(t, client.ReadServer, []*namespace.Namespace{nspace}, NewExpandCmd)
defer ts.Shutdown(t)

ts.Cmd.PersistentArgs = append(ts.Cmd.PersistentArgs, "--"+cmdx.FlagFormat, string(cmdx.FormatJSON))
stdOut := ts.Cmd.ExecNoErr(t, "access", nspace.Name, "object")
assert.Equal(t, "null\n", stdOut)
}
8 changes: 8 additions & 0 deletions cmd/migrate/down.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"fmt"
"strconv"

"github.com/ory/x/flagx"

"github.com/ory/x/cmdx"
"github.com/spf13/cobra"

Expand Down Expand Up @@ -35,6 +37,11 @@ func newDownCmd() *cobra.Command {
}
cmdx.PrintTable(cmd, s)

if !flagx.MustGetBool(cmd, FlagYes) && !cmdx.AskForConfirmation("Do you really want to migrate down? This will delete data.", cmd.InOrStdin(), cmd.OutOrStdout()) {
_, _ = fmt.Fprintln(cmd.OutOrStdout(), "Migration aborted.")
return nil
}

if err := reg.Migrator().MigrateDown(ctx, int(steps)); err != nil {
_, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Could apply down migrations: %+v\n", err)
return cmdx.FailSilently(cmd)
Expand All @@ -51,6 +58,7 @@ func newDownCmd() *cobra.Command {
},
}

registerYesFlag(cmd.Flags())
cmdx.RegisterFormatFlags(cmd.Flags())

return cmd
Expand Down
8 changes: 4 additions & 4 deletions cmd/migrate/migrate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,10 @@ func TestMigrate(t *testing.T) {

t.Cleanup(func() {
// migrate all down
cmd.ExecNoErr(t, "down", "0")
t.Log(cmd.ExecNoErr(t, "down", "0", "--"+FlagYes))
})

parts := strings.Split(stdOut, "Do you want to apply above planned migrations?")
parts := strings.Split(stdOut, "Are you sure that you want to apply this migration?")
require.Len(t, parts, 2)

assertNoneApplied(t, parts[0])
Expand All @@ -115,7 +115,7 @@ func TestMigrate(t *testing.T) {

t.Cleanup(func() {
// migrate all down
cmd.ExecNoErr(t, "down", "0")
t.Log(cmd.ExecNoErr(t, "down", "0", "--"+FlagYes))
})

parts := strings.Split(out, "Applying migrations...")
Expand All @@ -130,7 +130,7 @@ func TestMigrate(t *testing.T) {

t.Cleanup(func() {
// migrate all down
cmd.ExecNoErr(t, "down", "0")
t.Log(cmd.ExecNoErr(t, "down", "0", "--"+FlagYes))
})

parts := strings.Split(out, "Applying migrations...")
Expand Down
16 changes: 12 additions & 4 deletions cmd/migrate/up.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ package migrate
import (
"fmt"

"github.com/ory/x/flagx"

"github.com/spf13/pflag"

"github.com/pkg/errors"

"github.com/ory/x/cmdx"
Expand All @@ -17,7 +21,7 @@ const (
)

func newUpCmd() *cobra.Command {
var yes, allNamespaces bool
var allNamespaces bool

cmd := &cobra.Command{
Use: "up",
Expand All @@ -43,7 +47,7 @@ func newUpCmd() *cobra.Command {
return nil
}

if !yes && !cmdx.AskForConfirmation("Do you want to apply above planned migrations?", cmd.InOrStdin(), cmd.OutOrStdout()) {
if !flagx.MustGetBool(cmd, FlagYes) && !cmdx.AskForConfirmation("Are you sure that you want to apply this migration? Make sure to check the CHANGELOG.md for breaking changes beforehand.", cmd.InOrStdin(), cmd.OutOrStdout()) {
_, _ = fmt.Fprintln(cmd.OutOrStdout(), "Aborting")
return nil
}
Expand Down Expand Up @@ -95,7 +99,7 @@ func newUpCmd() *cobra.Command {
continue
}

if !yes && !cmdx.AskForConfirmation(fmt.Sprintf("Do you want to apply above planned migrations for namespace %s?", nspace.Name), cmd.InOrStdin(), cmd.OutOrStdout()) {
if !flagx.MustGetBool(cmd, FlagYes) && !cmdx.AskForConfirmation(fmt.Sprintf("Do you want to apply above planned migrations for namespace %s?", nspace.Name), cmd.InOrStdin(), cmd.OutOrStdout()) {
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "Skipping namespace %s\n", nspace.Name)
continue
}
Expand All @@ -112,10 +116,14 @@ func newUpCmd() *cobra.Command {
},
}

cmd.Flags().BoolVarP(&yes, FlagYes, "y", false, "yes to all questions, no user input required")
registerYesFlag(cmd.Flags())
cmd.Flags().BoolVar(&allNamespaces, FlagAllNamespace, false, "migrate all pending namespaces as well")

cmdx.RegisterFormatFlags(cmd.Flags())

return cmd
}

func registerYesFlag(flags *pflag.FlagSet) {
flags.BoolP(FlagYes, "y", false, "yes to all questions, no user input required")
}
16 changes: 15 additions & 1 deletion cmd/namespace/migrate_down.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ package namespace

import (
"fmt"
"strconv"

"github.com/ory/x/flagx"

"github.com/ory/x/cmdx"
"github.com/spf13/cobra"
Expand All @@ -17,6 +20,12 @@ func NewMigrateDownCmd() *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()

steps, err := strconv.ParseInt(args[1], 0, 0)
if err != nil {
// return this error so it gets printed along the usage
return fmt.Errorf("malformed argument %s for <steps>: %+v", args[0], err)
}

reg, err := driver.NewDefaultRegistry(ctx, cmd.Flags())
if err != nil {
return err
Expand All @@ -34,7 +43,12 @@ func NewMigrateDownCmd() *cobra.Command {
return cmdx.FailSilently(cmd)
}

if err := reg.NamespaceMigrator().MigrateNamespaceDown(ctx, n, 0); err != nil {
if !flagx.MustGetBool(cmd, YesFlag) && !cmdx.AskForConfirmation(fmt.Sprintf("Do you really want to delete namespace %s? This will irrecoverably delete all relation tuples within the namespace.", n.Name), cmd.InOrStdin(), cmd.OutOrStdout()) {
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "Migration of namespace \"%s\" aborted.\n", n.Name)
return nil
}

if err := reg.NamespaceMigrator().MigrateNamespaceDown(ctx, n, int(steps)); err != nil {
_, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Could not apply namespace migration: %+v\n", err)
return cmdx.FailSilently(cmd)
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/namespace/migrate_up.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func NewMigrateUpCmd() *cobra.Command {
}

if !flagx.MustGetBool(cmd, YesFlag) {
if !cmdx.AskForConfirmation("Are you sure that you want to apply this migration? Make sure to check the CHANGELOG.md and UPGRADE.md for breaking changes beforehand.", cmd.InOrStdin(), cmd.OutOrStdout()) {
if !cmdx.AskForConfirmation("Are you sure that you want to apply this migration? Make sure to check the CHANGELOG.md for breaking changes beforehand.", cmd.InOrStdin(), cmd.OutOrStdout()) {
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "Migration of namespace \"%s\" aborted.\n", n.Name)
return nil
}
Expand Down
6 changes: 5 additions & 1 deletion cmd/status/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,10 @@ func newStatusCmd() *cobra.Command {
GetStatus() grpcHealthV1.HealthCheckResponse_ServingStatus
}
if block {
wc, err := c.Watch(cmd.Context(), &grpcHealthV1.HealthCheckRequest{})
ctx, cancel := context.WithCancel(cmd.Context())
defer cancel()

wc, err := c.Watch(ctx, &grpcHealthV1.HealthCheckRequest{})
if err != nil {
_, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Could not start watching the status: %+v\n", err)
return cmdx.FailSilently(cmd)
Expand All @@ -87,6 +90,7 @@ func newStatusCmd() *cobra.Command {
}

if status.GetStatus() == grpcHealthV1.HealthCheckResponse_SERVING {
cancel()
break
}

Expand Down
Loading

0 comments on commit 61c28e4

Please sign in to comment.