Function that finds container with a specific ID.

This commit is contained in:
Jakub Sobon 2019-03-28 23:04:34 -04:00
parent 0f0f1d4bc8
commit 85bcf9d8d9
No known key found for this signature in database
GPG Key ID: F2451A77FB05D3B7
2 changed files with 88 additions and 0 deletions

View File

@ -14,6 +14,11 @@
package container
import (
"errors"
"fmt"
)
// traversal.go provides functions that navigate the container tree.
// rootCont returns the root container.
@ -56,3 +61,26 @@ func postOrder(c *Container, errStr *string, visit visitFunc) {
return
}
}
// findID finds container with the provided ID.
// Returns an error of there is no container with the specified ID.
func findID(root *Container, id string) (*Container, error) {
if id == "" {
return nil, errors.New("the container ID must not be empty")
}
var (
errStr string
cont *Container
)
preOrder(root, &errStr, visitFunc(func(c *Container) error {
if c.opts.id == id {
cont = c
}
return nil
}))
if cont == nil {
return nil, fmt.Errorf("cannot find container with ID %q", id)
}
return cont, nil
}

View File

@ -165,3 +165,63 @@ func TestTraversal(t *testing.T) {
})
}
}
func TestFindID(t *testing.T) {
tests := []struct {
desc string
container func(ft *faketerm.Terminal) (*Container, error)
id string
wantFound bool
wantErr bool
}{
{
desc: "fails when searching with empty ID",
container: func(ft *faketerm.Terminal) (*Container, error) {
return New(ft)
},
wantErr: true,
},
{
desc: "no container with the specified ID",
container: func(ft *faketerm.Terminal) (*Container, error) {
return New(ft)
},
id: "mycont",
wantErr: true,
},
{
desc: "finds the container",
container: func(ft *faketerm.Terminal) (*Container, error) {
return New(ft, ID("mycont"))
},
id: "mycont",
wantFound: true,
},
}
for _, tc := range tests {
t.Run(tc.desc, func(t *testing.T) {
ft, err := faketerm.New(image.Point{10, 10})
if err != nil {
t.Fatalf("faketerm.New => unexpected error: %v", err)
}
cont, err := tc.container(ft)
if err != nil {
t.Fatalf("tc.container => unexpected error: %v", err)
}
got, err := findID(cont, tc.id)
if (err != nil) != tc.wantErr {
t.Errorf("findID => unexpected error: %v, wantErr: %v", err, tc.wantErr)
}
if err != nil {
return
}
if (got != nil) != tc.wantFound {
t.Errorf("findID returned %v, wantFound: %v", got, tc.wantFound)
}
})
}
}