From 85bcf9d8d90b6bb3f181cb6cbaf11024833fddc3 Mon Sep 17 00:00:00 2001 From: Jakub Sobon Date: Thu, 28 Mar 2019 23:04:34 -0400 Subject: [PATCH] Function that finds container with a specific ID. --- container/traversal.go | 28 +++++++++++++++++ container/traversal_test.go | 60 +++++++++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+) diff --git a/container/traversal.go b/container/traversal.go index 74a009c..f728b50 100644 --- a/container/traversal.go +++ b/container/traversal.go @@ -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 +} diff --git a/container/traversal_test.go b/container/traversal_test.go index e4dd430..4100f9b 100644 --- a/container/traversal_test.go +++ b/container/traversal_test.go @@ -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) + } + }) + } +}