Skip to content

Commit

Permalink
fix encrypt input error check (#247)
Browse files Browse the repository at this point in the history
fix cape encrypt error check
  • Loading branch information
eric-capeprivacy authored Feb 27, 2023
1 parent 74a2c76 commit 7b747fb
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
6 changes: 4 additions & 2 deletions cmd/cape/cmd/encrypt.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ func encrypt(cmd *cobra.Command, args []string) error {
}

input, userError := parseInput(cmd, args)
if err != nil {
if userError != nil {
return userError
}

Expand Down Expand Up @@ -117,10 +117,12 @@ func parseInput(cmd *cobra.Command, args []string) ([]byte, *UserError) {
case len(args) == 1:
// read input from command line string
input = []byte(args[0])
if len(input) == 0 {
return nil, &UserError{Msg: "unable to encrypt", Err: errors.New("input is empty")}
}
default:
return nil, &UserError{Msg: "invalid input", Err: errors.New("please provide input as a string, input file or stdin")}
}

return input, nil
}

Expand Down
42 changes: 42 additions & 0 deletions cmd/cape/cmd/encrypt_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package cmd

import (
"errors"
"fmt"
"testing"

"github.com/capeprivacy/cli/sdk"
Expand All @@ -22,3 +24,43 @@ func TestEncrypt(t *testing.T) {
t.Fatalf("didn't get expected output, got %s, wanted %s", got, want)
}
}

func TestEncryptBadInput(t *testing.T) {
for _, tt := range []struct {
name string
args []string
wantError error
}{
{
name: "empty input",
args: []string{"encrypt", "", "--username", "bendecoste"},
wantError: UserError{Msg: "unable to encrypt", Err: errors.New("input is empty")},
},
{
name: "too many inputs",
args: []string{"encrypt", "", "", "--username", "bendecoste"},
wantError: UserError{Msg: "you must pass in only one input data (stdin, string or filename)", Err: fmt.Errorf("invalid number of input arguments")},
},
{
name: "no file input",
args: []string{"encrypt", "-f", "", "--username", "bendecoste"},
wantError: UserError{Msg: "invalid input", Err: errors.New("please provide input as a string, input file or stdin")},
},
{
name: "bad file input",
args: []string{"encrypt", "-f", "nofile.txt", "--username", "bendecoste"},
wantError: &UserError{Msg: "unable to read data file", Err: errors.New("open nofile.txt: no such file or directory")},
},
} {
t.Run(tt.name, func(t *testing.T) {
capeEncrypt = func(message, username string, options ...sdk.Option) (string, error) {
return "cape:secret", nil
}
cmd, _, _ := getCmd()
cmd.SetArgs(tt.args)
if err := cmd.Execute(); err.Error() != tt.wantError.Error() {
t.Fatalf("expected error: %s, got: %s", tt.wantError.Error(), err.Error())
}
})
}
}

0 comments on commit 7b747fb

Please sign in to comment.