Skip to content

Commit

Permalink
Add path validation and fix broken tests for analyse command.
Browse files Browse the repository at this point in the history
  • Loading branch information
robinmitra committed Apr 22, 2019
1 parent 2a4ce2a commit 6fa1b25
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 8 deletions.
14 changes: 13 additions & 1 deletion cmd/analyse/analyse.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package analyse

import (
"errors"
"fmt"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"os"
)

type options struct {
Expand All @@ -22,7 +25,16 @@ func (o *options) initialise(cmd *cobra.Command, args []string) {
}

func (o *options) validate() {
return
if err := o.validatePath(os.Stat(o.root)); err != nil {
log.Fatal(err)
}
}

func (o *options) validatePath(info os.FileInfo, err error) error {
if os.IsNotExist(err) {
return errors.New(fmt.Sprintf("Directory \"%s\" does not exist", o.root))
}
return err
}

func (o *options) run() {
Expand Down
25 changes: 18 additions & 7 deletions cmd/analyse/analyse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package analyse
import (
"bytes"
"errors"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"os"
"path/filepath"
Expand All @@ -27,21 +28,31 @@ func (f fileInfoMock) Mode() os.FileMode {
}
func (f fileInfoMock) Sys() interface{} { return nil }

func TestInvalidArgs(t *testing.T) {
func init() {
log.SetLevel(log.ErrorLevel)
}

func TestInvalidPath(t *testing.T) {
cmd := cobra.Command{}
var args []string
err := validate(&cmd, args)
o := options{}
o.initialise(&cmd, args)
var info os.FileInfo
err := o.validatePath(info, errors.New("something went wrong"))
if err == nil {
t.Errorf("Expected validation to fail when passing invalid arguments.")
t.Errorf("Expected validation to fail when passing invalid path.")
}
}

func TestValidArgs(t *testing.T) {
func TestValidPath(t *testing.T) {
cmd := cobra.Command{}
args := []string{"some-path"}
err := validate(&cmd, args)
var args []string
o := options{}
o.initialise(&cmd, args)
var info os.FileInfo
err := o.validatePath(info, nil)
if err != nil {
t.Errorf("Expected validation to fail when passing invalid arguments.")
t.Errorf("Expected validation to pass when passing valid path.")
}
}

Expand Down

0 comments on commit 6fa1b25

Please sign in to comment.