Skip to content

Commit

Permalink
test: adding additional unit tests for query
Browse files Browse the repository at this point in the history
  • Loading branch information
adriantam committed Jun 30, 2023
1 parent 984d913 commit 9d22f32
Show file tree
Hide file tree
Showing 8 changed files with 614 additions and 100 deletions.
49 changes: 31 additions & 18 deletions cmd/query/check.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,46 +19,59 @@ import (
"context"
"encoding/json"
"fmt"
"os"

"github.com/openfga/cli/lib/cmd-utils"
"github.com/openfga/go-sdk/client"
"github.com/spf13/cobra"
)

func check(fgaClient client.SdkClient, user string, relation string, object string) (string, error) {
body := &client.ClientCheckRequest{
User: user,
Relation: relation,
Object: object,
}
options := &client.ClientCheckOptions{}

response, err := fgaClient.Check(context.Background()).Body(*body).Options(*options).Execute()
if err != nil {
fmt.Printf("Failed to check due to %v", err)

return "", fmt.Errorf("failed to check due to %w", err)
}

responseJSON, err := json.Marshal(response)
if err != nil {
fmt.Printf("Failed to check due to %v", err)

return "", fmt.Errorf("failed to check due to %w", err)
}

return string(responseJSON), nil
}

// checkCmd represents the check command.
var checkCmd = &cobra.Command{
Use: "check",
Short: "Check",
Long: "Check if a user has a particular relation with an object.",
Args: cobra.ExactArgs(3), //nolint:gomnd
Run: func(cmd *cobra.Command, args []string) {
RunE: func(cmd *cobra.Command, args []string) error {
clientConfig := cmdutils.GetClientConfig(cmd)
fgaClient, err := clientConfig.GetFgaClient()
if err != nil {
fmt.Printf("Failed to initialize FGA Client due to %v", err)
os.Exit(1)
}

body := &client.ClientCheckRequest{
User: args[0],
Relation: args[1],
Object: args[2],
return fmt.Errorf("failed to initialize FGA Client due to %w", err)
}
options := &client.ClientCheckOptions{}

response, err := fgaClient.Check(context.Background()).Body(*body).Options(*options).Execute()
output, err := check(fgaClient, args[0], args[1], args[2])
if err != nil {
fmt.Printf("Failed to check due to %v", err)
os.Exit(1)
return err
}
fmt.Print(output)

responseJSON, err := json.Marshal(response)
if err != nil {
fmt.Printf("Failed to check due to %v", err)
os.Exit(1)
}
fmt.Print(string(responseJSON))
return nil
},
}

Expand Down
92 changes: 92 additions & 0 deletions cmd/query/check_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package query

import (
"context"
"errors"
"testing"

"github.com/golang/mock/gomock"
mock_client "github.com/openfga/cli/mocks"
openfga "github.com/openfga/go-sdk"
"github.com/openfga/go-sdk/client"
)

var errMockCheck = errors.New("mock error")

func TestCheckWithError(t *testing.T) {
t.Parallel()

mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
mockFgaClient := mock_client.NewMockSdkClient(mockCtrl)

mockExecute := mock_client.NewMockSdkClientCheckRequestInterface(mockCtrl)

var expectedResponse client.ClientCheckResponse

mockExecute.EXPECT().Execute().Return(&expectedResponse, errMockCheck)

mockRequest := mock_client.NewMockSdkClientCheckRequestInterface(mockCtrl)
options := client.ClientCheckOptions{}
mockRequest.EXPECT().Options(options).Return(mockExecute)

mockBody := mock_client.NewMockSdkClientCheckRequestInterface(mockCtrl)

body := client.ClientCheckRequest{
User: "user:foo",
Relation: "writer",
Object: "doc:doc1",
}
mockBody.EXPECT().Body(body).Return(mockRequest)

mockFgaClient.EXPECT().Check(context.Background()).Return(mockBody)

_, err := check(mockFgaClient, "user:foo", "writer", "doc:doc1")
if err == nil {
t.Error("Expect error but there is none")
}
}

func TestCheckWithNoError(t *testing.T) {
t.Parallel()

mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
mockFgaClient := mock_client.NewMockSdkClient(mockCtrl)

mockExecute := mock_client.NewMockSdkClientCheckRequestInterface(mockCtrl)

expectedResponse := client.ClientCheckResponse{
CheckResponse: openfga.CheckResponse{
Allowed: openfga.PtrBool(true),
},
HttpResponse: nil,
}

mockExecute.EXPECT().Execute().Return(&expectedResponse, nil)

mockRequest := mock_client.NewMockSdkClientCheckRequestInterface(mockCtrl)
options := client.ClientCheckOptions{}
mockRequest.EXPECT().Options(options).Return(mockExecute)

mockBody := mock_client.NewMockSdkClientCheckRequestInterface(mockCtrl)

body := client.ClientCheckRequest{
User: "user:foo",
Relation: "writer",
Object: "doc:doc1",
}
mockBody.EXPECT().Body(body).Return(mockRequest)

mockFgaClient.EXPECT().Check(context.Background()).Return(mockBody)

output, err := check(mockFgaClient, "user:foo", "writer", "doc:doc1")
if err != nil {
t.Error(err)
}

expectedOutput := `{"allowed":true}`
if output != expectedOutput {
t.Errorf("Expected output %v actual %v", expectedOutput, output)
}
}
49 changes: 33 additions & 16 deletions cmd/query/expand.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,42 +19,59 @@ import (
"context"
"encoding/json"
"fmt"
"os"

"github.com/openfga/cli/lib/cmd-utils"
"github.com/openfga/go-sdk/client"
"github.com/spf13/cobra"
)

func expand(fgaClient client.SdkClient, relation string, object string) (string, error) {
body := &client.ClientExpandRequest{
Relation: relation,
Object: object,
}

tuples, err := fgaClient.Expand(context.Background()).Body(*body).Execute()
if err != nil {
fmt.Printf("Failed to expand tuples due to %v", err)

return "", fmt.Errorf("failed to expand tuples due to %w", err)
}

tuplesJSON, err := json.Marshal(tuples)
if err != nil {
fmt.Printf("Failed to expand tuples due to %v", err)

return "", fmt.Errorf("failed to expand tuples due to %w", err)
}

return string(tuplesJSON), nil
}

// expandCmd represents the expand command.
var expandCmd = &cobra.Command{
Use: "expand",
Short: "Expand",
Long: "Expands the relationships in userset tree format.",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
RunE: func(cmd *cobra.Command, args []string) error {
clientConfig := cmdutils.GetClientConfig(cmd)

fgaClient, err := clientConfig.GetFgaClient()
if err != nil {
fmt.Printf("Failed to initialize FGA Client due to %v", err)
os.Exit(1)
}
body := &client.ClientExpandRequest{
Relation: args[0],
Object: args[1],
}
tuples, err := fgaClient.Expand(context.Background()).Body(*body).Execute()
if err != nil {
fmt.Printf("Failed to expand tuples due to %v", err)
os.Exit(1)

return fmt.Errorf("failed to initialize FGA Client due to %w", err)
}

tuplesJSON, err := json.Marshal(tuples)
output, err := expand(fgaClient, args[0], args[1])
if err != nil {
fmt.Printf("Failed to expand tuples due to %v", err)
os.Exit(1)
return err
}
fmt.Print(string(tuplesJSON))

fmt.Print(output)

return nil
},
}

Expand Down
87 changes: 87 additions & 0 deletions cmd/query/expand_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package query

import (
"context"
"encoding/json"
"errors"
"reflect"
"testing"

"github.com/golang/mock/gomock"
mock_client "github.com/openfga/cli/mocks"
"github.com/openfga/go-sdk/client"
)

var errMockExpand = errors.New("mock error")

func TestExpandWithError(t *testing.T) {
t.Parallel()

mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
mockFgaClient := mock_client.NewMockSdkClient(mockCtrl)

mockExecute := mock_client.NewMockSdkClientExpandRequestInterface(mockCtrl)

var expectedResponse client.ClientExpandResponse

mockExecute.EXPECT().Execute().Return(&expectedResponse, errMockExpand)

mockBody := mock_client.NewMockSdkClientExpandRequestInterface(mockCtrl)

body := client.ClientExpandRequest{
Relation: "writer",
Object: "doc:doc1",
}
mockBody.EXPECT().Body(body).Return(mockExecute)

mockFgaClient.EXPECT().Expand(context.Background()).Return(mockBody)

_, err := expand(mockFgaClient, "writer", "doc:doc1")
if err == nil {
t.Error("Expect error but there is none")
}
}

func TestExpandWithNoError(t *testing.T) {
t.Parallel()

mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
mockFgaClient := mock_client.NewMockSdkClient(mockCtrl)

mockExecute := mock_client.NewMockSdkClientExpandRequestInterface(mockCtrl)

expandResponseTxt := `{"tree":{"root":{"name":"document:roadmap#viewer","union":{"nodes":[{"name": "document:roadmap#viewer","leaf":{"users":{"users":["user:81684243-9356-4421-8fbf-a4f8d36aa31b"]}}}]}}}}` //nolint:all

expectedResponse := client.ClientExpandResponse{}
if err := json.Unmarshal([]byte(expandResponseTxt), &expectedResponse); err != nil {
t.Fatalf("%v", err)
}

mockExecute.EXPECT().Execute().Return(&expectedResponse, nil)

mockBody := mock_client.NewMockSdkClientExpandRequestInterface(mockCtrl)

body := client.ClientExpandRequest{
Relation: "writer",
Object: "doc:doc1",
}
mockBody.EXPECT().Body(body).Return(mockExecute)

mockFgaClient.EXPECT().Expand(context.Background()).Return(mockBody)

output, err := expand(mockFgaClient, "writer", "doc:doc1")
if err != nil {
t.Error(err)
}

outputResponse := client.ClientExpandResponse{}
if err := json.Unmarshal([]byte(output), &outputResponse); err != nil {
t.Errorf("%v", err)
}

if !(reflect.DeepEqual(outputResponse, expectedResponse)) {
t.Errorf("Expect output response %v actual response %v", expandResponseTxt, output)
}
}
Loading

0 comments on commit 9d22f32

Please sign in to comment.