From 917c1f6d602e0a7672ab5555908970ed8b8b1dd7 Mon Sep 17 00:00:00 2001 From: Alberto Leal Date: Sun, 10 Apr 2016 13:09:16 +0000 Subject: [PATCH] Add unit tests for 'utils' package Signed-off-by: Alberto Leal --- libcontainer/utils/utils_test.go | 109 ++++++++++++++++++++++++++++++- 1 file changed, 108 insertions(+), 1 deletion(-) diff --git a/libcontainer/utils/utils_test.go b/libcontainer/utils/utils_test.go index 51f0efa1..6bb0d677 100644 --- a/libcontainer/utils/utils_test.go +++ b/libcontainer/utils/utils_test.go @@ -1,6 +1,13 @@ package utils -import "testing" +import ( + "bytes" + "fmt" + "os" + "path/filepath" + "syscall" + "testing" +) func TestGenerateName(t *testing.T) { name, err := GenerateRandomName("veth", 5) @@ -44,3 +51,103 @@ func TestSearchLabels(t *testing.T) { } } } + +func TestResolveRootfs(t *testing.T) { + dir := "rootfs" + os.Mkdir(dir, 0600) + defer os.Remove(dir) + + path, err := ResolveRootfs(dir) + if err != nil { + t.Fatal(err) + } + pwd, err := os.Getwd() + if err != nil { + t.Fatal(err) + } + if path != fmt.Sprintf("%s/%s", pwd, "rootfs") { + t.Errorf("expected rootfs to be abs and was %s", path) + } +} + +func TestResolveRootfsWithSymlink(t *testing.T) { + dir := "rootfs" + tmpDir, _ := filepath.EvalSymlinks(os.TempDir()) + os.Symlink(tmpDir, dir) + defer os.Remove(dir) + + path, err := ResolveRootfs(dir) + if err != nil { + t.Fatal(err) + } + + if path != tmpDir { + t.Errorf("expected rootfs to be the real path %s and was %s", path, os.TempDir()) + } +} + +func TestResolveRootfsWithNonExistingDir(t *testing.T) { + _, err := ResolveRootfs("foo") + if err == nil { + t.Error("expected error to happen but received nil") + } +} + +func TestExitStatus(t *testing.T) { + status := syscall.WaitStatus(0) + ex := ExitStatus(status) + if ex != 0 { + t.Errorf("expected exit status to equal 0 and received %d", ex) + } +} + +func TestExitStatusSignaled(t *testing.T) { + status := syscall.WaitStatus(2) + ex := ExitStatus(status) + if ex != 130 { + t.Errorf("expected exit status to equal 130 and received %d", ex) + } +} + +func TestWriteJSON(t *testing.T) { + person := struct { + Name string + Age int + }{ + Name: "Alice", + Age: 30, + } + + var b bytes.Buffer + err := WriteJSON(&b, person) + if err != nil { + t.Fatal(err) + } + + expected := `{"Name":"Alice","Age":30}` + if b.String() != expected { + t.Errorf("expected to write %s but was %s", expected, b.String()) + } +} + +func TestCleanPath(t *testing.T) { + path := CleanPath("") + if path != "" { + t.Errorf("expected to received empty string and received %s", path) + } + + path = CleanPath("rootfs") + if path != "rootfs" { + t.Errorf("expected to received 'rootfs' and received %s", path) + } + + path = CleanPath("../../../var") + if path != "var" { + t.Errorf("expected to received 'var' and received %s", path) + } + + path = CleanPath("/../../../var") + if path != "/var" { + t.Errorf("expected to received '/var' and received %s", path) + } +}