Skip to content

Commit

Permalink
tests: add unit tests for delete rules engine
Browse files Browse the repository at this point in the history
  • Loading branch information
PatrickMenoti committed Jul 3, 2024
1 parent cdcca68 commit 5b62783
Show file tree
Hide file tree
Showing 2 changed files with 202 additions and 65 deletions.
84 changes: 52 additions & 32 deletions pkg/cmd/delete/rules_engine/rules_engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,93 +9,113 @@ import (
msg "github.com/aziontech/azion-cli/messages/delete/rules_engine"
api "github.com/aziontech/azion-cli/pkg/api/rules_engine"
"github.com/aziontech/azion-cli/pkg/cmdutil"
"github.com/aziontech/azion-cli/pkg/iostreams"
"github.com/aziontech/azion-cli/pkg/logger"
"github.com/aziontech/azion-cli/pkg/output"
"github.com/aziontech/azion-cli/utils"
"github.com/spf13/cobra"
"go.uber.org/zap"
)

func NewCmd(f *cmdutil.Factory) *cobra.Command {
var rule_id int64
var app_id int64
var phase string
cmd := &cobra.Command{
var (
ruleID int64
applicationID int64
phase string
)

type DeleteCmd struct {
Io *iostreams.IOStreams
ReadInput func(string) (string, error)
DeleteRule func(context.Context, int64, int64, string) error
AskInput func(string) (string, error)
}

func NewDeleteCmd(f *cmdutil.Factory) *DeleteCmd {
return &DeleteCmd{
Io: f.IOStreams,
ReadInput: func(prompt string) (string, error) {
return utils.AskInput(prompt)
},
DeleteRule: func(ctx context.Context, ruleID, appID int64, phase string) error {
client := api.NewClient(f.HttpClient, f.Config.GetString("api_url"), f.Config.GetString("token"))
return client.Delete(ctx, appID, phase, ruleID)
},
AskInput: utils.AskInput,
}
}

func NewCobraCmd(delete *DeleteCmd, f *cmdutil.Factory) *cobra.Command {
cobraCmd := &cobra.Command{
Use: msg.Usage,
Short: msg.ShortDescription,
Long: msg.LongDescription,
SilenceUsage: true,
SilenceErrors: true,
Example: heredoc.Doc(`
$ azion delete rules-engine --rule-id 1234 --application-id 99887766 --phase request
$ azion delete rules-engine
`),
$ azion delete rules-engine --rule-id 1234 --application-id 99887766 --phase request
$ azion delete rules-engine
`),
RunE: func(cmd *cobra.Command, args []string) error {
if !cmd.Flags().Changed("rule-id") {
var err error

answer, err := utils.AskInput(msg.AskInputRulesId)
if !cmd.Flags().Changed("rule-id") {
answer, err := delete.AskInput(msg.AskInputRulesId)
if err != nil {
return err
}

num, err := strconv.ParseInt(answer, 10, 64)
if err != nil {
logger.Debug("Error while converting answer to int64", zap.Error(err))
return msg.ErrorConvertIdRule
}

rule_id = num
ruleID = num
}

if !cmd.Flags().Changed("application-id") {

answer, err := utils.AskInput(msg.AskInputApplicationId)
answer, err := delete.AskInput(msg.AskInputApplicationId)
if err != nil {
return err
}

num, err := strconv.ParseInt(answer, 10, 64)
if err != nil {
logger.Debug("Error while converting answer to int64", zap.Error(err))
return msg.ErrorConvertIdRule
return msg.ErrorConvertIdApplication
}

app_id = num
applicationID = num
}

if !cmd.Flags().Changed("phase") {

answer, err := utils.AskInput(msg.AskInputPhase)
answer, err := delete.AskInput(msg.AskInputPhase)
if err != nil {
return err
}

phase = answer
}

client := api.NewClient(f.HttpClient, f.Config.GetString("api_url"), f.Config.GetString("token"))

ctx := context.Background()

err := client.Delete(ctx, app_id, phase, rule_id)
err = delete.DeleteRule(ctx, ruleID, applicationID, phase)
if err != nil {
return fmt.Errorf(msg.ErrorFailToDelete.Error(), err)
}

deleteOut := output.GeneralOutput{
Msg: fmt.Sprintf(msg.DeleteOutputSuccess, rule_id),
Msg: fmt.Sprintf(msg.DeleteOutputSuccess, ruleID),
Out: f.IOStreams.Out,
Flags: f.Flags,
}
return output.Print(&deleteOut)

},
}

cmd.Flags().Int64Var(&rule_id, "rule-id", 0, msg.FlagRuleID)
cmd.Flags().Int64Var(&app_id, "application-id", 0, msg.FlagAppID)
cmd.Flags().StringVar(&phase, "phase", "", msg.FlagPhase)
cmd.Flags().BoolP("help", "h", false, msg.HelpFlag)
cobraCmd.Flags().Int64Var(&ruleID, "rule-id", 0, msg.FlagRuleID)
cobraCmd.Flags().Int64Var(&applicationID, "application-id", 0, msg.FlagAppID)
cobraCmd.Flags().StringVar(&phase, "phase", "", msg.FlagPhase)
cobraCmd.Flags().BoolP("help", "h", false, msg.HelpFlag)

return cmd
return cobraCmd
}

func NewCmd(f *cmdutil.Factory) *cobra.Command {
return NewCobraCmd(NewDeleteCmd(f), f)
}
183 changes: 150 additions & 33 deletions pkg/cmd/delete/rules_engine/rules_engine_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"testing"

"github.com/aziontech/azion-cli/pkg/logger"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"

msg "github.com/aziontech/azion-cli/messages/delete/rules_engine"
Expand All @@ -14,38 +15,154 @@ import (
"github.com/stretchr/testify/require"
)

func TestCreate(t *testing.T) {
func mockAppID(msg string) (string, error) {
return "4321", nil
}

func mockRuleID(msg string) (string, error) {
return "1234", nil
}

func mockPhase(msg string) (string, error) {
return "request", nil
}

func mockInvalid(msg string) (string, error) {
return "invalid", nil
}

func TestDeleteWithAskInput(t *testing.T) {
logger.New(zapcore.DebugLevel)
t.Run("delete rules engine with success", func(t *testing.T) {
mock := &httpmock.Registry{}

mock.Register(
httpmock.REST("DELETE", "edge_applications/4321/rules_engine/request/rules/1234"),
httpmock.StatusStringResponse(204, ""),
)

f, stdout, _ := testutils.NewFactory(mock)
cmd := NewCmd(f)
cmd.SetArgs([]string{"--application-id", "4321", "--phase", "request", "--rule-id", "1234"})

_, err := cmd.ExecuteC()
require.NoError(t, err)
assert.Equal(t, fmt.Sprintf(msg.DeleteOutputSuccess, 1234), stdout.String())
})

t.Run("delete rules engine that is not found", func(t *testing.T) {
mock := &httpmock.Registry{}

mock.Register(
httpmock.REST("DELETE", "edge_applications/4321/rules_engine/request/rules/1234"),
httpmock.StatusStringResponse(404, "Not Found"),
)

f, _, _ := testutils.NewFactory(mock)
cmd := NewCmd(f)
cmd.SetArgs([]string{"--rule-id", "1234", "--application-id", "4321", "--phase", "response"})

_, err := cmd.ExecuteC()
require.Error(t, err)
})

tests := []struct {
name string
applicationID string
ruleID string
phase string
method string
endpoint string
statusCode int
responseBody string
expectedOutput string
expectError bool
mockInputs func(msg string) (string, error)
mockError error
}{
{
name: "ask for application id and rule id success",
applicationID: "4321",
ruleID: "1234",
phase: "request",
method: "DELETE",
endpoint: "edge_applications/4321/rules_engine/request/rules/1234",
statusCode: 204,
responseBody: "",
expectedOutput: fmt.Sprintf(msg.DeleteOutputSuccess, 1234),
expectError: false,
mockInputs: mockAppID,
mockError: nil,
},
{
name: "ask for rule id success",
phase: "request",
applicationID: "4321",
method: "DELETE",
endpoint: "edge_applications/4321/rules_engine/request/rules/1234",
statusCode: 204,
responseBody: "",
expectedOutput: fmt.Sprintf(msg.DeleteOutputSuccess, 1234),
expectError: false,
mockInputs: mockRuleID,
mockError: nil,
},
{
name: "ask for phase success",
applicationID: "4321",
ruleID: "1234",
method: "DELETE",
endpoint: "edge_applications/4321/rules_engine/request/rules/1234",
statusCode: 204,
responseBody: "",
expectedOutput: fmt.Sprintf(msg.DeleteOutputSuccess, 1234),
expectError: false,
mockInputs: mockPhase,
mockError: nil,
},
{
name: "error in input",
applicationID: "invalid",
ruleID: "1234",
phase: "request",
method: "DELETE",
endpoint: "edge_applications/invalid/rules_engine/request/rules/1234",
statusCode: 400,
responseBody: "Bad Request",
expectedOutput: "",
expectError: true,
mockInputs: mockInvalid,
mockError: fmt.Errorf("invalid argument \"\" for \"--application-id\" flag: strconv.ParseInt: parsing \"\": invalid syntax"),
},
{
name: "error in input",
phase: "request",
ruleID: "1234",
method: "DELETE",
endpoint: "edge_applications/invalid/rules_engine/request/rules/1234",
statusCode: 400,
responseBody: "Bad Request",
expectedOutput: "",
expectError: true,
mockInputs: mockInvalid,
mockError: fmt.Errorf("invalid argument \"\" for \"--application-id\" flag: strconv.ParseInt: parsing \"\": invalid syntax"),
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
mock := &httpmock.Registry{}
mock.Register(
httpmock.REST(tt.method, tt.endpoint),
httpmock.StatusStringResponse(tt.statusCode, tt.responseBody),
)

f, stdout, _ := testutils.NewFactory(mock)

// Create your delete command instance (adjust as per your package structure)
deleteCmd := NewDeleteCmd(f)
deleteCmd.AskInput = tt.mockInputs

// Create your Cobra command instance (adjust as per your package structure)
cobraCmd := NewCobraCmd(deleteCmd, f)

// Set command line arguments based on test case
if tt.applicationID != "" && tt.ruleID != "" && tt.phase != "" {
cobraCmd.SetArgs([]string{"--application-id", tt.applicationID, "--rule-id", tt.ruleID, "--phase", tt.phase})
} else if tt.applicationID != "" && tt.ruleID != "" {
cobraCmd.SetArgs([]string{"--application-id", tt.applicationID, "--rule-id", tt.ruleID})
} else if tt.applicationID != "" && tt.phase != "" {
cobraCmd.SetArgs([]string{"--application-id", tt.applicationID, "--phase", tt.phase})
} else if tt.ruleID != "" && tt.phase != "" {
cobraCmd.SetArgs([]string{"--rule-id", tt.ruleID, "--phase", tt.phase})
} else if tt.applicationID != "" {
cobraCmd.SetArgs([]string{"--application-id", tt.applicationID})
} else if tt.ruleID != "" {
cobraCmd.SetArgs([]string{"--rule-id", tt.ruleID})
} else if tt.phase != "" {
cobraCmd.SetArgs([]string{"--phase", tt.phase})
}

// Execute the command
_, err := cobraCmd.ExecuteC()

// Validate the results
if tt.expectError {
require.Error(t, err)
logger.Debug("Expected error occurred", zap.Error(err))
} else {
require.NoError(t, err)
assert.Equal(t, tt.expectedOutput, stdout.String())
logger.Debug("Expected output", zap.String("output", stdout.String()))
}
})
}
}

0 comments on commit 5b62783

Please sign in to comment.