add test for formatting/rejecting relative path in filetree

This commit is contained in:
Alex Goodman 2019-11-19 10:13:26 -08:00
parent ed57565910
commit 17742e7b6c
No known key found for this signature in database
GPG Key ID: 150587AB82D3C4E6
2 changed files with 42 additions and 3 deletions

View File

@ -2,6 +2,7 @@ package filetree
import (
"fmt"
"path"
"sort"
"strings"
@ -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 {
@ -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))
}
}

View File

@ -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{})