Skip to content

Commit

Permalink
add test for formatting/rejecting relative path in filetree
Browse files Browse the repository at this point in the history
  • Loading branch information
wagoodman committed Nov 19, 2019
1 parent ed57565 commit 17742e7
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
11 changes: 8 additions & 3 deletions dive/filetree/file_tree.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package filetree

import (
"fmt"
"path"
"sort"
"strings"

Expand Down Expand Up @@ -240,8 +241,12 @@ func (tree *FileTree) GetNode(path string) (*FileNode, error) {
}

// AddPath adds a new node to the tree with the given payload
func (tree *FileTree) AddPath(path string, data FileInfo) (*FileNode, []*FileNode, error) {
nodeNames := strings.Split(strings.Trim(path, "/"), "/")
func (tree *FileTree) AddPath(filepath string, data FileInfo) (*FileNode, []*FileNode, error) {
filepath = path.Clean(filepath)
if filepath == "." {
return nil, nil, fmt.Errorf("cannot add relative path '%s'", filepath)
}
nodeNames := strings.Split(strings.Trim(filepath, "/"), "/")
node := tree.Root
addedNodes := make([]*FileNode, 0)
for idx, name := range nodeNames {
Expand All @@ -264,7 +269,7 @@ func (tree *FileTree) AddPath(path string, data FileInfo) (*FileNode, []*FileNod

if node == nil {
// the child could not be added
return node, addedNodes, fmt.Errorf(fmt.Sprintf("could not add child node: '%s' (path:'%s')", name, path))
return node, addedNodes, fmt.Errorf(fmt.Sprintf("could not add child node: '%s' (path:'%s')", name, filepath))
}
}

Expand Down
34 changes: 34 additions & 0 deletions dive/filetree/file_tree_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,40 @@ func TestStringBetween(t *testing.T) {

}

func TestRejectPurelyRelativePath(t *testing.T) {
tree := NewFileTree()
_, _, err := tree.AddPath("./etc/nginx/nginx.conf", FileInfo{})
if err != nil {
t.Errorf("could not setup test: %v", err)
}
_, _, err = tree.AddPath("./", FileInfo{})

if err == nil {
t.Errorf("expected to reject relative path, but did not")
}

}

func TestAddRelativePath(t *testing.T) {
tree := NewFileTree()
_, _, err := tree.AddPath("./etc/nginx/nginx.conf", FileInfo{})
if err != nil {
t.Errorf("could not setup test: %v", err)
}

expected :=
`└── etc
└── nginx
└── nginx.conf
`
actual := tree.String(false)

if expected != actual {
t.Errorf("Expected tree string:\n--->%s<---\nGot:\n--->%s<---", expected, actual)
}

}

func TestAddPath(t *testing.T) {
tree := NewFileTree()
_, _, err := tree.AddPath("/etc/nginx/nginx.conf", FileInfo{})
Expand Down

0 comments on commit 17742e7

Please sign in to comment.