Add unit test for sync pipe

Docker-DCO-1.1-Signed-off-by: Michael Crosby <michael@docker.com> (github: crosbymichael)
This commit is contained in:
Michael Crosby 2014-06-26 11:50:22 -07:00
parent eb9a561b18
commit e7916505a3
2 changed files with 71 additions and 2 deletions

View File

@ -24,6 +24,7 @@ func NewSyncPipe() (s *SyncPipe, err error) {
if err != nil {
return nil, err
}
s.child = os.NewFile(uintptr(fds[0]), "child syncpipe")
s.parent = os.NewFile(uintptr(fds[1]), "parent syncpipe")
@ -32,6 +33,7 @@ func NewSyncPipe() (s *SyncPipe, err error) {
func NewSyncPipeFromFd(parendFd, childFd uintptr) (*SyncPipe, error) {
s := &SyncPipe{}
if parendFd > 0 {
s.parent = os.NewFile(parendFd, "parendPipe")
} else if childFd > 0 {
@ -39,6 +41,7 @@ func NewSyncPipeFromFd(parendFd, childFd uintptr) (*SyncPipe, error) {
} else {
return nil, fmt.Errorf("no valid sync pipe fd specified")
}
return s, nil
}
@ -65,9 +68,11 @@ func (s *SyncPipe) ReadFromChild() error {
if err != nil {
return err
}
if len(data) > 0 {
return fmt.Errorf("Child error: %s", string(data))
return fmt.Errorf("%s", data)
}
return nil
}
@ -83,7 +88,6 @@ func (s *SyncPipe) ReadFromParent() (*network.NetworkState, error) {
}
}
return networkState, nil
}
func (s *SyncPipe) ReportChildError(err error) {
@ -95,9 +99,11 @@ func (s *SyncPipe) Close() error {
if s.parent != nil {
s.parent.Close()
}
if s.child != nil {
s.child.Close()
}
return nil
}

View File

@ -0,0 +1,63 @@
package namespaces
import (
"fmt"
"testing"
)
func TestSendErrorFromChild(t *testing.T) {
pipe, err := NewSyncPipe()
if err != nil {
t.Fatal(err)
}
defer func() {
if err := pipe.Close(); err != nil {
t.Fatal(err)
}
}()
expected := "something bad happened"
pipe.ReportChildError(fmt.Errorf(expected))
childError := pipe.ReadFromChild()
if childError == nil {
t.Fatal("expected an error to be returned but did not receive anything")
}
if childError.Error() != expected {
t.Fatalf("expected %q but received error message %q", expected, childError.Error())
}
}
func TestSendPayloadToChild(t *testing.T) {
pipe, err := NewSyncPipe()
if err != nil {
t.Fatal(err)
}
defer func() {
if err := pipe.Close(); err != nil {
t.Fatal(err)
}
}()
expected := "libcontainer"
if err := pipe.SendToChild(map[string]string{"name": expected}); err != nil {
t.Fatal(err)
}
payload, err := pipe.ReadFromParent()
if err != nil {
t.Fatal(err)
}
if len(payload) != 1 {
t.Fatalf("expected to only have one value in the payload but received %d", len(payload))
}
if name := payload["name"]; name != expected {
t.Fatalf("expected name %q but received %q", expected, name)
}
}