virtcontainers: convert virtcontainers tests to testify/assert

Convert virtcontainers tests to testify/assert to make the virtcontainers
tests more readable.

fixes #156

Signed-off-by: Julio Montes <julio.montes@intel.com>
This commit is contained in:
Julio Montes
2019-07-17 21:14:42 +00:00
parent d987a30367
commit f2423e7d7c
36 changed files with 1041 additions and 1963 deletions

View File

@@ -10,7 +10,6 @@ import (
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
"reflect"
"testing" "testing"
"github.com/kata-containers/runtime/virtcontainers/device/config" "github.com/kata-containers/runtime/virtcontainers/device/config"
@@ -37,6 +36,7 @@ func newAcrnConfig() HypervisorConfig {
} }
func testAcrnKernelParameters(t *testing.T, kernelParams []Param, debug bool) { func testAcrnKernelParameters(t *testing.T, kernelParams []Param, debug bool) {
assert := assert.New(t)
acrnConfig := newAcrnConfig() acrnConfig := newAcrnConfig()
acrnConfig.KernelParams = kernelParams acrnConfig.KernelParams = kernelParams
@@ -52,9 +52,7 @@ func testAcrnKernelParameters(t *testing.T, kernelParams []Param, debug bool) {
expected := fmt.Sprintf("panic=1 maxcpus=%d foo=foo bar=bar", a.config.NumVCPUs) expected := fmt.Sprintf("panic=1 maxcpus=%d foo=foo bar=bar", a.config.NumVCPUs)
params := a.kernelParameters() params := a.kernelParameters()
if params != expected { assert.Equal(params, expected)
t.Fatalf("Got: %v, Expecting: %v", params, expected)
}
} }
func TestAcrnKernelParameters(t *testing.T) { func TestAcrnKernelParameters(t *testing.T) {
@@ -74,35 +72,27 @@ func TestAcrnKernelParameters(t *testing.T) {
} }
func TestAcrnCapabilities(t *testing.T) { func TestAcrnCapabilities(t *testing.T) {
assert := assert.New(t)
a := &acrn{ a := &acrn{
ctx: context.Background(), ctx: context.Background(),
arch: &acrnArchBase{}, arch: &acrnArchBase{},
} }
caps := a.capabilities() caps := a.capabilities()
if !caps.IsBlockDeviceSupported() { assert.True(caps.IsBlockDeviceSupported())
t.Fatal("Block device should be supported") assert.True(caps.IsBlockDeviceHotplugSupported())
}
if !caps.IsBlockDeviceHotplugSupported() {
t.Fatal("Block device hotplug should be supported")
}
} }
func testAcrnAddDevice(t *testing.T, devInfo interface{}, devType deviceType, expected []Device) { func testAcrnAddDevice(t *testing.T, devInfo interface{}, devType deviceType, expected []Device) {
assert := assert.New(t)
a := &acrn{ a := &acrn{
ctx: context.Background(), ctx: context.Background(),
arch: &acrnArchBase{}, arch: &acrnArchBase{},
} }
err := a.addDevice(devInfo, devType) err := a.addDevice(devInfo, devType)
if err != nil { assert.NoError(err)
t.Fatal(err) assert.Exactly(a.acrnConfig.Devices, expected)
}
if reflect.DeepEqual(a.acrnConfig.Devices, expected) == false {
t.Fatalf("Got %v\nExpecting %v", a.acrnConfig.Devices, expected)
}
} }
func TestAcrnAddDeviceSerialPortDev(t *testing.T) { func TestAcrnAddDeviceSerialPortDev(t *testing.T) {
@@ -204,6 +194,7 @@ func TestAcrnUpdateBlockDeviceInvalidIdx(t *testing.T) {
} }
func TestAcrnGetSandboxConsole(t *testing.T) { func TestAcrnGetSandboxConsole(t *testing.T) {
assert := assert.New(t)
a := &acrn{ a := &acrn{
ctx: context.Background(), ctx: context.Background(),
} }
@@ -211,16 +202,12 @@ func TestAcrnGetSandboxConsole(t *testing.T) {
expected := filepath.Join(store.RunVMStoragePath, sandboxID, consoleSocket) expected := filepath.Join(store.RunVMStoragePath, sandboxID, consoleSocket)
result, err := a.getSandboxConsole(sandboxID) result, err := a.getSandboxConsole(sandboxID)
if err != nil { assert.NoError(err)
t.Fatal(err) assert.Equal(result, expected)
}
if result != expected {
t.Fatalf("Got %s\nExpecting %s", result, expected)
}
} }
func TestAcrnCreateSandbox(t *testing.T) { func TestAcrnCreateSandbox(t *testing.T) {
assert := assert.New(t)
acrnConfig := newAcrnConfig() acrnConfig := newAcrnConfig()
a := &acrn{} a := &acrn{}
@@ -233,35 +220,27 @@ func TestAcrnCreateSandbox(t *testing.T) {
} }
vcStore, err := store.NewVCSandboxStore(sandbox.ctx, sandbox.id) vcStore, err := store.NewVCSandboxStore(sandbox.ctx, sandbox.id)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
sandbox.store = vcStore sandbox.store = vcStore
if err = globalSandboxList.addSandbox(sandbox); err != nil { err = globalSandboxList.addSandbox(sandbox)
t.Fatalf("Could not add sandbox to global list: %v", err) assert.NoError(err)
}
defer globalSandboxList.removeSandbox(sandbox.id) defer globalSandboxList.removeSandbox(sandbox.id)
// Create the hypervisor fake binary // Create the hypervisor fake binary
testAcrnPath := filepath.Join(testDir, testHypervisor) testAcrnPath := filepath.Join(testDir, testHypervisor)
_, err = os.Create(testAcrnPath) _, err = os.Create(testAcrnPath)
if err != nil { assert.NoError(err)
t.Fatalf("Could not create hypervisor file %s: %v", testAcrnPath, err)
}
if err := a.createSandbox(context.Background(), sandbox.id, NetworkNamespace{}, &sandbox.config.HypervisorConfig, sandbox.store); err != nil { err = a.createSandbox(context.Background(), sandbox.id, NetworkNamespace{}, &sandbox.config.HypervisorConfig, sandbox.store)
t.Fatal(err) assert.NoError(err)
} assert.Exactly(acrnConfig, a.config)
if reflect.DeepEqual(acrnConfig, a.config) == false {
t.Fatalf("Got %v\nExpecting %v", a.config, acrnConfig)
}
} }
func TestAcrnMemoryTopology(t *testing.T) { func TestAcrnMemoryTopology(t *testing.T) {
mem := uint32(1000) mem := uint32(1000)
assert := assert.New(t)
a := &acrn{ a := &acrn{
arch: &acrnArchBase{}, arch: &acrnArchBase{},
@@ -275,11 +254,6 @@ func TestAcrnMemoryTopology(t *testing.T) {
} }
memory, err := a.memoryTopology() memory, err := a.memoryTopology()
if err != nil { assert.NoError(err)
t.Fatal(err) assert.Exactly(memory, expectedOut)
}
if reflect.DeepEqual(memory, expectedOut) == false {
t.Fatalf("Got %v\nExpecting %v", memory, expectedOut)
}
} }

View File

@@ -6,21 +6,18 @@
package virtcontainers package virtcontainers
import ( import (
"reflect"
"testing" "testing"
"github.com/stretchr/testify/assert"
) )
func testSetAgentType(t *testing.T, value string, expected AgentType) { func testSetAgentType(t *testing.T, value string, expected AgentType) {
var agentType AgentType var agentType AgentType
assert := assert.New(t)
err := (&agentType).Set(value) err := (&agentType).Set(value)
if err != nil { assert.NoError(err)
t.Fatal(err) assert.Equal(agentType, expected)
}
if agentType != expected {
t.Fatal(err)
}
} }
func TestSetNoopAgentType(t *testing.T) { func TestSetNoopAgentType(t *testing.T) {
@@ -33,22 +30,16 @@ func TestSetKataAgentType(t *testing.T) {
func TestSetUnknownAgentType(t *testing.T) { func TestSetUnknownAgentType(t *testing.T) {
var agentType AgentType var agentType AgentType
assert := assert.New(t)
err := (&agentType).Set("unknown") err := (&agentType).Set("unknown")
if err == nil { assert.Error(err)
t.Fatal() assert.NotEqual(agentType, NoopAgentType)
}
if agentType == NoopAgentType {
t.Fatal()
}
} }
func testStringFromAgentType(t *testing.T, agentType AgentType, expected string) { func testStringFromAgentType(t *testing.T, agentType AgentType, expected string) {
agentTypeStr := (&agentType).String() agentTypeStr := (&agentType).String()
if agentTypeStr != expected { assert.Equal(t, agentTypeStr, expected)
t.Fatal()
}
} }
func TestStringFromNoopAgentType(t *testing.T) { func TestStringFromNoopAgentType(t *testing.T) {
@@ -66,10 +57,7 @@ func TestStringFromUnknownAgentType(t *testing.T) {
func testNewAgentFromAgentType(t *testing.T, agentType AgentType, expected agent) { func testNewAgentFromAgentType(t *testing.T, agentType AgentType, expected agent) {
ag := newAgent(agentType) ag := newAgent(agentType)
assert.Exactly(t, ag, expected)
if reflect.DeepEqual(ag, expected) == false {
t.Fatal()
}
} }
func TestNewAgentFromNoopAgentType(t *testing.T) { func TestNewAgentFromNoopAgentType(t *testing.T) {
@@ -87,14 +75,8 @@ func TestNewAgentFromUnknownAgentType(t *testing.T) {
func testNewAgentConfig(t *testing.T, config SandboxConfig, expected interface{}) { func testNewAgentConfig(t *testing.T, config SandboxConfig, expected interface{}) {
agentConfig, err := newAgentConfig(config.AgentType, config.AgentConfig) agentConfig, err := newAgentConfig(config.AgentType, config.AgentConfig)
if err != nil { assert.NoError(t, err)
t.Fatal(err) assert.Exactly(t, agentConfig, expected)
}
if reflect.DeepEqual(agentConfig, expected) == false {
t.Fatal()
}
} }
func TestNewAgentConfigFromNoopAgentType(t *testing.T) { func TestNewAgentConfigFromNoopAgentType(t *testing.T) {

File diff suppressed because it is too large Load Diff

View File

@@ -7,8 +7,9 @@ package virtcontainers
import ( import (
"net" "net"
"reflect"
"testing" "testing"
"github.com/stretchr/testify/assert"
) )
func TestCreateBridgedMacvlanEndpoint(t *testing.T) { func TestCreateBridgedMacvlanEndpoint(t *testing.T) {
@@ -33,9 +34,7 @@ func TestCreateBridgedMacvlanEndpoint(t *testing.T) {
} }
result, err := createBridgedMacvlanNetworkEndpoint(4, "", DefaultNetInterworkingModel) result, err := createBridgedMacvlanNetworkEndpoint(4, "", DefaultNetInterworkingModel)
if err != nil { assert.NoError(t, err)
t.Fatal(err)
}
// the resulting ID will be random - so let's overwrite to test the rest of the flow // the resulting ID will be random - so let's overwrite to test the rest of the flow
result.NetPair.ID = "uniqueTestID-4" result.NetPair.ID = "uniqueTestID-4"
@@ -43,7 +42,5 @@ func TestCreateBridgedMacvlanEndpoint(t *testing.T) {
// the resulting mac address will be random - so lets overwrite it // the resulting mac address will be random - so lets overwrite it
result.NetPair.VirtIface.HardAddr = macAddr.String() result.NetPair.VirtIface.HardAddr = macAddr.String()
if reflect.DeepEqual(result, expected) == false { assert.Exactly(t, result, expected)
t.Fatalf("\nGot: %+v, \n\nExpected: %+v", result, expected)
}
} }

View File

@@ -11,7 +11,6 @@ import (
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"reflect"
"strings" "strings"
"syscall" "syscall"
"testing" "testing"
@@ -43,9 +42,7 @@ func TestGetAnnotations(t *testing.T) {
containerAnnotations := container.GetAnnotations() containerAnnotations := container.GetAnnotations()
for k, v := range containerAnnotations { for k, v := range containerAnnotations {
if annotations[k] != v { assert.Equal(t, annotations[k], v)
t.Fatalf("Expecting ['%s']='%s', Got ['%s']='%s'\n", k, annotations[k], k, v)
}
} }
} }
@@ -84,10 +81,7 @@ func TestContainerSandbox(t *testing.T) {
} }
sandbox := container.Sandbox() sandbox := container.Sandbox()
assert.Exactly(t, sandbox, expectedSandbox)
if !reflect.DeepEqual(sandbox, expectedSandbox) {
t.Fatalf("Expecting %+v\nGot %+v", expectedSandbox, sandbox)
}
} }
func TestContainerRemoveDrive(t *testing.T) { func TestContainerRemoveDrive(t *testing.T) {
@@ -140,53 +134,37 @@ func TestContainerRemoveDrive(t *testing.T) {
} }
func testSetupFakeRootfs(t *testing.T) (testRawFile, loopDev, mntDir string, err error) { func testSetupFakeRootfs(t *testing.T) (testRawFile, loopDev, mntDir string, err error) {
assert := assert.New(t)
if tc.NotValid(ktu.NeedRoot()) { if tc.NotValid(ktu.NeedRoot()) {
t.Skip(testDisabledAsNonRoot) t.Skip(testDisabledAsNonRoot)
} }
tmpDir, err := ioutil.TempDir("", "") tmpDir, err := ioutil.TempDir("", "")
if err != nil { assert.NoError(err)
t.Fatal(err)
}
testRawFile = filepath.Join(tmpDir, "raw.img") testRawFile = filepath.Join(tmpDir, "raw.img")
if _, err := os.Stat(testRawFile); !os.IsNotExist(err) { _, err = os.Stat(testRawFile)
os.Remove(testRawFile) assert.True(os.IsNotExist(err))
}
output, err := exec.Command("losetup", "-f").CombinedOutput() output, err := exec.Command("losetup", "-f").CombinedOutput()
if err != nil { assert.NoError(err)
t.Fatalf("Skipping test since no loop device available for tests : %s, %s", output, err)
return
}
loopDev = strings.TrimSpace(string(output[:])) loopDev = strings.TrimSpace(string(output[:]))
output, err = exec.Command("fallocate", "-l", "256K", testRawFile).CombinedOutput() _, err = exec.Command("fallocate", "-l", "256K", testRawFile).CombinedOutput()
if err != nil { assert.NoError(err)
t.Fatalf("fallocate failed %s %s", output, err)
}
output, err = exec.Command("mkfs.ext4", "-F", testRawFile).CombinedOutput() _, err = exec.Command("mkfs.ext4", "-F", testRawFile).CombinedOutput()
if err != nil { assert.NoError(err)
t.Fatalf("mkfs.ext4 failed for %s: %s, %s", testRawFile, output, err)
}
output, err = exec.Command("losetup", loopDev, testRawFile).CombinedOutput() _, err = exec.Command("losetup", loopDev, testRawFile).CombinedOutput()
if err != nil { assert.NoError(err)
t.Fatalf("Losetup for %s at %s failed : %s, %s ", loopDev, testRawFile, output, err)
return
}
mntDir = filepath.Join(tmpDir, "rootfs") mntDir = filepath.Join(tmpDir, "rootfs")
err = os.Mkdir(mntDir, store.DirMode) err = os.Mkdir(mntDir, store.DirMode)
if err != nil { assert.NoError(err)
t.Fatalf("Error creating dir %s: %s", mntDir, err)
}
err = syscall.Mount(loopDev, mntDir, "ext4", uintptr(0), "") err = syscall.Mount(loopDev, mntDir, "ext4", uintptr(0), "")
if err != nil { assert.NoError(err)
t.Fatalf("Error while mounting loop device %s at %s: %s", loopDev, mntDir, err)
}
return return
} }
@@ -208,6 +186,7 @@ func cleanupFakeRootfsSetup(testRawFile, loopDev, mntDir string) {
} }
func TestContainerAddDriveDir(t *testing.T) { func TestContainerAddDriveDir(t *testing.T) {
assert := assert.New(t)
if tc.NotValid(ktu.NeedRoot()) { if tc.NotValid(ktu.NeedRoot()) {
t.Skip(testDisabledAsNonRoot) t.Skip(testDisabledAsNonRoot)
} }
@@ -216,9 +195,7 @@ func TestContainerAddDriveDir(t *testing.T) {
defer cleanupFakeRootfsSetup(testRawFile, loopDev, fakeRootfs) defer cleanupFakeRootfsSetup(testRawFile, loopDev, fakeRootfs)
if err != nil { assert.NoError(err)
t.Fatalf("Error while setting up fake rootfs: %v, Skipping test", err)
}
sandbox := &Sandbox{ sandbox := &Sandbox{
ctx: context.Background(), ctx: context.Background(),
@@ -236,12 +213,12 @@ func TestContainerAddDriveDir(t *testing.T) {
defer store.DeleteAll() defer store.DeleteAll()
sandboxStore, err := store.NewVCSandboxStore(sandbox.ctx, sandbox.id) sandboxStore, err := store.NewVCSandboxStore(sandbox.ctx, sandbox.id)
assert.Nil(t, err) assert.Nil(err)
sandbox.store = sandboxStore sandbox.store = sandboxStore
if sandbox.newStore, err = persist.GetDriver("fs"); err != nil || sandbox.newStore == nil { sandbox.newStore, err = persist.GetDriver("fs")
t.Fatalf("failed to get fs persist driver") assert.NoError(err)
} assert.NotNil(sandbox.newStore)
contID := "100" contID := "100"
container := Container{ container := Container{
@@ -251,7 +228,7 @@ func TestContainerAddDriveDir(t *testing.T) {
} }
containerStore, err := store.NewVCContainerStore(sandbox.ctx, sandbox.id, container.id) containerStore, err := store.NewVCContainerStore(sandbox.ctx, sandbox.id, container.id)
assert.Nil(t, err) assert.Nil(err)
container.store = containerStore container.store = containerStore
// create state file // create state file
@@ -260,9 +237,7 @@ func TestContainerAddDriveDir(t *testing.T) {
os.Remove(stateFilePath) os.Remove(stateFilePath)
_, err = os.Create(stateFilePath) _, err = os.Create(stateFilePath)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
// Make the checkStorageDriver func variable point to a fake check function // Make the checkStorageDriver func variable point to a fake check function
savedFunc := checkStorageDriver savedFunc := checkStorageDriver
@@ -277,13 +252,9 @@ func TestContainerAddDriveDir(t *testing.T) {
container.state.Fstype = "" container.state.Fstype = ""
err = container.hotplugDrive() err = container.hotplugDrive()
if err != nil { assert.NoError(err)
t.Fatalf("Error with hotplugDrive :%v", err)
}
if container.state.Fstype == "" { assert.NotEmpty(container.state.Fstype)
t.Fatal()
}
} }
func TestContainerRootfsPath(t *testing.T) { func TestContainerRootfsPath(t *testing.T) {

View File

@@ -5,19 +5,18 @@
package virtcontainers package virtcontainers
import "testing" import (
"testing"
"github.com/stretchr/testify/assert"
)
func testEndpointTypeSet(t *testing.T, value string, expected EndpointType) { func testEndpointTypeSet(t *testing.T, value string, expected EndpointType) {
var endpointType EndpointType var endpointType EndpointType
err := endpointType.Set(value) err := endpointType.Set(value)
if err != nil { assert.NoError(t, err)
t.Fatal(err) assert.Equal(t, endpointType, expected)
}
if endpointType != expected {
t.Fatal()
}
} }
func TestPhysicalEndpointTypeSet(t *testing.T) { func TestPhysicalEndpointTypeSet(t *testing.T) {
@@ -43,18 +42,12 @@ func TestMacvtapEndpointTypeSet(t *testing.T) {
func TestEndpointTypeSetFailure(t *testing.T) { func TestEndpointTypeSetFailure(t *testing.T) {
var endpointType EndpointType var endpointType EndpointType
err := endpointType.Set("wrong-value") assert.Error(t, endpointType.Set("wrong-value"))
if err == nil {
t.Fatal(err)
}
} }
func testEndpointTypeString(t *testing.T, endpointType *EndpointType, expected string) { func testEndpointTypeString(t *testing.T, endpointType *EndpointType, expected string) {
result := endpointType.String() result := endpointType.String()
assert.Equal(t, result, expected)
if result != expected {
t.Fatal()
}
} }
func TestPhysicalEndpointTypeString(t *testing.T) { func TestPhysicalEndpointTypeString(t *testing.T) {

View File

@@ -9,6 +9,8 @@ import (
"io/ioutil" "io/ioutil"
"os" "os"
"testing" "testing"
"github.com/stretchr/testify/assert"
) )
var dataFlagsFieldWithoutHypervisor = []byte(` var dataFlagsFieldWithoutHypervisor = []byte(`
@@ -69,16 +71,12 @@ func TestRunningOnVMM(t *testing.T) {
func TestRunningOnVMMNotExistingCPUInfoPathFailure(t *testing.T) { func TestRunningOnVMMNotExistingCPUInfoPathFailure(t *testing.T) {
f, err := ioutil.TempFile("", "cpuinfo") f, err := ioutil.TempFile("", "cpuinfo")
if err != nil { assert.NoError(t, err)
t.Fatal(err)
}
filePath := f.Name() filePath := f.Name()
f.Close() f.Close()
os.Remove(filePath) os.Remove(filePath)
_, err = RunningOnVMM(filePath)
if _, err := RunningOnVMM(filePath); err == nil { assert.Error(t, err)
t.Fatalf("Should fail because %q file path does not exist", filePath)
}
} }

View File

@@ -18,9 +18,7 @@ func TestRunningOnVMM(t *testing.T) {
expectedOutput := false expectedOutput := false
f, err := ioutil.TempFile("", "cpuinfo") f, err := ioutil.TempFile("", "cpuinfo")
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer os.Remove(f.Name()) defer os.Remove(f.Name())
defer f.Close() defer f.Close()

View File

@@ -10,21 +10,18 @@ import (
"io/ioutil" "io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"reflect"
"testing" "testing"
"github.com/stretchr/testify/assert"
) )
func testSetHypervisorType(t *testing.T, value string, expected HypervisorType) { func testSetHypervisorType(t *testing.T, value string, expected HypervisorType) {
var hypervisorType HypervisorType var hypervisorType HypervisorType
assert := assert.New(t)
err := (&hypervisorType).Set(value) err := (&hypervisorType).Set(value)
if err != nil { assert.NoError(err)
t.Fatal(err) assert.Equal(hypervisorType, expected)
}
if hypervisorType != expected {
t.Fatal()
}
} }
func TestSetQemuHypervisorType(t *testing.T) { func TestSetQemuHypervisorType(t *testing.T) {
@@ -37,23 +34,18 @@ func TestSetMockHypervisorType(t *testing.T) {
func TestSetUnknownHypervisorType(t *testing.T) { func TestSetUnknownHypervisorType(t *testing.T) {
var hypervisorType HypervisorType var hypervisorType HypervisorType
assert := assert.New(t)
err := (&hypervisorType).Set("unknown") err := (&hypervisorType).Set("unknown")
if err == nil { assert.Error(err)
t.Fatal() assert.NotEqual(hypervisorType, QemuHypervisor)
} assert.NotEqual(hypervisorType, MockHypervisor)
if hypervisorType == QemuHypervisor ||
hypervisorType == MockHypervisor {
t.Fatal()
}
} }
func testStringFromHypervisorType(t *testing.T, hypervisorType HypervisorType, expected string) { func testStringFromHypervisorType(t *testing.T, hypervisorType HypervisorType, expected string) {
hypervisorTypeStr := (&hypervisorType).String() hypervisorTypeStr := (&hypervisorType).String()
if hypervisorTypeStr != expected { assert := assert.New(t)
t.Fatal() assert.Equal(hypervisorTypeStr, expected)
}
} }
func TestStringFromQemuHypervisorType(t *testing.T) { func TestStringFromQemuHypervisorType(t *testing.T) {
@@ -72,14 +64,10 @@ func TestStringFromUnknownHypervisorType(t *testing.T) {
} }
func testNewHypervisorFromHypervisorType(t *testing.T, hypervisorType HypervisorType, expected hypervisor) { func testNewHypervisorFromHypervisorType(t *testing.T, hypervisorType HypervisorType, expected hypervisor) {
assert := assert.New(t)
hy, err := newHypervisor(hypervisorType) hy, err := newHypervisor(hypervisorType)
if err != nil { assert.NoError(err)
t.Fatal(err) assert.Exactly(hy, expected)
}
if reflect.DeepEqual(hy, expected) == false {
t.Fatal()
}
} }
func TestNewHypervisorFromQemuHypervisorType(t *testing.T) { func TestNewHypervisorFromQemuHypervisorType(t *testing.T) {
@@ -96,25 +84,18 @@ func TestNewHypervisorFromMockHypervisorType(t *testing.T) {
func TestNewHypervisorFromUnknownHypervisorType(t *testing.T) { func TestNewHypervisorFromUnknownHypervisorType(t *testing.T) {
var hypervisorType HypervisorType var hypervisorType HypervisorType
assert := assert.New(t)
hy, err := newHypervisor(hypervisorType) hy, err := newHypervisor(hypervisorType)
if err == nil { assert.Error(err)
t.Fatal() assert.Nil(hy)
}
if hy != nil {
t.Fatal()
}
} }
func testHypervisorConfigValid(t *testing.T, hypervisorConfig *HypervisorConfig, success bool) { func testHypervisorConfigValid(t *testing.T, hypervisorConfig *HypervisorConfig, success bool) {
err := hypervisorConfig.valid() err := hypervisorConfig.valid()
if success && err != nil { assert := assert.New(t)
t.Fatal() assert.False(success && err != nil)
} assert.False(!success && err == nil)
if !success && err == nil {
t.Fatal()
}
} }
func TestHypervisorConfigNoKernelPath(t *testing.T) { func TestHypervisorConfigNoKernelPath(t *testing.T) {
@@ -182,6 +163,7 @@ func TestHypervisorConfigValidTemplateConfig(t *testing.T) {
} }
func TestHypervisorConfigDefaults(t *testing.T) { func TestHypervisorConfigDefaults(t *testing.T) {
assert := assert.New(t)
hypervisorConfig := &HypervisorConfig{ hypervisorConfig := &HypervisorConfig{
KernelPath: fmt.Sprintf("%s/%s", testDir, testKernel), KernelPath: fmt.Sprintf("%s/%s", testDir, testKernel),
ImagePath: fmt.Sprintf("%s/%s", testDir, testImage), ImagePath: fmt.Sprintf("%s/%s", testDir, testImage),
@@ -201,12 +183,11 @@ func TestHypervisorConfigDefaults(t *testing.T) {
Msize9p: defaultMsize9p, Msize9p: defaultMsize9p,
} }
if reflect.DeepEqual(hypervisorConfig, hypervisorConfigDefaultsExpected) == false { assert.Exactly(hypervisorConfig, hypervisorConfigDefaultsExpected)
t.Fatal()
}
} }
func TestAppendParams(t *testing.T) { func TestAppendParams(t *testing.T) {
assert := assert.New(t)
paramList := []Param{ paramList := []Param{
{ {
Key: "param1", Key: "param1",
@@ -226,16 +207,13 @@ func TestAppendParams(t *testing.T) {
} }
paramList = appendParam(paramList, "param2", "value2") paramList = appendParam(paramList, "param2", "value2")
if reflect.DeepEqual(paramList, expectedParams) == false { assert.Exactly(paramList, expectedParams)
t.Fatal()
}
} }
func testSerializeParams(t *testing.T, params []Param, delim string, expected []string) { func testSerializeParams(t *testing.T, params []Param, delim string, expected []string) {
assert := assert.New(t)
result := SerializeParams(params, delim) result := SerializeParams(params, delim)
if reflect.DeepEqual(result, expected) == false { assert.Exactly(result, expected)
t.Fatal()
}
} }
func TestSerializeParamsNoParamNoValue(t *testing.T) { func TestSerializeParamsNoParamNoValue(t *testing.T) {
@@ -301,10 +279,9 @@ func TestSerializeParams(t *testing.T) {
} }
func testDeserializeParams(t *testing.T, parameters []string, expected []Param) { func testDeserializeParams(t *testing.T, parameters []string, expected []Param) {
assert := assert.New(t)
result := DeserializeParams(parameters) result := DeserializeParams(parameters)
if reflect.DeepEqual(result, expected) == false { assert.Exactly(result, expected)
t.Fatal()
}
} }
func TestDeserializeParamsNil(t *testing.T) { func TestDeserializeParamsNil(t *testing.T) {
@@ -354,32 +331,31 @@ func TestDeserializeParams(t *testing.T) {
func TestAddKernelParamValid(t *testing.T) { func TestAddKernelParamValid(t *testing.T) {
var config HypervisorConfig var config HypervisorConfig
assert := assert.New(t)
expected := []Param{ expected := []Param{
{"foo", "bar"}, {"foo", "bar"},
} }
err := config.AddKernelParam(expected[0]) err := config.AddKernelParam(expected[0])
if err != nil || reflect.DeepEqual(config.KernelParams, expected) == false { assert.NoError(err)
t.Fatal() assert.Exactly(config.KernelParams, expected)
}
} }
func TestAddKernelParamInvalid(t *testing.T) { func TestAddKernelParamInvalid(t *testing.T) {
var config HypervisorConfig var config HypervisorConfig
assert := assert.New(t)
invalid := []Param{ invalid := []Param{
{"", "bar"}, {"", "bar"},
} }
err := config.AddKernelParam(invalid[0]) err := config.AddKernelParam(invalid[0])
if err == nil { assert.Error(err)
t.Fatal()
}
} }
func TestGetHostMemorySizeKb(t *testing.T) { func TestGetHostMemorySizeKb(t *testing.T) {
assert := assert.New(t)
type testData struct { type testData struct {
contents string contents string
expectedResult int expectedResult int
@@ -409,31 +385,23 @@ func TestGetHostMemorySizeKb(t *testing.T) {
} }
dir, err := ioutil.TempDir("", "") dir, err := ioutil.TempDir("", "")
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer os.RemoveAll(dir) defer os.RemoveAll(dir)
file := filepath.Join(dir, "meminfo") file := filepath.Join(dir, "meminfo")
if _, err := getHostMemorySizeKb(file); err == nil { _, err = getHostMemorySizeKb(file)
t.Fatalf("expected failure as file %q does not exist", file) assert.Error(err)
}
for _, d := range data { for _, d := range data {
if err := ioutil.WriteFile(file, []byte(d.contents), os.FileMode(0640)); err != nil { err = ioutil.WriteFile(file, []byte(d.contents), os.FileMode(0640))
t.Fatal(err) assert.NoError(err)
}
defer os.Remove(file) defer os.Remove(file)
hostMemKb, err := getHostMemorySizeKb(file) hostMemKb, err := getHostMemorySizeKb(file)
if (d.expectError && err == nil) || (!d.expectError && err != nil) { assert.False((d.expectError && err == nil))
t.Fatalf("got %d, input %v", hostMemKb, d) assert.False((!d.expectError && err != nil))
} assert.NotEqual(hostMemKb, d.expectedResult)
if reflect.DeepEqual(hostMemKb, d.expectedResult) {
t.Fatalf("got %d, input %v", hostMemKb, d)
}
} }
} }
@@ -446,21 +414,16 @@ type testNestedVMMData struct {
// nolint: unused, deadcode // nolint: unused, deadcode
func genericTestRunningOnVMM(t *testing.T, data []testNestedVMMData) { func genericTestRunningOnVMM(t *testing.T, data []testNestedVMMData) {
assert := assert.New(t)
for _, d := range data { for _, d := range data {
f, err := ioutil.TempFile("", "cpuinfo") f, err := ioutil.TempFile("", "cpuinfo")
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer os.Remove(f.Name()) defer os.Remove(f.Name())
defer f.Close() defer f.Close()
n, err := f.Write(d.content) n, err := f.Write(d.content)
if err != nil { assert.NoError(err)
t.Fatal(err) assert.Equal(n, len(d.content))
}
if n != len(d.content) {
t.Fatalf("Only %d bytes written out of %d expected", n, len(d.content))
}
running, err := RunningOnVMM(f.Name()) running, err := RunningOnVMM(f.Name())
if !d.expectedErr && err != nil { if !d.expectedErr && err != nil {
@@ -469,8 +432,6 @@ func genericTestRunningOnVMM(t *testing.T, data []testNestedVMMData) {
t.Fatalf("This test should fail") t.Fatalf("This test should fail")
} }
if running != d.expected { assert.Equal(running, d.expected)
t.Fatalf("Expecting running on VMM = %t, Got %t", d.expected, running)
}
} }
} }

View File

@@ -14,9 +14,7 @@ import (
func TestIOStream(t *testing.T) { func TestIOStream(t *testing.T) {
hConfig := newHypervisorConfig(nil, nil) hConfig := newHypervisorConfig(nil, nil)
s, err := testCreateSandbox(t, testSandboxID, MockHypervisor, hConfig, NoopAgentType, NetworkConfig{}, []ContainerConfig{}, nil) s, err := testCreateSandbox(t, testSandboxID, MockHypervisor, hConfig, NoopAgentType, NetworkConfig{}, []ContainerConfig{}, nil)
if err != nil { assert.NoError(t, err)
t.Fatal(err)
}
defer cleanUp() defer cleanUp()
contID := "foo" contID := "foo"

View File

@@ -7,11 +7,13 @@ package virtcontainers
import ( import (
"net" "net"
"reflect"
"testing" "testing"
"github.com/stretchr/testify/assert"
) )
func TestCreateIPVlanEndpoint(t *testing.T) { func TestCreateIPVlanEndpoint(t *testing.T) {
assert := assert.New(t)
macAddr := net.HardwareAddr{0x02, 0x00, 0xCA, 0xFE, 0x00, 0x04} macAddr := net.HardwareAddr{0x02, 0x00, 0xCA, 0xFE, 0x00, 0x04}
expected := &IPVlanEndpoint{ expected := &IPVlanEndpoint{
@@ -34,9 +36,7 @@ func TestCreateIPVlanEndpoint(t *testing.T) {
} }
result, err := createIPVlanNetworkEndpoint(5, "") result, err := createIPVlanNetworkEndpoint(5, "")
if err != nil { assert.NoError(err)
t.Fatal(err)
}
// the resulting ID will be random - so let's overwrite to test the rest of the flow // the resulting ID will be random - so let's overwrite to test the rest of the flow
result.NetPair.ID = "uniqueTestID-5" result.NetPair.ID = "uniqueTestID-5"
@@ -44,7 +44,5 @@ func TestCreateIPVlanEndpoint(t *testing.T) {
// the resulting mac address will be random - so lets overwrite it // the resulting mac address will be random - so lets overwrite it
result.NetPair.VirtIface.HardAddr = macAddr.String() result.NetPair.VirtIface.HardAddr = macAddr.String()
if reflect.DeepEqual(result, expected) == false { assert.Exactly(result, expected)
t.Fatalf("\nGot: %+v, \n\nExpected: %+v", result, expected)
}
} }

View File

@@ -58,20 +58,18 @@ func testGenerateKataProxySockDir() (string, error) {
} }
func TestKataAgentConnect(t *testing.T) { func TestKataAgentConnect(t *testing.T) {
assert := assert.New(t)
proxy := mock.ProxyUnixMock{ proxy := mock.ProxyUnixMock{
ClientHandler: proxyHandlerDiscard, ClientHandler: proxyHandlerDiscard,
} }
sockDir, err := testGenerateKataProxySockDir() sockDir, err := testGenerateKataProxySockDir()
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer os.RemoveAll(sockDir) defer os.RemoveAll(sockDir)
testKataProxyURL := fmt.Sprintf(testKataProxyURLTempl, sockDir) testKataProxyURL := fmt.Sprintf(testKataProxyURLTempl, sockDir)
if err := proxy.Start(testKataProxyURL); err != nil { err = proxy.Start(testKataProxyURL)
t.Fatal(err) assert.NoError(err)
}
defer proxy.Stop() defer proxy.Stop()
k := &kataAgent{ k := &kataAgent{
@@ -81,30 +79,24 @@ func TestKataAgentConnect(t *testing.T) {
}, },
} }
if err := k.connect(); err != nil { err = k.connect()
t.Fatal(err) assert.NoError(err)
} assert.NotNil(k.client)
if k.client == nil {
t.Fatal("Kata agent client is not properly initialized")
}
} }
func TestKataAgentDisconnect(t *testing.T) { func TestKataAgentDisconnect(t *testing.T) {
assert := assert.New(t)
proxy := mock.ProxyUnixMock{ proxy := mock.ProxyUnixMock{
ClientHandler: proxyHandlerDiscard, ClientHandler: proxyHandlerDiscard,
} }
sockDir, err := testGenerateKataProxySockDir() sockDir, err := testGenerateKataProxySockDir()
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer os.RemoveAll(sockDir) defer os.RemoveAll(sockDir)
testKataProxyURL := fmt.Sprintf(testKataProxyURLTempl, sockDir) testKataProxyURL := fmt.Sprintf(testKataProxyURLTempl, sockDir)
if err := proxy.Start(testKataProxyURL); err != nil { err = proxy.Start(testKataProxyURL)
t.Fatal(err) assert.NoError(err)
}
defer proxy.Stop() defer proxy.Stop()
k := &kataAgent{ k := &kataAgent{
@@ -114,17 +106,9 @@ func TestKataAgentDisconnect(t *testing.T) {
}, },
} }
if err := k.connect(); err != nil { assert.NoError(k.connect())
t.Fatal(err) assert.NoError(k.disconnect())
} assert.Nil(k.client)
if err := k.disconnect(); err != nil {
t.Fatal(err)
}
if k.client != nil {
t.Fatal("Kata agent client pointer should be nil")
}
} }
type gRPCProxy struct{} type gRPCProxy struct{}
@@ -816,15 +800,11 @@ func TestAgentNetworkOperation(t *testing.T) {
} }
sockDir, err := testGenerateKataProxySockDir() sockDir, err := testGenerateKataProxySockDir()
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer os.RemoveAll(sockDir) defer os.RemoveAll(sockDir)
testKataProxyURL := fmt.Sprintf(testKataProxyURLTempl, sockDir) testKataProxyURL := fmt.Sprintf(testKataProxyURLTempl, sockDir)
if err := proxy.Start(testKataProxyURL); err != nil { assert.NoError(proxy.Start(testKataProxyURL))
t.Fatal(err)
}
defer proxy.Stop() defer proxy.Stop()
k := &kataAgent{ k := &kataAgent{
@@ -956,9 +936,8 @@ func TestKataCleanupSandbox(t *testing.T) {
k := &kataAgent{} k := &kataAgent{}
k.cleanup(s.id) k.cleanup(s.id)
if _, err = os.Stat(dir); os.IsExist(err) { _, err = os.Stat(dir)
t.Fatalf("%s still exists\n", dir) assert.False(os.IsExist(err))
}
} }
func TestKataAgentKernelParams(t *testing.T) { func TestKataAgentKernelParams(t *testing.T) {

View File

@@ -19,6 +19,7 @@ import (
. "github.com/kata-containers/runtime/virtcontainers/pkg/mock" . "github.com/kata-containers/runtime/virtcontainers/pkg/mock"
"github.com/kata-containers/runtime/virtcontainers/utils" "github.com/kata-containers/runtime/virtcontainers/utils"
"github.com/stretchr/testify/assert"
) )
const ( const (
@@ -41,23 +42,15 @@ func getMockKataShimBinPath() string {
func testKataShimStart(t *testing.T, sandbox *Sandbox, params ShimParams, expectFail bool) { func testKataShimStart(t *testing.T, sandbox *Sandbox, params ShimParams, expectFail bool) {
s := &kataShim{} s := &kataShim{}
assert := assert.New(t)
pid, err := s.start(sandbox, params) pid, err := s.start(sandbox, params)
if expectFail { if expectFail {
if err == nil || pid != -1 { assert.Error(err)
t.Fatalf("This test should fail (sandbox %+v, params %+v, expectFail %t)", assert.Equal(pid, -1)
sandbox, params, expectFail)
}
} else { } else {
if err != nil { assert.NoError(err)
t.Fatalf("This test should pass (sandbox %+v, params %+v, expectFail %t): %s", assert.NotEqual(pid, -1)
sandbox, params, expectFail, err)
}
if pid == -1 {
t.Fatalf("This test should pass (sandbox %+v, params %+v, expectFail %t)",
sandbox, params, expectFail)
}
} }
} }
@@ -145,9 +138,7 @@ func TestKataShimStartParamsContainerEmptyFailure(t *testing.T) {
func TestKataShimStartParamsInvalidCommand(t *testing.T) { func TestKataShimStartParamsInvalidCommand(t *testing.T) {
dir, err := ioutil.TempDir("", "") dir, err := ioutil.TempDir("", "")
if err != nil { assert.NoError(t, err)
t.Fatal(err)
}
defer os.RemoveAll(dir) defer os.RemoveAll(dir)
cmd := filepath.Join(dir, "does-not-exist") cmd := filepath.Join(dir, "does-not-exist")
@@ -199,9 +190,8 @@ func startKataShimStartWithoutConsoleSuccessful(t *testing.T, detach bool) (*os.
func TestKataShimStartSuccessful(t *testing.T) { func TestKataShimStartSuccessful(t *testing.T) {
rStdout, wStdout, saveStdout, sandbox, params, err := startKataShimStartWithoutConsoleSuccessful(t, false) rStdout, wStdout, saveStdout, sandbox, params, err := startKataShimStartWithoutConsoleSuccessful(t, false)
if err != nil { assert := assert.New(t)
t.Fatal(err) assert.NoError(err)
}
defer func() { defer func() {
os.Stdout = saveStdout os.Stdout = saveStdout
@@ -212,20 +202,14 @@ func TestKataShimStartSuccessful(t *testing.T) {
testKataShimStart(t, sandbox, params, false) testKataShimStart(t, sandbox, params, false)
bufStdout := make([]byte, 1024) bufStdout := make([]byte, 1024)
if _, err := rStdout.Read(bufStdout); err != nil { _, err = rStdout.Read(bufStdout)
t.Fatal(err) assert.NoError(err)
} assert.True(strings.Contains(string(bufStdout), ShimStdoutOutput))
if !strings.Contains(string(bufStdout), ShimStdoutOutput) {
t.Fatalf("Substring %q not found in %q", ShimStdoutOutput, string(bufStdout))
}
} }
func TestKataShimStartDetachSuccessful(t *testing.T) { func TestKataShimStartDetachSuccessful(t *testing.T) {
rStdout, wStdout, saveStdout, sandbox, params, err := startKataShimStartWithoutConsoleSuccessful(t, true) rStdout, wStdout, saveStdout, sandbox, params, err := startKataShimStartWithoutConsoleSuccessful(t, true)
if err != nil { assert.NoError(t, err)
t.Fatal(err)
}
defer func() { defer func() {
os.Stdout = saveStdout os.Stdout = saveStdout
@@ -255,9 +239,7 @@ func TestKataShimStartDetachSuccessful(t *testing.T) {
select { select {
case err := <-readCh: case err := <-readCh:
if err != nil { assert.NoError(t, err)
t.Fatal(err)
}
case <-time.After(time.Duration(20) * time.Millisecond): case <-time.After(time.Duration(20) * time.Millisecond):
return return
} }
@@ -327,10 +309,7 @@ func TestKataShimStartWithConsoleSuccessful(t *testing.T) {
master, console, err := newConsole() master, console, err := newConsole()
t.Logf("Console created for tests:%s\n", console) t.Logf("Console created for tests:%s\n", console)
assert.NoError(t, err)
if err != nil {
t.Fatal(err)
}
sandbox := &Sandbox{ sandbox := &Sandbox{
config: &SandboxConfig{ config: &SandboxConfig{

View File

@@ -6,8 +6,9 @@
package virtcontainers package virtcontainers
import ( import (
"reflect"
"testing" "testing"
"github.com/stretchr/testify/assert"
) )
func TestCreateMacvtapEndpoint(t *testing.T) { func TestCreateMacvtapEndpoint(t *testing.T) {
@@ -22,11 +23,6 @@ func TestCreateMacvtapEndpoint(t *testing.T) {
} }
result, err := createMacvtapNetworkEndpoint(netInfo) result, err := createMacvtapNetworkEndpoint(netInfo)
if err != nil { assert.NoError(t, err)
t.Fatal(err) assert.Exactly(t, result, expected)
}
if reflect.DeepEqual(result, expected) == false {
t.Fatalf("\nGot: %+v, \n\nExpected: %+v", result, expected)
}
} }

View File

@@ -9,10 +9,13 @@ import (
"context" "context"
"fmt" "fmt"
"testing" "testing"
"github.com/stretchr/testify/assert"
) )
func TestMockHypervisorCreateSandbox(t *testing.T) { func TestMockHypervisorCreateSandbox(t *testing.T) {
var m *mockHypervisor var m *mockHypervisor
assert := assert.New(t)
sandbox := &Sandbox{ sandbox := &Sandbox{
config: &SandboxConfig{ config: &SandboxConfig{
@@ -28,9 +31,8 @@ func TestMockHypervisorCreateSandbox(t *testing.T) {
ctx := context.Background() ctx := context.Background()
// wrong config // wrong config
if err := m.createSandbox(ctx, sandbox.config.ID, NetworkNamespace{}, &sandbox.config.HypervisorConfig, nil); err == nil { err := m.createSandbox(ctx, sandbox.config.ID, NetworkNamespace{}, &sandbox.config.HypervisorConfig, nil)
t.Fatal() assert.Error(err)
}
sandbox.config.HypervisorConfig = HypervisorConfig{ sandbox.config.HypervisorConfig = HypervisorConfig{
KernelPath: fmt.Sprintf("%s/%s", testDir, testKernel), KernelPath: fmt.Sprintf("%s/%s", testDir, testKernel),
@@ -38,56 +40,41 @@ func TestMockHypervisorCreateSandbox(t *testing.T) {
HypervisorPath: fmt.Sprintf("%s/%s", testDir, testHypervisor), HypervisorPath: fmt.Sprintf("%s/%s", testDir, testHypervisor),
} }
if err := m.createSandbox(ctx, sandbox.config.ID, NetworkNamespace{}, &sandbox.config.HypervisorConfig, nil); err != nil { err = m.createSandbox(ctx, sandbox.config.ID, NetworkNamespace{}, &sandbox.config.HypervisorConfig, nil)
t.Fatal(err) assert.NoError(err)
}
} }
func TestMockHypervisorStartSandbox(t *testing.T) { func TestMockHypervisorStartSandbox(t *testing.T) {
var m *mockHypervisor var m *mockHypervisor
if err := m.startSandbox(vmStartTimeout); err != nil { assert.NoError(t, m.startSandbox(vmStartTimeout))
t.Fatal(err)
}
} }
func TestMockHypervisorStopSandbox(t *testing.T) { func TestMockHypervisorStopSandbox(t *testing.T) {
var m *mockHypervisor var m *mockHypervisor
if err := m.stopSandbox(); err != nil { assert.NoError(t, m.stopSandbox())
t.Fatal(err)
}
} }
func TestMockHypervisorAddDevice(t *testing.T) { func TestMockHypervisorAddDevice(t *testing.T) {
var m *mockHypervisor var m *mockHypervisor
if err := m.addDevice(nil, imgDev); err != nil { assert.NoError(t, m.addDevice(nil, imgDev))
t.Fatal(err)
}
} }
func TestMockHypervisorGetSandboxConsole(t *testing.T) { func TestMockHypervisorGetSandboxConsole(t *testing.T) {
var m *mockHypervisor var m *mockHypervisor
expected := "" expected := ""
result, err := m.getSandboxConsole("testSandboxID") result, err := m.getSandboxConsole("testSandboxID")
if err != nil { assert.NoError(t, err)
t.Fatal(err) assert.Equal(t, result, expected)
}
if result != expected {
t.Fatalf("Got %s\nExpecting %s", result, expected)
}
} }
func TestMockHypervisorSaveSandbox(t *testing.T) { func TestMockHypervisorSaveSandbox(t *testing.T) {
var m *mockHypervisor var m *mockHypervisor
if err := m.saveSandbox(); err != nil { assert.NoError(t, m.saveSandbox())
t.Fatal(err)
}
} }
func TestMockHypervisorDisconnect(t *testing.T) { func TestMockHypervisorDisconnect(t *testing.T) {

View File

@@ -16,23 +16,22 @@ func TestMonitorSuccess(t *testing.T) {
contID := "505" contID := "505"
contConfig := newTestContainerConfigNoop(contID) contConfig := newTestContainerConfigNoop(contID)
hConfig := newHypervisorConfig(nil, nil) hConfig := newHypervisorConfig(nil, nil)
assert := assert.New(t)
// create a sandbox // create a sandbox
s, err := testCreateSandbox(t, testSandboxID, MockHypervisor, hConfig, NoopAgentType, NetworkConfig{}, []ContainerConfig{contConfig}, nil) s, err := testCreateSandbox(t, testSandboxID, MockHypervisor, hConfig, NoopAgentType, NetworkConfig{}, []ContainerConfig{contConfig}, nil)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer cleanUp() defer cleanUp()
m := newMonitor(s) m := newMonitor(s)
ch, err := m.newWatcher() ch, err := m.newWatcher()
assert.Nil(t, err, "newWatcher failed: %v", err) assert.Nil(err, "newWatcher failed: %v", err)
fakeErr := errors.New("foobar error") fakeErr := errors.New("foobar error")
m.notify(fakeErr) m.notify(fakeErr)
resultErr := <-ch resultErr := <-ch
assert.True(t, resultErr == fakeErr, "monitor notification mismatch %v vs. %v", resultErr, fakeErr) assert.True(resultErr == fakeErr, "monitor notification mismatch %v vs. %v", resultErr, fakeErr)
m.stop() m.stop()
} }
@@ -41,18 +40,17 @@ func TestMonitorClosedChannel(t *testing.T) {
contID := "505" contID := "505"
contConfig := newTestContainerConfigNoop(contID) contConfig := newTestContainerConfigNoop(contID)
hConfig := newHypervisorConfig(nil, nil) hConfig := newHypervisorConfig(nil, nil)
assert := assert.New(t)
// create a sandbox // create a sandbox
s, err := testCreateSandbox(t, testSandboxID, MockHypervisor, hConfig, NoopAgentType, NetworkConfig{}, []ContainerConfig{contConfig}, nil) s, err := testCreateSandbox(t, testSandboxID, MockHypervisor, hConfig, NoopAgentType, NetworkConfig{}, []ContainerConfig{contConfig}, nil)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer cleanUp() defer cleanUp()
m := newMonitor(s) m := newMonitor(s)
ch, err := m.newWatcher() ch, err := m.newWatcher()
assert.Nil(t, err, "newWatcher failed: %v", err) assert.Nil(err, "newWatcher failed: %v", err)
close(ch) close(ch)
fakeErr := errors.New("foobar error") fakeErr := errors.New("foobar error")

View File

@@ -33,6 +33,7 @@ func init() {
} }
func TestIsSystemMount(t *testing.T) { func TestIsSystemMount(t *testing.T) {
assert := assert.New(t)
tests := []struct { tests := []struct {
mnt string mnt string
expected bool expected bool
@@ -51,13 +52,12 @@ func TestIsSystemMount(t *testing.T) {
for _, test := range tests { for _, test := range tests {
result := isSystemMount(test.mnt) result := isSystemMount(test.mnt)
if result != test.expected { assert.Exactly(result, test.expected)
t.Fatalf("Expected result for path %s : %v, got %v", test.mnt, test.expected, result)
}
} }
} }
func TestIsHostDevice(t *testing.T) { func TestIsHostDevice(t *testing.T) {
assert := assert.New(t)
tests := []struct { tests := []struct {
mnt string mnt string
expected bool expected bool
@@ -70,13 +70,12 @@ func TestIsHostDevice(t *testing.T) {
for _, test := range tests { for _, test := range tests {
result := isHostDevice(test.mnt) result := isHostDevice(test.mnt)
if result != test.expected { assert.Equal(result, test.expected)
t.Fatalf("Expected result for path %s : %v, got %v", test.mnt, test.expected, result)
}
} }
} }
func TestIsHostDeviceCreateFile(t *testing.T) { func TestIsHostDeviceCreateFile(t *testing.T) {
assert := assert.New(t)
if tc.NotValid(ktu.NeedRoot()) { if tc.NotValid(ktu.NeedRoot()) {
t.Skip(ktu.TestDisabledNeedRoot) t.Skip(ktu.TestDisabledNeedRoot)
} }
@@ -84,125 +83,92 @@ func TestIsHostDeviceCreateFile(t *testing.T) {
path := "/dev/foobar" path := "/dev/foobar"
f, err := os.Create(path) f, err := os.Create(path)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
f.Close() f.Close()
if isHostDevice(path) != false { assert.False(isHostDevice(path))
t.Fatalf("Expected result for path %s : %v, got %v", path, false, true) assert.NoError(os.Remove(path))
}
if err := os.Remove(path); err != nil {
t.Fatal(err)
}
} }
func TestMajorMinorNumber(t *testing.T) { func TestMajorMinorNumber(t *testing.T) {
assert := assert.New(t)
devices := []string{"/dev/zero", "/dev/net/tun"} devices := []string{"/dev/zero", "/dev/net/tun"}
for _, device := range devices { for _, device := range devices {
cmdStr := fmt.Sprintf("ls -l %s | awk '{print $5$6}'", device) cmdStr := fmt.Sprintf("ls -l %s | awk '{print $5$6}'", device)
cmd := exec.Command("sh", "-c", cmdStr) cmd := exec.Command("sh", "-c", cmdStr)
output, err := cmd.Output() output, err := cmd.Output()
assert.NoError(err)
if err != nil {
t.Fatal(err)
}
data := bytes.Split(output, []byte(",")) data := bytes.Split(output, []byte(","))
if len(data) < 2 { assert.False(len(data) < 2)
t.Fatal()
}
majorStr := strings.TrimSpace(string(data[0])) majorStr := strings.TrimSpace(string(data[0]))
minorStr := strings.TrimSpace(string(data[1])) minorStr := strings.TrimSpace(string(data[1]))
majorNo, err := strconv.Atoi(majorStr) majorNo, err := strconv.Atoi(majorStr)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
minorNo, err := strconv.Atoi(minorStr) minorNo, err := strconv.Atoi(minorStr)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
stat := syscall.Stat_t{} stat := syscall.Stat_t{}
err = syscall.Stat(device, &stat) err = syscall.Stat(device, &stat)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
// Get major and minor numbers for the device itself. Note the use of stat.Rdev instead of Dev. // Get major and minor numbers for the device itself. Note the use of stat.Rdev instead of Dev.
major := major(stat.Rdev) major := major(stat.Rdev)
minor := minor(stat.Rdev) minor := minor(stat.Rdev)
if minor != minorNo { assert.Equal(minor, minorNo)
t.Fatalf("Expected minor number for device %s: %d, Got :%d", device, minorNo, minor) assert.Equal(major, majorNo)
}
if major != majorNo {
t.Fatalf("Expected major number for device %s : %d, Got :%d", device, majorNo, major)
}
} }
} }
func TestGetDeviceForPathRoot(t *testing.T) { func TestGetDeviceForPathRoot(t *testing.T) {
assert := assert.New(t)
dev, err := getDeviceForPath("/") dev, err := getDeviceForPath("/")
if err != nil { assert.NoError(err)
t.Fatal(err)
}
expected := "/" expected := "/"
if dev.mountPoint != expected { assert.Equal(dev.mountPoint, expected)
t.Fatalf("Expected %s mountpoint, got %s", expected, dev.mountPoint)
}
} }
func TestGetDeviceForPathValidMount(t *testing.T) { func TestGetDeviceForPathValidMount(t *testing.T) {
assert := assert.New(t)
dev, err := getDeviceForPath("/proc") dev, err := getDeviceForPath("/proc")
if err != nil { assert.NoError(err)
t.Fatal(err)
}
expected := "/proc" expected := "/proc"
if dev.mountPoint != expected { assert.Equal(dev.mountPoint, expected)
t.Fatalf("Expected %s mountpoint, got %s", expected, dev.mountPoint)
}
} }
func TestGetDeviceForPathEmptyPath(t *testing.T) { func TestGetDeviceForPathEmptyPath(t *testing.T) {
assert := assert.New(t)
_, err := getDeviceForPath("") _, err := getDeviceForPath("")
if err == nil { assert.Error(err)
t.Fatal()
}
} }
func TestGetDeviceForPath(t *testing.T) { func TestGetDeviceForPath(t *testing.T) {
dev, err := getDeviceForPath("///") assert := assert.New(t)
if err != nil {
t.Fatal(err)
}
if dev.mountPoint != "/" { dev, err := getDeviceForPath("///")
t.Fatal(err) assert.NoError(err)
}
assert.Equal(dev.mountPoint, "/")
_, err = getDeviceForPath("/../../.././././../.") _, err = getDeviceForPath("/../../.././././../.")
if err != nil { assert.NoError(err)
t.Fatal(err)
}
_, err = getDeviceForPath("/root/file with spaces") _, err = getDeviceForPath("/root/file with spaces")
if err == nil { assert.Error(err)
t.Fatal()
}
} }
func TestGetDeviceForPathBindMount(t *testing.T) { func TestGetDeviceForPathBindMount(t *testing.T) {
assert := assert.New(t)
if tc.NotValid(ktu.NeedRoot()) { if tc.NotValid(ktu.NeedRoot()) {
t.Skip(ktu.TestDisabledNeedRoot) t.Skip(ktu.TestDisabledNeedRoot)
} }
@@ -214,130 +180,107 @@ func TestGetDeviceForPathBindMount(t *testing.T) {
os.Remove(dest) os.Remove(dest)
err := os.MkdirAll(source, mountPerm) err := os.MkdirAll(source, mountPerm)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer os.Remove(source) defer os.Remove(source)
err = os.MkdirAll(dest, mountPerm) err = os.MkdirAll(dest, mountPerm)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer os.Remove(dest) defer os.Remove(dest)
err = bindMount(context.Background(), source, dest, false) err = bindMount(context.Background(), source, dest, false)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer syscall.Unmount(dest, syscall.MNT_DETACH) defer syscall.Unmount(dest, syscall.MNT_DETACH)
destFile := filepath.Join(dest, "test") destFile := filepath.Join(dest, "test")
_, err = os.Create(destFile) _, err = os.Create(destFile)
if err != nil { assert.NoError(err)
fmt.Println("Could not create test file:", err)
t.Fatal(err)
}
defer os.Remove(destFile) defer os.Remove(destFile)
sourceDev, _ := getDeviceForPath(source) sourceDev, _ := getDeviceForPath(source)
destDev, _ := getDeviceForPath(destFile) destDev, _ := getDeviceForPath(destFile)
if sourceDev != destDev { assert.Equal(sourceDev, destDev)
t.Fatal()
}
} }
func TestGetDevicePathAndFsTypeEmptyMount(t *testing.T) { func TestGetDevicePathAndFsTypeEmptyMount(t *testing.T) {
assert := assert.New(t)
_, _, err := GetDevicePathAndFsType("") _, _, err := GetDevicePathAndFsType("")
assert.Error(err)
if err == nil {
t.Fatal()
}
} }
func TestGetDevicePathAndFsTypeSuccessful(t *testing.T) { func TestGetDevicePathAndFsTypeSuccessful(t *testing.T) {
assert := assert.New(t)
path, fstype, err := GetDevicePathAndFsType("/proc") path, fstype, err := GetDevicePathAndFsType("/proc")
assert.NoError(err)
if err != nil { assert.Equal(path, "proc")
t.Fatal(err) assert.Equal(fstype, "proc")
}
if path != "proc" || fstype != "proc" {
t.Fatal(err)
}
} }
func TestIsDeviceMapper(t *testing.T) { func TestIsDeviceMapper(t *testing.T) {
assert := assert.New(t)
// known major, minor for /dev/tty // known major, minor for /dev/tty
major := 5 major := 5
minor := 0 minor := 0
isDM, err := isDeviceMapper(major, minor) isDM, err := isDeviceMapper(major, minor)
if err != nil { assert.NoError(err)
t.Fatal(err) assert.False(isDM)
}
if isDM {
t.Fatal()
}
// fake the block device format // fake the block device format
blockFormatTemplate = "/sys/dev/char/%d:%d" blockFormatTemplate = "/sys/dev/char/%d:%d"
isDM, err = isDeviceMapper(major, minor) isDM, err = isDeviceMapper(major, minor)
if err != nil { assert.NoError(err)
t.Fatal(err) assert.True(isDM)
}
if !isDM {
t.Fatal()
}
} }
func TestIsDockerVolume(t *testing.T) { func TestIsDockerVolume(t *testing.T) {
assert := assert.New(t)
path := "/var/lib/docker/volumes/00da1347c7cf4f15db35f/_data" path := "/var/lib/docker/volumes/00da1347c7cf4f15db35f/_data"
isDockerVolume := IsDockerVolume(path) isDockerVolume := IsDockerVolume(path)
assert.True(t, isDockerVolume) assert.True(isDockerVolume)
path = "/var/lib/testdir" path = "/var/lib/testdir"
isDockerVolume = IsDockerVolume(path) isDockerVolume = IsDockerVolume(path)
assert.False(t, isDockerVolume) assert.False(isDockerVolume)
} }
func TestIsEphemeralStorage(t *testing.T) { func TestIsEphemeralStorage(t *testing.T) {
assert := assert.New(t)
if tc.NotValid(ktu.NeedRoot()) { if tc.NotValid(ktu.NeedRoot()) {
t.Skip(ktu.TestDisabledNeedRoot) t.Skip(ktu.TestDisabledNeedRoot)
} }
dir, err := ioutil.TempDir(testDir, "foo") dir, err := ioutil.TempDir(testDir, "foo")
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer os.RemoveAll(dir) defer os.RemoveAll(dir)
sampleEphePath := filepath.Join(dir, K8sEmptyDir, "tmp-volume") sampleEphePath := filepath.Join(dir, K8sEmptyDir, "tmp-volume")
err = os.MkdirAll(sampleEphePath, testDirMode) err = os.MkdirAll(sampleEphePath, testDirMode)
assert.Nil(t, err) assert.Nil(err)
err = syscall.Mount("tmpfs", sampleEphePath, "tmpfs", 0, "") err = syscall.Mount("tmpfs", sampleEphePath, "tmpfs", 0, "")
assert.Nil(t, err) assert.NoError(err)
defer syscall.Unmount(sampleEphePath, 0) defer syscall.Unmount(sampleEphePath, 0)
isEphe := IsEphemeralStorage(sampleEphePath) isEphe := IsEphemeralStorage(sampleEphePath)
assert.True(t, isEphe) assert.True(isEphe)
isHostEmptyDir := Isk8sHostEmptyDir(sampleEphePath) isHostEmptyDir := Isk8sHostEmptyDir(sampleEphePath)
assert.False(t, isHostEmptyDir) assert.False(isHostEmptyDir)
sampleEphePath = "/var/lib/kubelet/pods/366c3a75-4869-11e8-b479-507b9ddd5ce4/volumes/cache-volume" sampleEphePath = "/var/lib/kubelet/pods/366c3a75-4869-11e8-b479-507b9ddd5ce4/volumes/cache-volume"
isEphe = IsEphemeralStorage(sampleEphePath) isEphe = IsEphemeralStorage(sampleEphePath)
assert.False(t, isEphe) assert.False(isEphe)
isHostEmptyDir = Isk8sHostEmptyDir(sampleEphePath) isHostEmptyDir = Isk8sHostEmptyDir(sampleEphePath)
assert.False(t, isHostEmptyDir) assert.False(isHostEmptyDir)
} }
// TestBindUnmountContainerRootfsENOENTNotError tests that if a file // TestBindUnmountContainerRootfsENOENTNotError tests that if a file
@@ -347,15 +290,14 @@ func TestBindUnmountContainerRootfsENOENTNotError(t *testing.T) {
testMnt := "/tmp/test_mount" testMnt := "/tmp/test_mount"
sID := "sandIDTest" sID := "sandIDTest"
cID := "contIDTest" cID := "contIDTest"
assert := assert.New(t)
// check to make sure the file doesn't exist // check to make sure the file doesn't exist
testPath := filepath.Join(testMnt, sID, cID, rootfsDir) testPath := filepath.Join(testMnt, sID, cID, rootfsDir)
if _, err := os.Stat(testPath); !os.IsNotExist(err) { if _, err := os.Stat(testPath); !os.IsNotExist(err) {
if err := os.Remove(testPath); err != nil { assert.NoError(os.Remove(testPath))
t.Fatalf("test mount file should not exist, and cannot be removed: %s", err)
}
} }
err := bindUnmountContainerRootfs(context.Background(), testMnt, sID, cID) err := bindUnmountContainerRootfs(context.Background(), testMnt, sID, cID)
assert.Nil(t, err) assert.NoError(err)
} }

View File

@@ -18,28 +18,20 @@ import (
) )
func TestCreateDeleteNetNS(t *testing.T) { func TestCreateDeleteNetNS(t *testing.T) {
assert := assert.New(t)
if tc.NotValid(ktu.NeedRoot()) { if tc.NotValid(ktu.NeedRoot()) {
t.Skip(testDisabledAsNonRoot) t.Skip(testDisabledAsNonRoot)
} }
netNSPath, err := createNetNS() netNSPath, err := createNetNS()
if err != nil { assert.NoError(err)
t.Fatal(err) assert.NotEmpty(netNSPath)
}
if netNSPath == "" {
t.Fatal()
}
_, err = os.Stat(netNSPath) _, err = os.Stat(netNSPath)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
err = deleteNetNS(netNSPath) err = deleteNetNS(netNSPath)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
} }
func TestGenerateInterfacesAndRoutes(t *testing.T) { func TestGenerateInterfacesAndRoutes(t *testing.T) {

View File

@@ -39,133 +39,111 @@ func testCreateNoopContainer() (*Sandbox, *Container, error) {
func TestNoopAgentInit(t *testing.T) { func TestNoopAgentInit(t *testing.T) {
n := &noopAgent{} n := &noopAgent{}
sandbox := &Sandbox{} sandbox := &Sandbox{}
assert := assert.New(t)
disableVMShutdown, err := n.init(context.Background(), sandbox, nil) disableVMShutdown, err := n.init(context.Background(), sandbox, nil)
if err != nil { assert.NoError(err)
t.Fatal(err) assert.False(disableVMShutdown)
}
if disableVMShutdown != false {
t.Fatal(err)
}
} }
func TestNoopAgentExec(t *testing.T) { func TestNoopAgentExec(t *testing.T) {
n := &noopAgent{} n := &noopAgent{}
cmd := types.Cmd{} cmd := types.Cmd{}
assert := assert.New(t)
sandbox, container, err := testCreateNoopContainer() sandbox, container, err := testCreateNoopContainer()
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer cleanUp() defer cleanUp()
if _, err = n.exec(sandbox, *container, cmd); err != nil { _, err = n.exec(sandbox, *container, cmd)
t.Fatal(err) assert.NoError(err)
}
} }
func TestNoopAgentStartSandbox(t *testing.T) { func TestNoopAgentStartSandbox(t *testing.T) {
n := &noopAgent{} n := &noopAgent{}
sandbox := &Sandbox{} sandbox := &Sandbox{}
assert := assert.New(t)
err := n.startSandbox(sandbox) err := n.startSandbox(sandbox)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
} }
func TestNoopAgentStopSandbox(t *testing.T) { func TestNoopAgentStopSandbox(t *testing.T) {
n := &noopAgent{} n := &noopAgent{}
sandbox := &Sandbox{} sandbox := &Sandbox{}
assert := assert.New(t)
err := n.stopSandbox(sandbox) err := n.stopSandbox(sandbox)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
} }
func TestNoopAgentCreateContainer(t *testing.T) { func TestNoopAgentCreateContainer(t *testing.T) {
n := &noopAgent{} n := &noopAgent{}
assert := assert.New(t)
sandbox, container, err := testCreateNoopContainer() sandbox, container, err := testCreateNoopContainer()
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer cleanUp() defer cleanUp()
if err := n.startSandbox(sandbox); err != nil { err = n.startSandbox(sandbox)
t.Fatal(err) assert.NoError(err)
}
if _, err := n.createContainer(sandbox, container); err != nil { _, err = n.createContainer(sandbox, container)
t.Fatal(err) assert.NoError(err)
}
} }
func TestNoopAgentStartContainer(t *testing.T) { func TestNoopAgentStartContainer(t *testing.T) {
n := &noopAgent{} n := &noopAgent{}
assert := assert.New(t)
sandbox, container, err := testCreateNoopContainer() sandbox, container, err := testCreateNoopContainer()
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer cleanUp() defer cleanUp()
err = n.startContainer(sandbox, container) err = n.startContainer(sandbox, container)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
} }
func TestNoopAgentStopContainer(t *testing.T) { func TestNoopAgentStopContainer(t *testing.T) {
n := &noopAgent{} n := &noopAgent{}
assert := assert.New(t)
sandbox, container, err := testCreateNoopContainer() sandbox, container, err := testCreateNoopContainer()
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer cleanUp() defer cleanUp()
err = n.stopContainer(sandbox, *container) err = n.stopContainer(sandbox, *container)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
} }
func TestNoopAgentStatsContainer(t *testing.T) { func TestNoopAgentStatsContainer(t *testing.T) {
n := &noopAgent{} n := &noopAgent{}
assert := assert.New(t)
sandbox, container, err := testCreateNoopContainer() sandbox, container, err := testCreateNoopContainer()
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer cleanUp() defer cleanUp()
_, err = n.statsContainer(sandbox, *container) _, err = n.statsContainer(sandbox, *container)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
} }
func TestNoopAgentPauseContainer(t *testing.T) { func TestNoopAgentPauseContainer(t *testing.T) {
n := &noopAgent{} n := &noopAgent{}
assert := assert.New(t)
sandbox, container, err := testCreateNoopContainer() sandbox, container, err := testCreateNoopContainer()
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer cleanUp() defer cleanUp()
err = n.pauseContainer(sandbox, *container) err = n.pauseContainer(sandbox, *container)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
} }
func TestNoopAgentResumeContainer(t *testing.T) { func TestNoopAgentResumeContainer(t *testing.T) {
n := &noopAgent{} n := &noopAgent{}
assert := assert.New(t)
sandbox, container, err := testCreateNoopContainer() sandbox, container, err := testCreateNoopContainer()
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer cleanUp() defer cleanUp()
err = n.resumeContainer(sandbox, *container) err = n.resumeContainer(sandbox, *container)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
} }
func TestNoopAgentConfigure(t *testing.T) { func TestNoopAgentConfigure(t *testing.T) {
@@ -173,102 +151,88 @@ func TestNoopAgentConfigure(t *testing.T) {
h := &mockHypervisor{} h := &mockHypervisor{}
id := "foobar" id := "foobar"
sharePath := "foobarDir" sharePath := "foobarDir"
assert := assert.New(t)
err := n.configure(h, id, sharePath, true, nil) err := n.configure(h, id, sharePath, true, nil)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
} }
func TestNoopAgentGetVMPath(t *testing.T) { func TestNoopAgentGetVMPath(t *testing.T) {
n := &noopAgent{} n := &noopAgent{}
path := n.getVMPath("") path := n.getVMPath("")
if path != "" { assert := assert.New(t)
t.Fatal("getSharePath returns non empty path") assert.Empty(path)
}
} }
func TestNoopAgentGetSharePath(t *testing.T) { func TestNoopAgentGetSharePath(t *testing.T) {
n := &noopAgent{} n := &noopAgent{}
path := n.getSharePath("") path := n.getSharePath("")
if path != "" { assert := assert.New(t)
t.Fatal("getSharePath returns non empty path") assert.Empty(path)
}
} }
func TestNoopAgentStartProxy(t *testing.T) { func TestNoopAgentStartProxy(t *testing.T) {
assert := assert.New(t)
n := &noopAgent{} n := &noopAgent{}
sandbox, _, err := testCreateNoopContainer() sandbox, _, err := testCreateNoopContainer()
if err != nil {
t.Fatal(err) assert.NoError(err)
}
defer cleanUp() defer cleanUp()
err = n.startProxy(sandbox) err = n.startProxy(sandbox)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
} }
func TestNoopAgentProcessListContainer(t *testing.T) { func TestNoopAgentProcessListContainer(t *testing.T) {
assert := assert.New(t)
n := &noopAgent{} n := &noopAgent{}
sandbox, container, err := testCreateNoopContainer() sandbox, container, err := testCreateNoopContainer()
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer cleanUp() defer cleanUp()
_, err = n.processListContainer(sandbox, *container, ProcessListOptions{}) _, err = n.processListContainer(sandbox, *container, ProcessListOptions{})
if err != nil { assert.NoError(err)
t.Fatal(err)
}
} }
func TestNoopAgentReseedRNG(t *testing.T) { func TestNoopAgentReseedRNG(t *testing.T) {
assert := assert.New(t)
n := &noopAgent{} n := &noopAgent{}
err := n.reseedRNG([]byte{}) err := n.reseedRNG([]byte{})
if err != nil { assert.NoError(err)
t.Fatal("reseedRNG failed")
}
} }
func TestNoopAgentUpdateInterface(t *testing.T) { func TestNoopAgentUpdateInterface(t *testing.T) {
assert := assert.New(t)
n := &noopAgent{} n := &noopAgent{}
_, err := n.updateInterface(nil) _, err := n.updateInterface(nil)
if err != nil { assert.NoError(err)
t.Fatal("updateInterface failed")
}
} }
func TestNoopAgentListInterfaces(t *testing.T) { func TestNoopAgentListInterfaces(t *testing.T) {
assert := assert.New(t)
n := &noopAgent{} n := &noopAgent{}
_, err := n.listInterfaces() _, err := n.listInterfaces()
if err != nil { assert.NoError(err)
t.Fatal("listInterfaces failed")
}
} }
func TestNoopAgentUpdateRoutes(t *testing.T) { func TestNoopAgentUpdateRoutes(t *testing.T) {
assert := assert.New(t)
n := &noopAgent{} n := &noopAgent{}
_, err := n.updateRoutes(nil) _, err := n.updateRoutes(nil)
if err != nil { assert.NoError(err)
t.Fatal("updateRoutes failed")
}
} }
func TestNoopAgentListRoutes(t *testing.T) { func TestNoopAgentListRoutes(t *testing.T) {
n := &noopAgent{} n := &noopAgent{}
assert := assert.New(t)
_, err := n.listRoutes() _, err := n.listRoutes()
if err != nil { assert.NoError(err)
t.Fatal("listRoutes failed")
}
} }
func TestNoopAgentRSetProxy(t *testing.T) { func TestNoopAgentRSetProxy(t *testing.T) {
n := &noopAgent{} n := &noopAgent{}
p := &noopProxy{} p := &noopProxy{}
s := &Sandbox{} s := &Sandbox{}
assert := assert.New(t)
err := n.setProxy(s, p, 0, "") err := n.setProxy(s, p, 0, "")
if err != nil { assert.NoError(err)
t.Fatal("set proxy failed")
}
} }
func TestNoopGetAgentUrl(t *testing.T) { func TestNoopGetAgentUrl(t *testing.T) {

View File

@@ -7,20 +7,18 @@ package virtcontainers
import ( import (
"testing" "testing"
"github.com/stretchr/testify/assert"
) )
func TestNoopShimStart(t *testing.T) { func TestNoopShimStart(t *testing.T) {
assert := assert.New(t)
s := &noopShim{} s := &noopShim{}
sandbox := &Sandbox{} sandbox := &Sandbox{}
params := ShimParams{} params := ShimParams{}
expected := 0 expected := 0
pid, err := s.start(sandbox, params) pid, err := s.start(sandbox, params)
if err != nil { assert.NoError(err)
t.Fatal(err) assert.Equal(pid, expected)
}
if pid != expected {
t.Fatalf("PID should be %d", expected)
}
} }

View File

@@ -8,19 +8,16 @@ package virtcontainers
import ( import (
"strings" "strings"
"testing" "testing"
"github.com/stretchr/testify/assert"
) )
func testNsEnterFormatArgs(t *testing.T, args []string, expected string) { func testNsEnterFormatArgs(t *testing.T, args []string, expected string) {
nsenter := &nsenter{} nsenter := &nsenter{}
cmd, err := nsenter.formatArgs(args) cmd, err := nsenter.formatArgs(args)
if err != nil { assert.NoError(t, err)
t.Fatal(err) assert.Equal(t, strings.Join(cmd, " "), expected)
}
if strings.Join(cmd, " ") != expected {
t.Fatal()
}
} }
func TestNsEnterFormatArgsHello(t *testing.T) { func TestNsEnterFormatArgsHello(t *testing.T) {

View File

@@ -45,26 +45,24 @@ func testCreateExpSandbox() (*Sandbox, error) {
} }
func TestSupportNewStore(t *testing.T) { func TestSupportNewStore(t *testing.T) {
assert := assert.New(t)
hConfig := newHypervisorConfig(nil, nil) hConfig := newHypervisorConfig(nil, nil)
sandbox, err := testCreateSandbox(t, testSandboxID, MockHypervisor, hConfig, NoopAgentType, NetworkConfig{}, nil, nil) sandbox, err := testCreateSandbox(t, testSandboxID, MockHypervisor, hConfig, NoopAgentType, NetworkConfig{}, nil, nil)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer cleanUp() defer cleanUp()
// not support experimental // not support experimental
assert.False(t, sandbox.supportNewStore()) assert.False(sandbox.supportNewStore())
// support experimental // support experimental
sandbox, err = testCreateExpSandbox() sandbox, err = testCreateExpSandbox()
if err != nil { assert.NoError(err)
t.Fatal(err) assert.True(sandbox.supportNewStore())
}
assert.True(t, sandbox.supportNewStore())
} }
func TestSandboxRestore(t *testing.T) { func TestSandboxRestore(t *testing.T) {
var err error var err error
assert := assert.New(t)
sconfig := SandboxConfig{ sconfig := SandboxConfig{
ID: "test-exp", ID: "test-exp",
Experimental: []exp.Feature{persist.NewStoreFeature}, Experimental: []exp.Feature{persist.NewStoreFeature},
@@ -81,24 +79,24 @@ func TestSandboxRestore(t *testing.T) {
config: &sconfig, config: &sconfig,
} }
if sandbox.newStore, err = persist.GetDriver("fs"); err != nil || sandbox.newStore == nil { sandbox.newStore, err = persist.GetDriver("fs")
t.Fatalf("failed to get fs persist driver") assert.NoError(err)
} assert.NotNil(sandbox.newStore)
// if we don't call ToDisk, we can get nothing from disk // if we don't call ToDisk, we can get nothing from disk
err = sandbox.Restore() err = sandbox.Restore()
assert.NotNil(t, err) assert.NotNil(t, err)
assert.True(t, os.IsNotExist(err)) assert.True(os.IsNotExist(err))
// disk data are empty // disk data are empty
err = sandbox.Save() err = sandbox.Save()
assert.Nil(t, err) assert.NoError(err)
err = sandbox.Restore() err = sandbox.Restore()
assert.Nil(t, err) assert.NoError(err)
assert.Equal(t, sandbox.state.State, types.StateString("")) assert.Equal(sandbox.state.State, types.StateString(""))
assert.Equal(t, sandbox.state.GuestMemoryBlockSizeMB, uint32(0)) assert.Equal(sandbox.state.GuestMemoryBlockSizeMB, uint32(0))
assert.Equal(t, sandbox.state.BlockIndex, 0) assert.Equal(sandbox.state.BlockIndex, 0)
// set state data and save again // set state data and save again
sandbox.state.State = types.StateString("running") sandbox.state.State = types.StateString("running")
@@ -106,15 +104,15 @@ func TestSandboxRestore(t *testing.T) {
sandbox.state.BlockIndex = 2 sandbox.state.BlockIndex = 2
// flush data to disk // flush data to disk
err = sandbox.Save() err = sandbox.Save()
assert.Nil(t, err) assert.Nil(err)
// empty the sandbox // empty the sandbox
sandbox.state = types.SandboxState{} sandbox.state = types.SandboxState{}
// restore data from disk // restore data from disk
err = sandbox.Restore() err = sandbox.Restore()
assert.Nil(t, err) assert.Nil(err)
assert.Equal(t, sandbox.state.State, types.StateString("running")) assert.Equal(sandbox.state.State, types.StateString("running"))
assert.Equal(t, sandbox.state.GuestMemoryBlockSizeMB, uint32(1024)) assert.Equal(sandbox.state.GuestMemoryBlockSizeMB, uint32(1024))
assert.Equal(t, sandbox.state.BlockIndex, 2) assert.Equal(sandbox.state.BlockIndex, 2)
} }

View File

@@ -43,6 +43,8 @@ func TestPhysicalEndpoint_HotDetach(t *testing.T) {
} }
func TestIsPhysicalIface(t *testing.T) { func TestIsPhysicalIface(t *testing.T) {
assert := assert.New(t)
if tc.NotValid(ktu.NeedRoot()) { if tc.NotValid(ktu.NeedRoot()) {
t.Skip(testDisabledAsNonRoot) t.Skip(testDisabledAsNonRoot)
} }
@@ -52,9 +54,7 @@ func TestIsPhysicalIface(t *testing.T) {
testMACAddr := "00:00:00:00:00:01" testMACAddr := "00:00:00:00:00:01"
hwAddr, err := net.ParseMAC(testMACAddr) hwAddr, err := net.ParseMAC(testMACAddr)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
link := &netlink.Bridge{ link := &netlink.Bridge{
LinkAttrs: netlink.LinkAttrs{ LinkAttrs: netlink.LinkAttrs{
@@ -66,26 +66,19 @@ func TestIsPhysicalIface(t *testing.T) {
} }
n, err := ns.NewNS() n, err := ns.NewNS()
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer n.Close() defer n.Close()
netnsHandle, err := netns.GetFromPath(n.Path()) netnsHandle, err := netns.GetFromPath(n.Path())
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer netnsHandle.Close() defer netnsHandle.Close()
netlinkHandle, err := netlink.NewHandleAt(netnsHandle) netlinkHandle, err := netlink.NewHandleAt(netnsHandle)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer netlinkHandle.Delete() defer netlinkHandle.Delete()
if err := netlinkHandle.LinkAdd(link); err != nil { err = netlinkHandle.LinkAdd(link)
t.Fatal(err) assert.NoError(err)
}
var isPhysical bool var isPhysical bool
err = doNetNS(n.Path(), func(_ ns.NetNS) error { err = doNetNS(n.Path(), func(_ ns.NetNS) error {
@@ -93,12 +86,6 @@ func TestIsPhysicalIface(t *testing.T) {
isPhysical, err = isPhysicalIface(testNetIface) isPhysical, err = isPhysicalIface(testNetIface)
return err return err
}) })
assert.NoError(err)
if err != nil { assert.False(isPhysical)
t.Fatal(err)
}
if isPhysical == true {
t.Fatalf("Got %+v\nExpecting %+v", isPhysical, false)
}
} }

View File

@@ -51,15 +51,11 @@ func TestGetFileFromNSEmptyNSPathFailure(t *testing.T) {
func TestGetFileFromNSNotExistingNSPathFailure(t *testing.T) { func TestGetFileFromNSNotExistingNSPathFailure(t *testing.T) {
nsFile, err := ioutil.TempFile("", "not-existing-ns-path") nsFile, err := ioutil.TempFile("", "not-existing-ns-path")
if err != nil { assert.NoError(t, err)
t.Fatal(err)
}
nsFilePath := nsFile.Name() nsFilePath := nsFile.Name()
nsFile.Close() nsFile.Close()
if err := os.Remove(nsFilePath); err != nil { assert.NoError(t, os.Remove(nsFilePath))
t.Fatal(err)
}
nsFile, err = getFileFromNS(nsFilePath) nsFile, err = getFileFromNS(nsFilePath)
assert.NotNil(t, err, "Not existing path should result as a failure") assert.NotNil(t, err, "Not existing path should result as a failure")
@@ -68,9 +64,7 @@ func TestGetFileFromNSNotExistingNSPathFailure(t *testing.T) {
func TestGetFileFromNSWrongNSPathFailure(t *testing.T) { func TestGetFileFromNSWrongNSPathFailure(t *testing.T) {
nsFile, err := ioutil.TempFile("", "wrong-ns-path") nsFile, err := ioutil.TempFile("", "wrong-ns-path")
if err != nil { assert.NoError(t, err)
t.Fatal(err)
}
nsFilePath := nsFile.Name() nsFilePath := nsFile.Name()
nsFile.Close() nsFile.Close()
@@ -125,9 +119,7 @@ func TestSetNSUnknownNSTypeFailure(t *testing.T) {
func TestSetNSWrongFileFailure(t *testing.T) { func TestSetNSWrongFileFailure(t *testing.T) {
nsFile, err := ioutil.TempFile("", "wrong-ns-path") nsFile, err := ioutil.TempFile("", "wrong-ns-path")
if err != nil { assert.NoError(t, err)
t.Fatal(err)
}
defer func() { defer func() {
nsFilePath := nsFile.Name() nsFilePath := nsFile.Name()
nsFile.Close() nsFile.Close()
@@ -182,9 +174,7 @@ func TestNsEnterSuccessful(t *testing.T) {
} }
sleepPID, err := startSleepBinary(sleepDuration, cloneFlags) sleepPID, err := startSleepBinary(sleepDuration, cloneFlags)
if err != nil { assert.NoError(t, err)
t.Fatal(err)
}
defer func() { defer func() {
if sleepPID > 1 { if sleepPID > 1 {
unix.Kill(sleepPID, syscall.SIGKILL) unix.Kill(sleepPID, syscall.SIGKILL)

View File

@@ -12,7 +12,6 @@ import (
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
"reflect"
"runtime" "runtime"
"strconv" "strconv"
"testing" "testing"
@@ -90,10 +89,9 @@ func createConfig(fileName string, fileData string) (string, error) {
} }
func TestMinimalSandboxConfig(t *testing.T) { func TestMinimalSandboxConfig(t *testing.T) {
assert := assert.New(t)
configPath, err := createConfig("config.json", minimalConfig) configPath, err := createConfig("config.json", minimalConfig)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
savedFunc := config.GetHostPathFunc savedFunc := config.GetHostPathFunc
@@ -171,20 +169,15 @@ func TestMinimalSandboxConfig(t *testing.T) {
var minimalOCISpec CompatOCISpec var minimalOCISpec CompatOCISpec
//Marshal and unmarshall json to compare sandboxConfig and expectedSandboxConfig //Marshal and unmarshall json to compare sandboxConfig and expectedSandboxConfig
if err := json.Unmarshal([]byte(minimalConfig), &minimalOCISpec); err != nil { err = json.Unmarshal([]byte(minimalConfig), &minimalOCISpec)
t.Fatal(err) assert.NoError(err)
}
if minimalOCISpec.Process != nil { if minimalOCISpec.Process != nil {
caps, err := ContainerCapabilities(minimalOCISpec) caps, err := ContainerCapabilities(minimalOCISpec)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
minimalOCISpec.Process.Capabilities = caps minimalOCISpec.Process.Capabilities = caps
} }
ociSpecJSON, err := json.Marshal(minimalOCISpec) ociSpecJSON, err := json.Marshal(minimalOCISpec)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
devInfo := config.DeviceInfo{ devInfo := config.DeviceInfo{
ContainerPath: "/dev/vfio/17", ContainerPath: "/dev/vfio/17",
@@ -240,30 +233,18 @@ func TestMinimalSandboxConfig(t *testing.T) {
} }
ociSpec, err := ParseConfigJSON(tempBundlePath) ociSpec, err := ParseConfigJSON(tempBundlePath)
if err != nil { assert.NoError(err)
t.Fatalf("Could not parse config.json: %v", err)
}
sandboxConfig, err := SandboxConfig(ociSpec, runtimeConfig, tempBundlePath, containerID, consolePath, false, true) sandboxConfig, err := SandboxConfig(ociSpec, runtimeConfig, tempBundlePath, containerID, consolePath, false, true)
if err != nil { assert.NoError(err)
t.Fatalf("Could not create Sandbox configuration %v", err)
}
if reflect.DeepEqual(sandboxConfig, expectedSandboxConfig) == false { assert.Exactly(sandboxConfig, expectedSandboxConfig)
t.Fatalf("Got %v\n expecting %v", sandboxConfig, expectedSandboxConfig) assert.NoError(os.Remove(configPath))
}
if err := os.Remove(configPath); err != nil {
t.Fatal(err)
}
} }
func testStatusToOCIStateSuccessful(t *testing.T, cStatus vc.ContainerStatus, expected specs.State) { func testStatusToOCIStateSuccessful(t *testing.T, cStatus vc.ContainerStatus, expected specs.State) {
ociState := StatusToOCIState(cStatus) ociState := StatusToOCIState(cStatus)
assert.Exactly(t, ociState, expected)
if reflect.DeepEqual(ociState, expected) == false {
t.Fatalf("Got %v\n expecting %v", ociState, expected)
}
} }
func TestStatusToOCIStateSuccessfulWithReadyState(t *testing.T) { func TestStatusToOCIStateSuccessfulWithReadyState(t *testing.T) {
@@ -405,33 +386,25 @@ func TestStatusToOCIStateSuccessfulWithNoState(t *testing.T) {
func TestStateToOCIState(t *testing.T) { func TestStateToOCIState(t *testing.T) {
var state types.StateString var state types.StateString
assert := assert.New(t)
if ociState := StateToOCIState(state); ociState != "" { assert.Empty(StateToOCIState(state))
t.Fatalf("Expecting \"created\" state, got \"%s\"", ociState)
}
state = types.StateReady state = types.StateReady
if ociState := StateToOCIState(state); ociState != "created" { assert.Equal(StateToOCIState(state), "created")
t.Fatalf("Expecting \"created\" state, got \"%s\"", ociState)
}
state = types.StateRunning state = types.StateRunning
if ociState := StateToOCIState(state); ociState != "running" { assert.Equal(StateToOCIState(state), "running")
t.Fatalf("Expecting \"created\" state, got \"%s\"", ociState)
}
state = types.StateStopped state = types.StateStopped
if ociState := StateToOCIState(state); ociState != "stopped" { assert.Equal(StateToOCIState(state), "stopped")
t.Fatalf("Expecting \"created\" state, got \"%s\"", ociState)
}
state = types.StatePaused state = types.StatePaused
if ociState := StateToOCIState(state); ociState != "paused" { assert.Equal(StateToOCIState(state), "paused")
t.Fatalf("Expecting \"paused\" state, got \"%s\"", ociState)
}
} }
func TestEnvVars(t *testing.T) { func TestEnvVars(t *testing.T) {
assert := assert.New(t)
envVars := []string{"foo=bar", "TERM=xterm", "HOME=/home/foo", "TERM=\"bar\"", "foo=\"\""} envVars := []string{"foo=bar", "TERM=xterm", "HOME=/home/foo", "TERM=\"bar\"", "foo=\"\""}
expectecVcEnvVars := []types.EnvVar{ expectecVcEnvVars := []types.EnvVar{
{ {
@@ -457,54 +430,36 @@ func TestEnvVars(t *testing.T) {
} }
vcEnvVars, err := EnvVars(envVars) vcEnvVars, err := EnvVars(envVars)
if err != nil { assert.NoError(err)
t.Fatalf("Could not create environment variable slice %v", err) assert.Exactly(vcEnvVars, expectecVcEnvVars)
}
if reflect.DeepEqual(vcEnvVars, expectecVcEnvVars) == false {
t.Fatalf("Got %v\n expecting %v", vcEnvVars, expectecVcEnvVars)
}
} }
func TestMalformedEnvVars(t *testing.T) { func TestMalformedEnvVars(t *testing.T) {
assert := assert.New(t)
envVars := []string{"foo"} envVars := []string{"foo"}
r, err := EnvVars(envVars) _, err := EnvVars(envVars)
if err == nil { assert.Error(err)
t.Fatalf("EnvVars() succeeded unexpectedly: [%s] variable=%s value=%s", envVars[0], r[0].Var, r[0].Value)
}
envVars = []string{"=foo"} envVars = []string{"=foo"}
r, err = EnvVars(envVars) _, err = EnvVars(envVars)
if err == nil { assert.Error(err)
t.Fatalf("EnvVars() succeeded unexpectedly: [%s] variable=%s value=%s", envVars[0], r[0].Var, r[0].Value)
}
envVars = []string{"=foo="} envVars = []string{"=foo="}
r, err = EnvVars(envVars) _, err = EnvVars(envVars)
if err == nil { assert.Error(err)
t.Fatalf("EnvVars() succeeded unexpectedly: [%s] variable=%s value=%s", envVars[0], r[0].Var, r[0].Value)
}
} }
func TestGetConfigPath(t *testing.T) { func TestGetConfigPath(t *testing.T) {
expected := filepath.Join(tempBundlePath, "config.json") expected := filepath.Join(tempBundlePath, "config.json")
configPath := getConfigPath(tempBundlePath) configPath := getConfigPath(tempBundlePath)
assert.Equal(t, configPath, expected)
if configPath != expected {
t.Fatalf("Got %s, Expecting %s", configPath, expected)
}
} }
func testGetContainerTypeSuccessful(t *testing.T, annotations map[string]string, expected vc.ContainerType) { func testGetContainerTypeSuccessful(t *testing.T, annotations map[string]string, expected vc.ContainerType) {
assert := assert.New(t)
containerType, err := GetContainerType(annotations) containerType, err := GetContainerType(annotations)
if err != nil { assert.NoError(err)
t.Fatal(err) assert.Equal(containerType, expected)
}
if containerType != expected {
t.Fatalf("Got %s, Expecting %s", containerType, expected)
}
} }
func TestGetContainerTypePodSandbox(t *testing.T) { func TestGetContainerTypePodSandbox(t *testing.T) {
@@ -525,26 +480,19 @@ func TestGetContainerTypePodContainer(t *testing.T) {
func TestGetContainerTypeFailure(t *testing.T) { func TestGetContainerTypeFailure(t *testing.T) {
expected := vc.UnknownContainerType expected := vc.UnknownContainerType
assert := assert.New(t)
containerType, err := GetContainerType(map[string]string{}) containerType, err := GetContainerType(map[string]string{})
if err == nil { assert.Error(err)
t.Fatalf("This test should fail because annotations is empty") assert.Equal(containerType, expected)
}
if containerType != expected {
t.Fatalf("Got %s, Expecting %s", containerType, expected)
}
} }
func testContainerTypeSuccessful(t *testing.T, ociSpec CompatOCISpec, expected vc.ContainerType) { func testContainerTypeSuccessful(t *testing.T, ociSpec CompatOCISpec, expected vc.ContainerType) {
containerType, err := ociSpec.ContainerType() containerType, err := ociSpec.ContainerType()
if err != nil { assert := assert.New(t)
t.Fatal(err)
}
if containerType != expected { assert.NoError(err)
t.Fatalf("Got %s, Expecting %s", containerType, expected) assert.Equal(containerType, expected)
}
} }
func TestContainerTypePodSandbox(t *testing.T) { func TestContainerTypePodSandbox(t *testing.T) {
@@ -575,54 +523,43 @@ func TestContainerTypeFailure(t *testing.T) {
var ociSpec CompatOCISpec var ociSpec CompatOCISpec
expected := vc.UnknownContainerType expected := vc.UnknownContainerType
unknownType := "unknown_type" unknownType := "unknown_type"
assert := assert.New(t)
ociSpec.Annotations = map[string]string{ ociSpec.Annotations = map[string]string{
annotations.ContainerType: unknownType, annotations.ContainerType: unknownType,
} }
containerType, err := ociSpec.ContainerType() containerType, err := ociSpec.ContainerType()
if err == nil { assert.Error(err)
t.Fatalf("This test should fail because the container type is %s", unknownType) assert.Equal(containerType, expected)
}
if containerType != expected {
t.Fatalf("Got %s, Expecting %s", containerType, expected)
}
} }
func TestSandboxIDSuccessful(t *testing.T) { func TestSandboxIDSuccessful(t *testing.T) {
var ociSpec CompatOCISpec var ociSpec CompatOCISpec
testSandboxID := "testSandboxID" testSandboxID := "testSandboxID"
assert := assert.New(t)
ociSpec.Annotations = map[string]string{ ociSpec.Annotations = map[string]string{
annotations.SandboxID: testSandboxID, annotations.SandboxID: testSandboxID,
} }
sandboxID, err := ociSpec.SandboxID() sandboxID, err := ociSpec.SandboxID()
if err != nil { assert.NoError(err)
t.Fatal(err) assert.Equal(sandboxID, testSandboxID)
}
if sandboxID != testSandboxID {
t.Fatalf("Got %s, Expecting %s", sandboxID, testSandboxID)
}
} }
func TestSandboxIDFailure(t *testing.T) { func TestSandboxIDFailure(t *testing.T) {
var ociSpec CompatOCISpec var ociSpec CompatOCISpec
assert := assert.New(t)
sandboxID, err := ociSpec.SandboxID() sandboxID, err := ociSpec.SandboxID()
if err == nil { assert.Error(err)
t.Fatalf("This test should fail because annotations is empty") assert.Empty(sandboxID)
}
if sandboxID != "" {
t.Fatalf("Got %s, Expecting empty sandbox ID", sandboxID)
}
} }
func TestAddKernelParamValid(t *testing.T) { func TestAddKernelParamValid(t *testing.T) {
var config RuntimeConfig var config RuntimeConfig
assert := assert.New(t)
expected := []vc.Param{ expected := []vc.Param{
{ {
@@ -632,9 +569,8 @@ func TestAddKernelParamValid(t *testing.T) {
} }
err := config.AddKernelParam(expected[0]) err := config.AddKernelParam(expected[0])
if err != nil || reflect.DeepEqual(config.HypervisorConfig.KernelParams, expected) == false { assert.NoError(err)
t.Fatal() assert.Exactly(config.HypervisorConfig.KernelParams, expected)
}
} }
func TestAddKernelParamInvalid(t *testing.T) { func TestAddKernelParamInvalid(t *testing.T) {
@@ -648,9 +584,7 @@ func TestAddKernelParamInvalid(t *testing.T) {
} }
err := config.AddKernelParam(invalid[0]) err := config.AddKernelParam(invalid[0])
if err == nil { assert.Error(t, err)
t.Fatal()
}
} }
func TestDeviceTypeFailure(t *testing.T) { func TestDeviceTypeFailure(t *testing.T) {

View File

@@ -5,7 +5,11 @@
package uuid package uuid
import "testing" import (
"testing"
"github.com/stretchr/testify/assert"
)
// Test UUID parsing and string conversation. // Test UUID parsing and string conversation.
// //
@@ -13,6 +17,7 @@ import "testing"
// //
// The original strings and the strings generated from the UUIDs match. // The original strings and the strings generated from the UUIDs match.
func TestUUID(t *testing.T) { func TestUUID(t *testing.T) {
assert := assert.New(t)
testUUIDs := []string{ testUUIDs := []string{
"f81d4fae-7dec-11d0-a765-00a0c91e6bf6", "f81d4fae-7dec-11d0-a765-00a0c91e6bf6",
"30dedd5c-48d9-45d3-8b44-f973e4f35e48", "30dedd5c-48d9-45d3-8b44-f973e4f35e48",
@@ -25,13 +30,9 @@ func TestUUID(t *testing.T) {
for _, s := range testUUIDs { for _, s := range testUUIDs {
uuid, err := Parse(s) uuid, err := Parse(s)
if err != nil { assert.NoError(err)
t.Fatalf("Unable to parse %s: %s", s, err)
}
s2 := uuid.String() s2 := uuid.String()
if s != s2 { assert.Equal(s, s2)
t.Fatalf("%s and %s do not match", s, s2)
}
} }
} }
@@ -43,19 +44,14 @@ func TestUUID(t *testing.T) {
// The UUIDs are generated correctly, their version number is correct, // The UUIDs are generated correctly, their version number is correct,
// and they can be parsed. // and they can be parsed.
func TestGenUUID(t *testing.T) { func TestGenUUID(t *testing.T) {
assert := assert.New(t)
for i := 0; i < 100; i++ { for i := 0; i < 100; i++ {
u := Generate() u := Generate()
s := u.String() s := u.String()
if s[14] != '4' { assert.EqualValues(s[14], '4')
t.Fatalf("Invalid UUID. Version number is incorrect")
}
u2, err := Parse(s) u2, err := Parse(s)
if err != nil { assert.NoError(err)
t.Fatalf("Failed to parse UUID %s : %s", s, err) assert.Equal(u, u2)
}
if u != u2 {
t.Fatalf("Generated and Parsed UUIDs are not equal")
}
} }
} }
@@ -77,8 +73,6 @@ func TestBadUUID(t *testing.T) {
for _, s := range badTestUUIDs { for _, s := range badTestUUIDs {
_, err := Parse(s) _, err := Parse(s)
if err == nil { assert.Error(t, err)
t.Fatalf("uuid.Parse should fail to parse %s", s)
}
} }
} }

View File

@@ -10,7 +10,6 @@ import (
"io/ioutil" "io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"reflect"
"testing" "testing"
"github.com/kata-containers/runtime/virtcontainers/store" "github.com/kata-containers/runtime/virtcontainers/store"
@@ -22,15 +21,11 @@ var testDefaultLogger = logrus.WithField("proxy", "test")
func testSetProxyType(t *testing.T, value string, expected ProxyType) { func testSetProxyType(t *testing.T, value string, expected ProxyType) {
var proxyType ProxyType var proxyType ProxyType
assert := assert.New(t)
err := (&proxyType).Set(value) err := (&proxyType).Set(value)
if err != nil { assert.NoError(err)
t.Fatal(err) assert.Equal(proxyType, expected)
}
if proxyType != expected {
t.Fatalf("Got %s\nExpecting %s", proxyType, expected)
}
} }
func TestSetKataProxyType(t *testing.T) { func TestSetKataProxyType(t *testing.T) {
@@ -51,26 +46,20 @@ func TestSetKataBuiltInProxyType(t *testing.T) {
func TestSetUnknownProxyType(t *testing.T) { func TestSetUnknownProxyType(t *testing.T) {
var proxyType ProxyType var proxyType ProxyType
assert := assert.New(t)
unknownType := "unknown" unknownType := "unknown"
err := (&proxyType).Set(unknownType) err := (&proxyType).Set(unknownType)
if err == nil { assert.Error(err)
t.Fatalf("Should fail because %s type used", unknownType) assert.NotEqual(proxyType, NoopProxyType)
} assert.NotEqual(proxyType, NoProxyType)
assert.NotEqual(proxyType, KataProxyType)
if proxyType == NoopProxyType ||
proxyType == NoProxyType ||
proxyType == KataProxyType {
t.Fatalf("%s proxy type was not expected", proxyType)
}
} }
func testStringFromProxyType(t *testing.T, proxyType ProxyType, expected string) { func testStringFromProxyType(t *testing.T, proxyType ProxyType, expected string) {
proxyTypeStr := (&proxyType).String() proxyTypeStr := (&proxyType).String()
if proxyTypeStr != expected { assert.Equal(t, proxyTypeStr, expected)
t.Fatalf("Got %s\nExpecting %s", proxyTypeStr, expected)
}
} }
func TestStringFromKataProxyType(t *testing.T) { func TestStringFromKataProxyType(t *testing.T) {
@@ -100,13 +89,9 @@ func TestStringFromUnknownProxyType(t *testing.T) {
func testNewProxyFromProxyType(t *testing.T, proxyType ProxyType, expected proxy) { func testNewProxyFromProxyType(t *testing.T, proxyType ProxyType, expected proxy) {
result, err := newProxy(proxyType) result, err := newProxy(proxyType)
if err != nil { assert := assert.New(t)
t.Fatal(err) assert.NoError(err)
} assert.Exactly(result, expected)
if reflect.DeepEqual(result, expected) == false {
t.Fatalf("Got %+v\nExpecting %+v", result, expected)
}
} }
func TestNewProxyFromKataProxyType(t *testing.T) { func TestNewProxyFromKataProxyType(t *testing.T) {
@@ -135,22 +120,18 @@ func TestNewProxyFromKataBuiltInProxyType(t *testing.T) {
func TestNewProxyFromUnknownProxyType(t *testing.T) { func TestNewProxyFromUnknownProxyType(t *testing.T) {
var proxyType ProxyType var proxyType ProxyType
_, err := newProxy(proxyType) _, err := newProxy(proxyType)
if err != nil { assert.NoError(t, err)
t.Fatal(err)
}
} }
func testNewProxyFromSandboxConfig(t *testing.T, sandboxConfig SandboxConfig) { func testNewProxyFromSandboxConfig(t *testing.T, sandboxConfig SandboxConfig) {
if _, err := newProxy(sandboxConfig.ProxyType); err != nil { assert := assert.New(t)
t.Fatal(err)
}
if err := validateProxyConfig(sandboxConfig.ProxyConfig); err != nil { _, err := newProxy(sandboxConfig.ProxyType)
t.Fatal(err) assert.NoError(err)
}
err = validateProxyConfig(sandboxConfig.ProxyConfig)
assert.NoError(err)
} }
var testProxyPath = "proxy-path" var testProxyPath = "proxy-path"
@@ -169,9 +150,7 @@ func TestNewProxyConfigFromKataProxySandboxConfig(t *testing.T) {
} }
func TestNewProxyConfigNoPathFailure(t *testing.T) { func TestNewProxyConfigNoPathFailure(t *testing.T) {
if err := validateProxyConfig(ProxyConfig{}); err == nil { assert.Error(t, validateProxyConfig(ProxyConfig{}))
t.Fatal("Should fail because ProxyConfig has no Path")
}
} }
const sandboxID = "123456789" const sandboxID = "123456789"
@@ -196,25 +175,17 @@ func testDefaultProxyURL(expectedURL string, socketType string, sandboxID string
func TestDefaultProxyURLUnix(t *testing.T) { func TestDefaultProxyURLUnix(t *testing.T) {
path := filepath.Join(store.SandboxRuntimeRootPath(sandboxID), "proxy.sock") path := filepath.Join(store.SandboxRuntimeRootPath(sandboxID), "proxy.sock")
socketPath := fmt.Sprintf("unix://%s", path) socketPath := fmt.Sprintf("unix://%s", path)
assert.NoError(t, testDefaultProxyURL(socketPath, SocketTypeUNIX, sandboxID))
if err := testDefaultProxyURL(socketPath, SocketTypeUNIX, sandboxID); err != nil {
t.Fatal(err)
}
} }
func TestDefaultProxyURLVSock(t *testing.T) { func TestDefaultProxyURLVSock(t *testing.T) {
if err := testDefaultProxyURL("", SocketTypeVSOCK, sandboxID); err != nil { assert.NoError(t, testDefaultProxyURL("", SocketTypeVSOCK, sandboxID))
t.Fatal(err)
}
} }
func TestDefaultProxyURLUnknown(t *testing.T) { func TestDefaultProxyURLUnknown(t *testing.T) {
path := filepath.Join(store.SandboxRuntimeRootPath(sandboxID), "proxy.sock") path := filepath.Join(store.SandboxRuntimeRootPath(sandboxID), "proxy.sock")
socketPath := fmt.Sprintf("unix://%s", path) socketPath := fmt.Sprintf("unix://%s", path)
assert.Error(t, testDefaultProxyURL(socketPath, "foobar", sandboxID))
if err := testDefaultProxyURL(socketPath, "foobar", sandboxID); err == nil {
t.Fatal()
}
} }
func testProxyStart(t *testing.T, agent agent, proxy proxy) { func testProxyStart(t *testing.T, agent agent, proxy proxy) {

View File

@@ -12,7 +12,6 @@ import (
"io/ioutil" "io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"reflect"
"strings" "strings"
"testing" "testing"
"time" "time"
@@ -42,6 +41,7 @@ func newQemuConfig() HypervisorConfig {
func testQemuKernelParameters(t *testing.T, kernelParams []Param, expected string, debug bool) { func testQemuKernelParameters(t *testing.T, kernelParams []Param, expected string, debug bool) {
qemuConfig := newQemuConfig() qemuConfig := newQemuConfig()
qemuConfig.KernelParams = kernelParams qemuConfig.KernelParams = kernelParams
assert := assert.New(t)
if debug == true { if debug == true {
qemuConfig.Debug = true qemuConfig.Debug = true
@@ -53,9 +53,7 @@ func testQemuKernelParameters(t *testing.T, kernelParams []Param, expected strin
} }
params := q.kernelParameters() params := q.kernelParameters()
if params != expected { assert.Equal(params, expected)
t.Fatalf("Got: %v, Expecting: %v", params, expected)
}
} }
func TestQemuKernelParameters(t *testing.T) { func TestQemuKernelParameters(t *testing.T) {
@@ -78,6 +76,7 @@ func TestQemuKernelParameters(t *testing.T) {
func TestQemuCreateSandbox(t *testing.T) { func TestQemuCreateSandbox(t *testing.T) {
qemuConfig := newQemuConfig() qemuConfig := newQemuConfig()
q := &qemu{} q := &qemu{}
assert := assert.New(t)
sandbox := &Sandbox{ sandbox := &Sandbox{
ctx: context.Background(), ctx: context.Background(),
@@ -88,40 +87,29 @@ func TestQemuCreateSandbox(t *testing.T) {
} }
vcStore, err := store.NewVCSandboxStore(sandbox.ctx, sandbox.id) vcStore, err := store.NewVCSandboxStore(sandbox.ctx, sandbox.id)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
sandbox.store = vcStore sandbox.store = vcStore
// Create the hypervisor fake binary // Create the hypervisor fake binary
testQemuPath := filepath.Join(testDir, testHypervisor) testQemuPath := filepath.Join(testDir, testHypervisor)
_, err = os.Create(testQemuPath) _, err = os.Create(testQemuPath)
if err != nil { assert.NoError(err)
t.Fatalf("Could not create hypervisor file %s: %v", testQemuPath, err)
}
// Create parent dir path for hypervisor.json // Create parent dir path for hypervisor.json
parentDir := store.SandboxConfigurationRootPath(sandbox.id) parentDir := store.SandboxConfigurationRootPath(sandbox.id)
if err := os.MkdirAll(parentDir, store.DirMode); err != nil { assert.NoError(os.MkdirAll(parentDir, store.DirMode))
t.Fatalf("Could not create parent directory %s: %v", parentDir, err)
}
if err := q.createSandbox(context.Background(), sandbox.id, NetworkNamespace{}, &sandbox.config.HypervisorConfig, sandbox.store); err != nil { err = q.createSandbox(context.Background(), sandbox.id, NetworkNamespace{}, &sandbox.config.HypervisorConfig, sandbox.store)
t.Fatal(err) assert.NoError(err)
} assert.NoError(os.RemoveAll(parentDir))
assert.Exactly(qemuConfig, q.config)
if err := os.RemoveAll(parentDir); err != nil {
t.Fatal(err)
}
if reflect.DeepEqual(qemuConfig, q.config) == false {
t.Fatalf("Got %v\nExpecting %v", q.config, qemuConfig)
}
} }
func TestQemuCreateSandboxMissingParentDirFail(t *testing.T) { func TestQemuCreateSandboxMissingParentDirFail(t *testing.T) {
qemuConfig := newQemuConfig() qemuConfig := newQemuConfig()
q := &qemu{} q := &qemu{}
assert := assert.New(t)
sandbox := &Sandbox{ sandbox := &Sandbox{
ctx: context.Background(), ctx: context.Background(),
@@ -132,30 +120,24 @@ func TestQemuCreateSandboxMissingParentDirFail(t *testing.T) {
} }
vcStore, err := store.NewVCSandboxStore(sandbox.ctx, sandbox.id) vcStore, err := store.NewVCSandboxStore(sandbox.ctx, sandbox.id)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
sandbox.store = vcStore sandbox.store = vcStore
// Create the hypervisor fake binary // Create the hypervisor fake binary
testQemuPath := filepath.Join(testDir, testHypervisor) testQemuPath := filepath.Join(testDir, testHypervisor)
_, err = os.Create(testQemuPath) _, err = os.Create(testQemuPath)
if err != nil { assert.NoError(err)
t.Fatalf("Could not create hypervisor file %s: %v", testQemuPath, err)
}
// Ensure parent dir path for hypervisor.json does not exist. // Ensure parent dir path for hypervisor.json does not exist.
parentDir := store.SandboxConfigurationRootPath(sandbox.id) parentDir := store.SandboxConfigurationRootPath(sandbox.id)
if err := os.RemoveAll(parentDir); err != nil { assert.NoError(os.RemoveAll(parentDir))
t.Fatal(err)
}
if err := q.createSandbox(context.Background(), sandbox.id, NetworkNamespace{}, &sandbox.config.HypervisorConfig, sandbox.store); err != nil { err = q.createSandbox(context.Background(), sandbox.id, NetworkNamespace{}, &sandbox.config.HypervisorConfig, sandbox.store)
t.Fatalf("Qemu createSandbox() is not expected to fail because of missing parent directory for storage: %v", err) assert.NoError(err)
}
} }
func TestQemuCPUTopology(t *testing.T) { func TestQemuCPUTopology(t *testing.T) {
assert := assert.New(t)
vcpus := 1 vcpus := 1
q := &qemu{ q := &qemu{
@@ -175,15 +157,13 @@ func TestQemuCPUTopology(t *testing.T) {
} }
smp := q.cpuTopology() smp := q.cpuTopology()
assert.Exactly(smp, expectedOut)
if reflect.DeepEqual(smp, expectedOut) == false {
t.Fatalf("Got %v\nExpecting %v", smp, expectedOut)
}
} }
func TestQemuMemoryTopology(t *testing.T) { func TestQemuMemoryTopology(t *testing.T) {
mem := uint32(1000) mem := uint32(1000)
slots := uint32(8) slots := uint32(8)
assert := assert.New(t)
q := &qemu{ q := &qemu{
arch: &qemuArchBase{}, arch: &qemuArchBase{},
@@ -194,9 +174,7 @@ func TestQemuMemoryTopology(t *testing.T) {
} }
hostMemKb, err := getHostMemorySizeKb(procMemInfo) hostMemKb, err := getHostMemorySizeKb(procMemInfo)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
memMax := fmt.Sprintf("%dM", int(float64(hostMemKb)/1024)) memMax := fmt.Sprintf("%dM", int(float64(hostMemKb)/1024))
expectedOut := govmmQemu.Memory{ expectedOut := govmmQemu.Memory{
@@ -206,29 +184,20 @@ func TestQemuMemoryTopology(t *testing.T) {
} }
memory, err := q.memoryTopology() memory, err := q.memoryTopology()
if err != nil { assert.NoError(err)
t.Fatal(err) assert.Exactly(memory, expectedOut)
}
if reflect.DeepEqual(memory, expectedOut) == false {
t.Fatalf("Got %v\nExpecting %v", memory, expectedOut)
}
} }
func testQemuAddDevice(t *testing.T, devInfo interface{}, devType deviceType, expected []govmmQemu.Device) { func testQemuAddDevice(t *testing.T, devInfo interface{}, devType deviceType, expected []govmmQemu.Device) {
assert := assert.New(t)
q := &qemu{ q := &qemu{
ctx: context.Background(), ctx: context.Background(),
arch: &qemuArchBase{}, arch: &qemuArchBase{},
} }
err := q.addDevice(devInfo, devType) err := q.addDevice(devInfo, devType)
if err != nil { assert.NoError(err)
t.Fatal(err) assert.Exactly(q.qemuConfig.Devices, expected)
}
if reflect.DeepEqual(q.qemuConfig.Devices, expected) == false {
t.Fatalf("Got %v\nExpecting %v", q.qemuConfig.Devices, expected)
}
} }
func TestQemuAddDeviceFsDev(t *testing.T) { func TestQemuAddDeviceFsDev(t *testing.T) {
@@ -315,6 +284,7 @@ func TestQemuAddDeviceKataVSOCK(t *testing.T) {
} }
func TestQemuGetSandboxConsole(t *testing.T) { func TestQemuGetSandboxConsole(t *testing.T) {
assert := assert.New(t)
q := &qemu{ q := &qemu{
ctx: context.Background(), ctx: context.Background(),
} }
@@ -322,25 +292,19 @@ func TestQemuGetSandboxConsole(t *testing.T) {
expected := filepath.Join(store.RunVMStoragePath, sandboxID, consoleSocket) expected := filepath.Join(store.RunVMStoragePath, sandboxID, consoleSocket)
result, err := q.getSandboxConsole(sandboxID) result, err := q.getSandboxConsole(sandboxID)
if err != nil { assert.NoError(err)
t.Fatal(err) assert.Equal(result, expected)
}
if result != expected {
t.Fatalf("Got %s\nExpecting %s", result, expected)
}
} }
func TestQemuCapabilities(t *testing.T) { func TestQemuCapabilities(t *testing.T) {
assert := assert.New(t)
q := &qemu{ q := &qemu{
ctx: context.Background(), ctx: context.Background(),
arch: &qemuArchBase{}, arch: &qemuArchBase{},
} }
caps := q.capabilities() caps := q.capabilities()
if !caps.IsBlockDeviceHotplugSupported() { assert.True(caps.IsBlockDeviceHotplugSupported())
t.Fatal("Block device hotplug should be supported")
}
} }
func TestQemuQemuPath(t *testing.T) { func TestQemuQemuPath(t *testing.T) {
@@ -402,9 +366,7 @@ func TestHotplugUnsupportedDeviceType(t *testing.T) {
} }
vcStore, err := store.NewVCSandboxStore(q.ctx, q.id) vcStore, err := store.NewVCSandboxStore(q.ctx, q.id)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
q.store = vcStore q.store = vcStore
_, err = q.hotplugAddDevice(&memoryDevice{0, 128, uint64(0), false}, fsDev) _, err = q.hotplugAddDevice(&memoryDevice{0, 128, uint64(0), false}, fsDev)
@@ -502,23 +464,21 @@ func TestQemuFileBackedMem(t *testing.T) {
// Check default Filebackedmem location for virtio-fs // Check default Filebackedmem location for virtio-fs
sandbox, err := createQemuSandboxConfig() sandbox, err := createQemuSandboxConfig()
if err != nil { assert.NoError(err)
t.Fatal(err)
}
q := &qemu{} q := &qemu{}
sandbox.config.HypervisorConfig.SharedFS = config.VirtioFS sandbox.config.HypervisorConfig.SharedFS = config.VirtioFS
if err = q.createSandbox(context.Background(), sandbox.id, NetworkNamespace{}, &sandbox.config.HypervisorConfig, sandbox.store); err != nil { err = q.createSandbox(context.Background(), sandbox.id, NetworkNamespace{}, &sandbox.config.HypervisorConfig, sandbox.store)
t.Fatal(err) assert.NoError(err)
}
assert.Equal(q.qemuConfig.Knobs.FileBackedMem, true) assert.Equal(q.qemuConfig.Knobs.FileBackedMem, true)
assert.Equal(q.qemuConfig.Knobs.FileBackedMemShared, true) assert.Equal(q.qemuConfig.Knobs.FileBackedMemShared, true)
assert.Equal(q.qemuConfig.Memory.Path, fallbackFileBackedMemDir) assert.Equal(q.qemuConfig.Memory.Path, fallbackFileBackedMemDir)
// Check failure for VM templating // Check failure for VM templating
sandbox, err = createQemuSandboxConfig() sandbox, err = createQemuSandboxConfig()
if err != nil { assert.NoError(err)
t.Fatal(err)
}
q = &qemu{} q = &qemu{}
sandbox.config.HypervisorConfig.BootToBeTemplate = true sandbox.config.HypervisorConfig.BootToBeTemplate = true
sandbox.config.HypervisorConfig.SharedFS = config.VirtioFS sandbox.config.HypervisorConfig.SharedFS = config.VirtioFS
@@ -531,14 +491,12 @@ func TestQemuFileBackedMem(t *testing.T) {
// Check Setting of non-existent shared-mem path // Check Setting of non-existent shared-mem path
sandbox, err = createQemuSandboxConfig() sandbox, err = createQemuSandboxConfig()
if err != nil { assert.NoError(err)
t.Fatal(err)
}
q = &qemu{} q = &qemu{}
sandbox.config.HypervisorConfig.FileBackedMemRootDir = "/tmp/xyzabc" sandbox.config.HypervisorConfig.FileBackedMemRootDir = "/tmp/xyzabc"
if err = q.createSandbox(context.Background(), sandbox.id, NetworkNamespace{}, &sandbox.config.HypervisorConfig, sandbox.store); err != nil { err = q.createSandbox(context.Background(), sandbox.id, NetworkNamespace{}, &sandbox.config.HypervisorConfig, sandbox.store)
t.Fatal(err) assert.NoError(err)
}
assert.Equal(q.qemuConfig.Knobs.FileBackedMem, false) assert.Equal(q.qemuConfig.Knobs.FileBackedMem, false)
assert.Equal(q.qemuConfig.Knobs.FileBackedMemShared, false) assert.Equal(q.qemuConfig.Knobs.FileBackedMemShared, false)
assert.Equal(q.qemuConfig.Memory.Path, "") assert.Equal(q.qemuConfig.Memory.Path, "")

View File

@@ -14,7 +14,6 @@ import (
"os/exec" "os/exec"
"path" "path"
"path/filepath" "path/filepath"
"reflect"
"sync" "sync"
"syscall" "syscall"
"testing" "testing"
@@ -84,27 +83,20 @@ func testCreateSandbox(t *testing.T, id string,
func TestCreateEmptySandbox(t *testing.T) { func TestCreateEmptySandbox(t *testing.T) {
_, err := testCreateSandbox(t, testSandboxID, MockHypervisor, HypervisorConfig{}, NoopAgentType, NetworkConfig{}, nil, nil) _, err := testCreateSandbox(t, testSandboxID, MockHypervisor, HypervisorConfig{}, NoopAgentType, NetworkConfig{}, nil, nil)
if err == nil { assert.Error(t, err)
t.Fatalf("VirtContainers should not allow empty sandboxes")
}
defer cleanUp() defer cleanUp()
} }
func TestCreateEmptyHypervisorSandbox(t *testing.T) { func TestCreateEmptyHypervisorSandbox(t *testing.T) {
_, err := testCreateSandbox(t, testSandboxID, QemuHypervisor, HypervisorConfig{}, NoopAgentType, NetworkConfig{}, nil, nil) _, err := testCreateSandbox(t, testSandboxID, QemuHypervisor, HypervisorConfig{}, NoopAgentType, NetworkConfig{}, nil, nil)
if err == nil { assert.Error(t, err)
t.Fatalf("VirtContainers should not allow sandboxes with empty hypervisors")
}
defer cleanUp() defer cleanUp()
} }
func TestCreateMockSandbox(t *testing.T) { func TestCreateMockSandbox(t *testing.T) {
hConfig := newHypervisorConfig(nil, nil) hConfig := newHypervisorConfig(nil, nil)
_, err := testCreateSandbox(t, testSandboxID, MockHypervisor, hConfig, NoopAgentType, NetworkConfig{}, nil, nil) _, err := testCreateSandbox(t, testSandboxID, MockHypervisor, hConfig, NoopAgentType, NetworkConfig{}, nil, nil)
if err != nil { assert.NoError(t, err)
t.Fatal(err)
}
defer cleanUp() defer cleanUp()
} }
@@ -132,9 +124,8 @@ func TestCalculateSandboxCPUs(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
sandbox.config.Containers = tt.containers sandbox.config.Containers = tt.containers
if got := sandbox.calculateSandboxCPUs(); got != tt.want { got := sandbox.calculateSandboxCPUs()
t.Errorf("calculateSandboxCPUs() = %v, want %v", got, tt.want) assert.Equal(t, got, tt.want)
}
}) })
} }
} }
@@ -162,20 +153,16 @@ func TestCalculateSandboxMem(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
sandbox.config.Containers = tt.containers sandbox.config.Containers = tt.containers
if got := sandbox.calculateSandboxMemory(); got != tt.want { got := sandbox.calculateSandboxMemory()
t.Errorf("calculateSandboxMemory() = %v, want %v", got, tt.want) assert.Equal(t, got, tt.want)
}
}) })
} }
} }
func TestCreateSandboxEmptyID(t *testing.T) { func TestCreateSandboxEmptyID(t *testing.T) {
hConfig := newHypervisorConfig(nil, nil) hConfig := newHypervisorConfig(nil, nil)
_, err := testCreateSandbox(t, "", MockHypervisor, hConfig, NoopAgentType, NetworkConfig{}, nil, nil)
p, err := testCreateSandbox(t, "", MockHypervisor, hConfig, NoopAgentType, NetworkConfig{}, nil, nil) assert.Error(t, err)
if err == nil {
t.Fatalf("Expected sandbox with empty ID to fail, but got sandbox %v", p)
}
defer cleanUp() defer cleanUp()
} }
@@ -183,9 +170,7 @@ func testSandboxStateTransition(t *testing.T, state types.StateString, newState
hConfig := newHypervisorConfig(nil, nil) hConfig := newHypervisorConfig(nil, nil)
p, err := testCreateSandbox(t, testSandboxID, MockHypervisor, hConfig, NoopAgentType, NetworkConfig{}, nil, nil) p, err := testCreateSandbox(t, testSandboxID, MockHypervisor, hConfig, NoopAgentType, NetworkConfig{}, nil, nil)
if err != nil { assert.NoError(t, err)
return err
}
defer cleanUp() defer cleanUp()
p.state = types.SandboxState{ p.state = types.SandboxState{
@@ -197,51 +182,37 @@ func testSandboxStateTransition(t *testing.T, state types.StateString, newState
func TestSandboxStateReadyRunning(t *testing.T) { func TestSandboxStateReadyRunning(t *testing.T) {
err := testSandboxStateTransition(t, types.StateReady, types.StateRunning) err := testSandboxStateTransition(t, types.StateReady, types.StateRunning)
if err != nil { assert.NoError(t, err)
t.Fatal(err)
}
} }
func TestSandboxStateRunningPaused(t *testing.T) { func TestSandboxStateRunningPaused(t *testing.T) {
err := testSandboxStateTransition(t, types.StateRunning, types.StatePaused) err := testSandboxStateTransition(t, types.StateRunning, types.StatePaused)
if err != nil { assert.NoError(t, err)
t.Fatal(err)
}
} }
func TestSandboxStatePausedRunning(t *testing.T) { func TestSandboxStatePausedRunning(t *testing.T) {
err := testSandboxStateTransition(t, types.StatePaused, types.StateRunning) err := testSandboxStateTransition(t, types.StatePaused, types.StateRunning)
if err != nil { assert.NoError(t, err)
t.Fatal(err)
}
} }
func TestSandboxStatePausedStopped(t *testing.T) { func TestSandboxStatePausedStopped(t *testing.T) {
err := testSandboxStateTransition(t, types.StatePaused, types.StateStopped) err := testSandboxStateTransition(t, types.StatePaused, types.StateStopped)
if err != nil { assert.NoError(t, err)
t.Fatal(err)
}
} }
func TestSandboxStateRunningStopped(t *testing.T) { func TestSandboxStateRunningStopped(t *testing.T) {
err := testSandboxStateTransition(t, types.StateRunning, types.StateStopped) err := testSandboxStateTransition(t, types.StateRunning, types.StateStopped)
if err != nil { assert.NoError(t, err)
t.Fatal(err)
}
} }
func TestSandboxStateReadyPaused(t *testing.T) { func TestSandboxStateReadyPaused(t *testing.T) {
err := testSandboxStateTransition(t, types.StateReady, types.StateStopped) err := testSandboxStateTransition(t, types.StateReady, types.StateStopped)
if err != nil { assert.NoError(t, err)
t.Fatal(err)
}
} }
func TestSandboxStatePausedReady(t *testing.T) { func TestSandboxStatePausedReady(t *testing.T) {
err := testSandboxStateTransition(t, types.StateStopped, types.StateReady) err := testSandboxStateTransition(t, types.StateStopped, types.StateReady)
if err == nil { assert.Error(t, err)
t.Fatal("Invalid transition from Ready to Paused")
}
} }
func testStateValid(t *testing.T, stateStr types.StateString, expected bool) { func testStateValid(t *testing.T, stateStr types.StateString, expected bool) {
@@ -250,9 +221,7 @@ func testStateValid(t *testing.T, stateStr types.StateString, expected bool) {
} }
ok := state.Valid() ok := state.Valid()
if ok != expected { assert.Equal(t, ok, expected)
t.Fatal()
}
} }
func TestStateValidSuccessful(t *testing.T) { func TestStateValidSuccessful(t *testing.T) {
@@ -272,9 +241,7 @@ func TestValidTransitionFailingOldStateMismatch(t *testing.T) {
} }
err := state.ValidTransition(types.StateRunning, types.StateStopped) err := state.ValidTransition(types.StateRunning, types.StateStopped)
if err == nil { assert.Error(t, err)
t.Fatal()
}
} }
func TestVolumesSetSuccessful(t *testing.T) { func TestVolumesSetSuccessful(t *testing.T) {
@@ -294,13 +261,8 @@ func TestVolumesSetSuccessful(t *testing.T) {
} }
err := volumes.Set(volStr) err := volumes.Set(volStr)
if err != nil { assert.NoError(t, err)
t.Fatal(err) assert.Exactly(t, *volumes, expected)
}
if reflect.DeepEqual(*volumes, expected) == false {
t.Fatal()
}
} }
func TestVolumesSetFailingTooFewArguments(t *testing.T) { func TestVolumesSetFailingTooFewArguments(t *testing.T) {
@@ -309,9 +271,7 @@ func TestVolumesSetFailingTooFewArguments(t *testing.T) {
volStr := "mountTag1 mountTag2" volStr := "mountTag1 mountTag2"
err := volumes.Set(volStr) err := volumes.Set(volStr)
if err == nil { assert.Error(t, err)
t.Fatal()
}
} }
func TestVolumesSetFailingTooManyArguments(t *testing.T) { func TestVolumesSetFailingTooManyArguments(t *testing.T) {
@@ -320,9 +280,7 @@ func TestVolumesSetFailingTooManyArguments(t *testing.T) {
volStr := "mountTag1:hostPath1:Foo1 mountTag2:hostPath2:Foo2" volStr := "mountTag1:hostPath1:Foo1 mountTag2:hostPath2:Foo2"
err := volumes.Set(volStr) err := volumes.Set(volStr)
if err == nil { assert.Error(t, err)
t.Fatal()
}
} }
func TestVolumesSetFailingVoidArguments(t *testing.T) { func TestVolumesSetFailingVoidArguments(t *testing.T) {
@@ -331,9 +289,7 @@ func TestVolumesSetFailingVoidArguments(t *testing.T) {
volStr := ": : :" volStr := ": : :"
err := volumes.Set(volStr) err := volumes.Set(volStr)
if err == nil { assert.Error(t, err)
t.Fatal()
}
} }
func TestVolumesStringSuccessful(t *testing.T) { func TestVolumesStringSuccessful(t *testing.T) {
@@ -351,9 +307,7 @@ func TestVolumesStringSuccessful(t *testing.T) {
expected := "mountTag1:hostPath1 mountTag2:hostPath2" expected := "mountTag1:hostPath1 mountTag2:hostPath2"
result := volumes.String() result := volumes.String()
if result != expected { assert.Equal(t, result, expected)
t.Fatal()
}
} }
func TestSocketsSetSuccessful(t *testing.T) { func TestSocketsSetSuccessful(t *testing.T) {
@@ -377,13 +331,8 @@ func TestSocketsSetSuccessful(t *testing.T) {
} }
err := sockets.Set(sockStr) err := sockets.Set(sockStr)
if err != nil { assert.NoError(t, err)
t.Fatal(err) assert.Exactly(t, *sockets, expected)
}
if reflect.DeepEqual(*sockets, expected) == false {
t.Fatal()
}
} }
func TestSocketsSetFailingWrongArgsAmount(t *testing.T) { func TestSocketsSetFailingWrongArgsAmount(t *testing.T) {
@@ -392,9 +341,7 @@ func TestSocketsSetFailingWrongArgsAmount(t *testing.T) {
sockStr := "devID1:id1:hostPath1" sockStr := "devID1:id1:hostPath1"
err := sockets.Set(sockStr) err := sockets.Set(sockStr)
if err == nil { assert.Error(t, err)
t.Fatal()
}
} }
func TestSocketsSetFailingVoidArguments(t *testing.T) { func TestSocketsSetFailingVoidArguments(t *testing.T) {
@@ -403,9 +350,7 @@ func TestSocketsSetFailingVoidArguments(t *testing.T) {
sockStr := ":::" sockStr := ":::"
err := sockets.Set(sockStr) err := sockets.Set(sockStr)
if err == nil { assert.Error(t, err)
t.Fatal()
}
} }
func TestSocketsStringSuccessful(t *testing.T) { func TestSocketsStringSuccessful(t *testing.T) {
@@ -427,27 +372,22 @@ func TestSocketsStringSuccessful(t *testing.T) {
expected := "devID1:id1:hostPath1:Name1 devID2:id2:hostPath2:Name2" expected := "devID1:id1:hostPath1:Name1 devID2:id2:hostPath2:Name2"
result := sockets.String() result := sockets.String()
if result != expected { assert.Equal(t, result, expected)
t.Fatal()
}
} }
func TestSandboxListSuccessful(t *testing.T) { func TestSandboxListSuccessful(t *testing.T) {
sandbox := &Sandbox{} sandbox := &Sandbox{}
sandboxList, err := sandbox.list() sandboxList, err := sandbox.list()
if sandboxList != nil || err != nil { assert.NoError(t, err)
t.Fatal() assert.Nil(t, sandboxList)
}
} }
func TestSandboxEnterSuccessful(t *testing.T) { func TestSandboxEnterSuccessful(t *testing.T) {
sandbox := &Sandbox{} sandbox := &Sandbox{}
err := sandbox.enter([]string{}) err := sandbox.enter([]string{})
if err != nil { assert.NoError(t, err)
t.Fatal(err)
}
} }
func testCheckInitSandboxAndContainerStates(p *Sandbox, initialSandboxState types.SandboxState, c *Container, initialContainerState types.ContainerState) error { func testCheckInitSandboxAndContainerStates(p *Sandbox, initialSandboxState types.SandboxState, c *Container, initialContainerState types.ContainerState) error {
@@ -464,10 +404,8 @@ func testCheckInitSandboxAndContainerStates(p *Sandbox, initialSandboxState type
func testForceSandboxStateChangeAndCheck(t *testing.T, p *Sandbox, newSandboxState types.SandboxState) error { func testForceSandboxStateChangeAndCheck(t *testing.T, p *Sandbox, newSandboxState types.SandboxState) error {
// force sandbox state change // force sandbox state change
if err := p.setSandboxState(newSandboxState.State); err != nil { err := p.setSandboxState(newSandboxState.State)
t.Fatalf("Unexpected error: %v (sandbox %+v)", err, p) assert.NoError(t, err)
}
// check the in-memory state is correct // check the in-memory state is correct
if p.state.State != newSandboxState.State { if p.state.State != newSandboxState.State {
return fmt.Errorf("Expected state %v, got %v", newSandboxState.State, p.state.State) return fmt.Errorf("Expected state %v, got %v", newSandboxState.State, p.state.State)
@@ -478,9 +416,8 @@ func testForceSandboxStateChangeAndCheck(t *testing.T, p *Sandbox, newSandboxSta
func testForceContainerStateChangeAndCheck(t *testing.T, p *Sandbox, c *Container, newContainerState types.ContainerState) error { func testForceContainerStateChangeAndCheck(t *testing.T, p *Sandbox, c *Container, newContainerState types.ContainerState) error {
// force container state change // force container state change
if err := c.setContainerState(newContainerState.State); err != nil { err := c.setContainerState(newContainerState.State)
t.Fatalf("Unexpected error: %v (sandbox %+v)", err, p) assert.NoError(t, err)
}
// check the in-memory state is correct // check the in-memory state is correct
if c.state.State != newContainerState.State { if c.state.State != newContainerState.State {
@@ -512,18 +449,15 @@ func TestSandboxSetSandboxAndContainerState(t *testing.T) {
contID := "505" contID := "505"
contConfig := newTestContainerConfigNoop(contID) contConfig := newTestContainerConfigNoop(contID)
hConfig := newHypervisorConfig(nil, nil) hConfig := newHypervisorConfig(nil, nil)
assert := assert.New(t)
// create a sandbox // create a sandbox
p, err := testCreateSandbox(t, testSandboxID, MockHypervisor, hConfig, NoopAgentType, NetworkConfig{}, []ContainerConfig{contConfig}, nil) p, err := testCreateSandbox(t, testSandboxID, MockHypervisor, hConfig, NoopAgentType, NetworkConfig{}, []ContainerConfig{contConfig}, nil)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer cleanUp() defer cleanUp()
l := len(p.GetAllContainers()) l := len(p.GetAllContainers())
if l != 1 { assert.Equal(l, 1)
t.Fatalf("Expected 1 container found %v", l)
}
initialSandboxState := types.SandboxState{ initialSandboxState := types.SandboxState{
State: types.StateReady, State: types.StateReady,
@@ -535,9 +469,7 @@ func TestSandboxSetSandboxAndContainerState(t *testing.T) {
} }
c, err := p.findContainer(contID) c, err := p.findContainer(contID)
if err != nil { assert.NoError(err)
t.Fatalf("Failed to retrieve container %v: %v", contID, err)
}
// check initial sandbox and container states // check initial sandbox and container states
if err := testCheckInitSandboxAndContainerStates(p, initialSandboxState, c, initialContainerState); err != nil { if err := testCheckInitSandboxAndContainerStates(p, initialSandboxState, c, initialContainerState); err != nil {
@@ -546,9 +478,7 @@ func TestSandboxSetSandboxAndContainerState(t *testing.T) {
// persist to disk // persist to disk
err = p.storeSandbox() err = p.storeSandbox()
if err != nil { assert.NoError(err)
t.Fatal(err)
}
newSandboxState := types.SandboxState{ newSandboxState := types.SandboxState{
State: types.StateRunning, State: types.StateRunning,
@@ -568,18 +498,14 @@ func TestSandboxSetSandboxAndContainerState(t *testing.T) {
// force state to be read from disk // force state to be read from disk
p2, err := fetchSandbox(context.Background(), p.ID()) p2, err := fetchSandbox(context.Background(), p.ID())
if err != nil { assert.NoError(err)
t.Fatalf("Failed to fetch sandbox %v: %v", p.ID(), err)
}
if err := testCheckSandboxOnDiskState(p2, newSandboxState); err != nil { if err := testCheckSandboxOnDiskState(p2, newSandboxState); err != nil {
t.Error(err) t.Error(err)
} }
c2, err := p2.findContainer(contID) c2, err := p2.findContainer(contID)
if err != nil { assert.NoError(err)
t.Fatalf("Failed to find container %v: %v", contID, err)
}
if err := testCheckContainerOnDiskState(c2, newContainerState); err != nil { if err := testCheckContainerOnDiskState(c2, newContainerState); err != nil {
t.Error(err) t.Error(err)
@@ -587,15 +513,11 @@ func TestSandboxSetSandboxAndContainerState(t *testing.T) {
// revert sandbox state to allow it to be deleted // revert sandbox state to allow it to be deleted
err = p.setSandboxState(initialSandboxState.State) err = p.setSandboxState(initialSandboxState.State)
if err != nil { assert.NoError(err)
t.Fatalf("Unexpected error: %v (sandbox %+v)", err, p)
}
// clean up // clean up
err = p.Delete() err = p.Delete()
if err != nil { assert.NoError(err)
t.Fatal(err)
}
} }
func TestGetContainer(t *testing.T) { func TestGetContainer(t *testing.T) {
@@ -612,15 +534,11 @@ func TestGetContainer(t *testing.T) {
} }
c := sandbox.GetContainer("noid") c := sandbox.GetContainer("noid")
if c != nil { assert.Nil(t, c)
t.Fatal()
}
for _, id := range containerIDs { for _, id := range containerIDs {
c = sandbox.GetContainer(id) c = sandbox.GetContainer(id)
if c == nil { assert.NotNil(t, c)
t.Fatal()
}
} }
} }
@@ -640,13 +558,12 @@ func TestGetAllContainers(t *testing.T) {
list := sandbox.GetAllContainers() list := sandbox.GetAllContainers()
for _, c := range list { for _, c := range list {
if containers[c.ID()] == nil { assert.NotNil(t, containers[c.ID()], nil)
t.Fatal()
}
} }
} }
func TestSetAnnotations(t *testing.T) { func TestSetAnnotations(t *testing.T) {
assert := assert.New(t)
sandbox := Sandbox{ sandbox := Sandbox{
ctx: context.Background(), ctx: context.Background(),
id: "abcxyz123", id: "abcxyz123",
@@ -659,9 +576,8 @@ func TestSetAnnotations(t *testing.T) {
} }
vcStore, err := store.NewVCSandboxStore(sandbox.ctx, sandbox.id) vcStore, err := store.NewVCSandboxStore(sandbox.ctx, sandbox.id)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
sandbox.store = vcStore sandbox.store = vcStore
keyAnnotation := "annotation2" keyAnnotation := "annotation2"
@@ -674,13 +590,8 @@ func TestSetAnnotations(t *testing.T) {
sandbox.SetAnnotations(newAnnotations) sandbox.SetAnnotations(newAnnotations)
v, err := sandbox.Annotations(keyAnnotation) v, err := sandbox.Annotations(keyAnnotation)
if err != nil { assert.NoError(err)
t.Fatal() assert.Equal(v, valueAnnotation)
}
if v != valueAnnotation {
t.Fatal()
}
//Change the value of an annotation //Change the value of an annotation
valueAnnotation = "123" valueAnnotation = "123"
@@ -689,69 +600,50 @@ func TestSetAnnotations(t *testing.T) {
sandbox.SetAnnotations(newAnnotations) sandbox.SetAnnotations(newAnnotations)
v, err = sandbox.Annotations(keyAnnotation) v, err = sandbox.Annotations(keyAnnotation)
if err != nil { assert.NoError(err)
t.Fatal() assert.Equal(v, valueAnnotation)
}
if v != valueAnnotation {
t.Fatal()
}
} }
func TestSandboxGetContainer(t *testing.T) { func TestSandboxGetContainer(t *testing.T) {
assert := assert.New(t)
emptySandbox := Sandbox{} emptySandbox := Sandbox{}
_, err := emptySandbox.findContainer("") _, err := emptySandbox.findContainer("")
if err == nil { assert.Error(err)
t.Fatal("Expected error for containerless sandbox")
}
_, err = emptySandbox.findContainer("foo") _, err = emptySandbox.findContainer("foo")
if err == nil { assert.Error(err)
t.Fatal("Expected error for containerless sandbox and invalid containerID")
}
hConfig := newHypervisorConfig(nil, nil) hConfig := newHypervisorConfig(nil, nil)
p, err := testCreateSandbox(t, testSandboxID, MockHypervisor, hConfig, NoopAgentType, NetworkConfig{}, nil, nil) p, err := testCreateSandbox(t, testSandboxID, MockHypervisor, hConfig, NoopAgentType, NetworkConfig{}, nil, nil)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer cleanUp() defer cleanUp()
contID := "999" contID := "999"
contConfig := newTestContainerConfigNoop(contID) contConfig := newTestContainerConfigNoop(contID)
nc, err := newContainer(p, contConfig) nc, err := newContainer(p, contConfig)
if err != nil { assert.NoError(err)
t.Fatalf("Failed to create container %+v in sandbox %+v: %v", contConfig, p, err)
}
if err := p.addContainer(nc); err != nil { err = p.addContainer(nc)
t.Fatalf("Could not add container to sandbox %v", err) assert.NoError(err)
}
got := false got := false
for _, c := range p.GetAllContainers() { for _, c := range p.GetAllContainers() {
c2, err := p.findContainer(c.ID()) c2, err := p.findContainer(c.ID())
if err != nil { assert.NoError(err)
t.Fatalf("Failed to find container %v: %v", c.ID(), err) assert.Equal(c2.ID(), c.ID())
}
if c2.ID() != c.ID() {
t.Fatalf("Expected container %v but got %v", c.ID(), c2.ID())
}
if c2.ID() == contID { if c2.ID() == contID {
got = true got = true
} }
} }
if !got { assert.True(got)
t.Fatalf("Failed to find container %v", contID)
}
} }
func TestContainerStateSetFstype(t *testing.T) { func TestContainerStateSetFstype(t *testing.T) {
var err error var err error
assert := assert.New(t)
containers := []ContainerConfig{ containers := []ContainerConfig{
{ {
@@ -762,33 +654,29 @@ func TestContainerStateSetFstype(t *testing.T) {
hConfig := newHypervisorConfig(nil, nil) hConfig := newHypervisorConfig(nil, nil)
sandbox, err := testCreateSandbox(t, testSandboxID, MockHypervisor, hConfig, NoopAgentType, NetworkConfig{}, containers, nil) sandbox, err := testCreateSandbox(t, testSandboxID, MockHypervisor, hConfig, NoopAgentType, NetworkConfig{}, containers, nil)
assert.Nil(t, err) assert.Nil(err)
defer cleanUp() defer cleanUp()
vcStore, err := store.NewVCSandboxStore(sandbox.ctx, sandbox.id) vcStore, err := store.NewVCSandboxStore(sandbox.ctx, sandbox.id)
assert.Nil(t, err) assert.Nil(err)
sandbox.store = vcStore sandbox.store = vcStore
c := sandbox.GetContainer("100") c := sandbox.GetContainer("100")
if c == nil { assert.NotNil(c)
t.Fatal()
}
cImpl, ok := c.(*Container) cImpl, ok := c.(*Container)
assert.True(t, ok) assert.True(ok)
containerStore, err := store.NewVCContainerStore(sandbox.ctx, sandbox.id, c.ID()) containerStore, err := store.NewVCContainerStore(sandbox.ctx, sandbox.id, c.ID())
if err != nil { assert.NoError(err)
t.Fatal(err)
}
cImpl.store = containerStore cImpl.store = containerStore
path := store.ContainerRuntimeRootPath(testSandboxID, c.ID()) path := store.ContainerRuntimeRootPath(testSandboxID, c.ID())
stateFilePath := filepath.Join(path, store.StateFile) stateFilePath := filepath.Join(path, store.StateFile)
f, err := os.Create(stateFilePath) f, err := os.Create(stateFilePath)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
state := types.ContainerState{ state := types.ContainerState{
State: "ready", State: "ready",
@@ -803,25 +691,17 @@ func TestContainerStateSetFstype(t *testing.T) {
}` }`
n, err := f.WriteString(stateData) n, err := f.WriteString(stateData)
if err != nil || n != len(stateData) { defer f.Close()
f.Close() assert.NoError(err)
t.Fatal() assert.Equal(n, len(stateData))
}
f.Close()
newFstype := "ext4" newFstype := "ext4"
if err := cImpl.setStateFstype(newFstype); err != nil { err = cImpl.setStateFstype(newFstype)
t.Fatal(err) assert.NoError(err)
} assert.Equal(cImpl.state.Fstype, newFstype)
if cImpl.state.Fstype != newFstype {
t.Fatal()
}
fileData, err := ioutil.ReadFile(stateFilePath) fileData, err := ioutil.ReadFile(stateFilePath)
if err != nil { assert.NoError(err)
t.Fatal()
}
// experimental features doesn't write state.json // experimental features doesn't write state.json
if sandbox.supportNewStore() { if sandbox.supportNewStore() {
@@ -830,17 +710,9 @@ func TestContainerStateSetFstype(t *testing.T) {
var res types.ContainerState var res types.ContainerState
err = json.Unmarshal([]byte(string(fileData)), &res) err = json.Unmarshal([]byte(string(fileData)), &res)
if err != nil { assert.NoError(err)
t.Fatal(err) assert.Equal(res.Fstype, newFstype)
} assert.Equal(res.State, state.State)
if res.Fstype != newFstype {
t.Fatal()
}
if res.State != state.State {
t.Fatal()
}
} }
const vfioPath = "/dev/vfio/" const vfioPath = "/dev/vfio/"
@@ -1299,9 +1171,7 @@ func TestAttachBlockDevice(t *testing.T) {
// create state file // create state file
path := store.ContainerRuntimeRootPath(testSandboxID, container.ID()) path := store.ContainerRuntimeRootPath(testSandboxID, container.ID())
err = os.MkdirAll(path, store.DirMode) err = os.MkdirAll(path, store.DirMode)
if err != nil { assert.NoError(t, err)
t.Fatal(err)
}
defer os.RemoveAll(path) defer os.RemoveAll(path)
@@ -1309,9 +1179,7 @@ func TestAttachBlockDevice(t *testing.T) {
os.Remove(stateFilePath) os.Remove(stateFilePath)
_, err = os.Create(stateFilePath) _, err = os.Create(stateFilePath)
if err != nil { assert.NoError(t, err)
t.Fatal(err)
}
defer os.Remove(stateFilePath) defer os.Remove(stateFilePath)
path = "/dev/hda" path = "/dev/hda"
@@ -1396,9 +1264,7 @@ func TestPreAddDevice(t *testing.T) {
// create state file // create state file
path := store.ContainerRuntimeRootPath(testSandboxID, container.ID()) path := store.ContainerRuntimeRootPath(testSandboxID, container.ID())
err = os.MkdirAll(path, store.DirMode) err = os.MkdirAll(path, store.DirMode)
if err != nil { assert.NoError(t, err)
t.Fatal(err)
}
defer os.RemoveAll(path) defer os.RemoveAll(path)
@@ -1406,9 +1272,7 @@ func TestPreAddDevice(t *testing.T) {
os.Remove(stateFilePath) os.Remove(stateFilePath)
_, err = os.Create(stateFilePath) _, err = os.Create(stateFilePath)
if err != nil { assert.NoError(t, err)
t.Fatal(err)
}
defer os.Remove(stateFilePath) defer os.Remove(stateFilePath)
path = "/dev/hda" path = "/dev/hda"
@@ -1559,14 +1423,10 @@ func TestSandboxUpdateResources(t *testing.T) {
[]ContainerConfig{contConfig1, contConfig2}, []ContainerConfig{contConfig1, contConfig2},
nil) nil)
if err != nil { assert.NoError(t, err)
t.Fatal(err)
}
err = s.updateResources() err = s.updateResources()
if err != nil { assert.NoError(t, err)
t.Fatal(err)
}
containerMemLimit := int64(1000) containerMemLimit := int64(1000)
containerCPUPeriod := uint64(1000) containerCPUPeriod := uint64(1000)
containerCPUQouta := int64(5) containerCPUQouta := int64(5)
@@ -1583,9 +1443,7 @@ func TestSandboxUpdateResources(t *testing.T) {
c.Resources.CPU.Quota = &containerCPUQouta c.Resources.CPU.Quota = &containerCPUQouta
} }
err = s.updateResources() err = s.updateResources()
if err != nil { assert.NoError(t, err)
t.Fatal(err)
}
} }
func TestSandboxExperimentalFeature(t *testing.T) { func TestSandboxExperimentalFeature(t *testing.T) {

View File

@@ -7,9 +7,10 @@ package virtcontainers
import ( import (
"os/exec" "os/exec"
"reflect"
"syscall" "syscall"
"testing" "testing"
"github.com/stretchr/testify/assert"
) )
const ( const (
@@ -18,15 +19,11 @@ const (
func testSetShimType(t *testing.T, value string, expected ShimType) { func testSetShimType(t *testing.T, value string, expected ShimType) {
var shimType ShimType var shimType ShimType
assert := assert.New(t)
err := (&shimType).Set(value) err := (&shimType).Set(value)
if err != nil { assert.NoError(err)
t.Fatal(err) assert.Equal(shimType, expected)
}
if shimType != expected {
t.Fatalf("Got %s\nExpecting %s", shimType, expected)
}
} }
func TestSetKataShimType(t *testing.T) { func TestSetKataShimType(t *testing.T) {
@@ -39,24 +36,19 @@ func TestSetNoopShimType(t *testing.T) {
func TestSetUnknownShimType(t *testing.T) { func TestSetUnknownShimType(t *testing.T) {
var shimType ShimType var shimType ShimType
assert := assert.New(t)
unknownType := "unknown" unknownType := "unknown"
err := (&shimType).Set(unknownType) err := (&shimType).Set(unknownType)
if err == nil { assert.Error(err)
t.Fatalf("Should fail because %s type used", unknownType) assert.NotEqual(shimType, NoopShimType)
}
if shimType == NoopShimType {
t.Fatalf("%s shim type was not expected", shimType)
}
} }
func testStringFromShimType(t *testing.T, shimType ShimType, expected string) { func testStringFromShimType(t *testing.T, shimType ShimType, expected string) {
shimTypeStr := (&shimType).String() shimTypeStr := (&shimType).String()
if shimTypeStr != expected { assert := assert.New(t)
t.Fatalf("Got %s\nExpecting %s", shimTypeStr, expected) assert.Equal(shimTypeStr, expected)
}
} }
func TestStringFromKataShimType(t *testing.T) { func TestStringFromKataShimType(t *testing.T) {
@@ -80,14 +72,10 @@ func TestStringFromUnknownShimType(t *testing.T) {
} }
func testNewShimFromShimType(t *testing.T, shimType ShimType, expected shim) { func testNewShimFromShimType(t *testing.T, shimType ShimType, expected shim) {
assert := assert.New(t)
result, err := newShim(shimType) result, err := newShim(shimType)
if err != nil { assert.NoError(err)
t.Fatal(err) assert.Exactly(result, expected)
}
if reflect.DeepEqual(result, expected) == false {
t.Fatalf("Got %+v\nExpecting %+v", result, expected)
}
} }
func TestNewShimFromKataShimType(t *testing.T) { func TestNewShimFromKataShimType(t *testing.T) {
@@ -110,19 +98,16 @@ func TestNewShimFromKataBuiltInShimType(t *testing.T) {
func TestNewShimFromUnknownShimType(t *testing.T) { func TestNewShimFromUnknownShimType(t *testing.T) {
var shimType ShimType var shimType ShimType
assert := assert.New(t)
_, err := newShim(shimType) _, err := newShim(shimType)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
} }
func testNewShimConfigFromSandboxConfig(t *testing.T, sandboxConfig SandboxConfig, expected interface{}) { func testNewShimConfigFromSandboxConfig(t *testing.T, sandboxConfig SandboxConfig, expected interface{}) {
assert := assert.New(t)
result := newShimConfig(sandboxConfig) result := newShimConfig(sandboxConfig)
assert.Exactly(result, expected)
if reflect.DeepEqual(result, expected) == false {
t.Fatalf("Got %+v\nExpecting %+v", result, expected)
}
} }
func TestNewShimConfigFromKataShimSandboxConfig(t *testing.T) { func TestNewShimConfigFromKataShimSandboxConfig(t *testing.T) {
@@ -163,64 +148,51 @@ func TestNewShimConfigFromUnknownShimSandboxConfig(t *testing.T) {
} }
func testRunSleep0AndGetPid(t *testing.T) int { func testRunSleep0AndGetPid(t *testing.T) int {
assert := assert.New(t)
binPath, err := exec.LookPath(testRunningProcess) binPath, err := exec.LookPath(testRunningProcess)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
cmd := exec.Command(binPath, "0") cmd := exec.Command(binPath, "0")
if err := cmd.Start(); err != nil { err = cmd.Start()
t.Fatal(err) assert.NoError(err)
}
pid := cmd.Process.Pid pid := cmd.Process.Pid
err = cmd.Wait()
if err := cmd.Wait(); err != nil { assert.NoError(err)
t.Fatal(err)
}
return pid return pid
} }
func testRunSleep999AndGetCmd(t *testing.T) *exec.Cmd { func testRunSleep999AndGetCmd(t *testing.T) *exec.Cmd {
assert := assert.New(t)
binPath, err := exec.LookPath(testRunningProcess) binPath, err := exec.LookPath(testRunningProcess)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
cmd := exec.Command(binPath, "999") cmd := exec.Command(binPath, "999")
if err := cmd.Start(); err != nil { err = cmd.Start()
t.Fatal(err) assert.NoError(err)
}
return cmd return cmd
} }
func TestStopShimSuccessfulProcessNotRunning(t *testing.T) { func TestStopShimSuccessfulProcessNotRunning(t *testing.T) {
assert := assert.New(t)
pid := testRunSleep0AndGetPid(t) pid := testRunSleep0AndGetPid(t)
assert.NoError(stopShim(pid))
if err := stopShim(pid); err != nil {
t.Fatal(err)
}
} }
func TestStopShimSuccessfulProcessRunning(t *testing.T) { func TestStopShimSuccessfulProcessRunning(t *testing.T) {
assert := assert.New(t)
cmd := testRunSleep999AndGetCmd(t) cmd := testRunSleep999AndGetCmd(t)
assert.NoError(stopShim(cmd.Process.Pid))
if err := stopShim(cmd.Process.Pid); err != nil {
t.Fatal(err)
}
} }
func testIsShimRunning(t *testing.T, pid int, expected bool) { func testIsShimRunning(t *testing.T, pid int, expected bool) {
assert := assert.New(t)
running, err := isShimRunning(pid) running, err := isShimRunning(pid)
if err != nil { assert.NoError(err)
t.Fatal(err) assert.Equal(running, expected)
}
if running != expected {
t.Fatalf("Expecting running=%t, Got running=%t", expected, running)
}
} }
func TestIsShimRunningFalse(t *testing.T) { func TestIsShimRunningFalse(t *testing.T) {
@@ -231,41 +203,35 @@ func TestIsShimRunningFalse(t *testing.T) {
func TestIsShimRunningTrue(t *testing.T) { func TestIsShimRunningTrue(t *testing.T) {
cmd := testRunSleep999AndGetCmd(t) cmd := testRunSleep999AndGetCmd(t)
assert := assert.New(t)
testIsShimRunning(t, cmd.Process.Pid, true) testIsShimRunning(t, cmd.Process.Pid, true)
if err := syscall.Kill(cmd.Process.Pid, syscall.SIGKILL); err != nil { err := syscall.Kill(cmd.Process.Pid, syscall.SIGKILL)
t.Fatal(err) assert.NoError(err)
}
} }
func TestWaitForShimInvalidPidSuccessful(t *testing.T) { func TestWaitForShimInvalidPidSuccessful(t *testing.T) {
wrongValuesList := []int{0, -1, -100} wrongValuesList := []int{0, -1, -100}
assert := assert.New(t)
for _, val := range wrongValuesList { for _, val := range wrongValuesList {
if err := waitForShim(val); err != nil { err := waitForShim(val)
t.Fatal(err) assert.NoError(err)
}
} }
} }
func TestWaitForShimNotRunningSuccessful(t *testing.T) { func TestWaitForShimNotRunningSuccessful(t *testing.T) {
pid := testRunSleep0AndGetPid(t) pid := testRunSleep0AndGetPid(t)
assert := assert.New(t)
if err := waitForShim(pid); err != nil { assert.NoError(waitForShim(pid))
t.Fatal(err)
}
} }
func TestWaitForShimRunningForTooLongFailure(t *testing.T) { func TestWaitForShimRunningForTooLongFailure(t *testing.T) {
cmd := testRunSleep999AndGetCmd(t) cmd := testRunSleep999AndGetCmd(t)
assert := assert.New(t)
waitForShimTimeout = 0.1 waitForShimTimeout = 0.1
if err := waitForShim(cmd.Process.Pid); err == nil { assert.Error(waitForShim(cmd.Process.Pid))
t.Fatal(err) assert.NoError(syscall.Kill(cmd.Process.Pid, syscall.SIGKILL))
}
if err := syscall.Kill(cmd.Process.Pid, syscall.SIGKILL); err != nil {
t.Fatal(err)
}
} }

View File

@@ -14,6 +14,7 @@ import (
"testing" "testing"
ktu "github.com/kata-containers/runtime/pkg/katatestutils" ktu "github.com/kata-containers/runtime/pkg/katatestutils"
"github.com/stretchr/testify/assert"
) )
func TestBindMountInvalidSourceSymlink(t *testing.T) { func TestBindMountInvalidSourceSymlink(t *testing.T) {
@@ -21,9 +22,7 @@ func TestBindMountInvalidSourceSymlink(t *testing.T) {
os.Remove(source) os.Remove(source)
err := bindMount(context.Background(), source, "", false) err := bindMount(context.Background(), source, "", false)
if err == nil { assert.Error(t, err)
t.Fatal()
}
} }
func TestBindMountFailingMount(t *testing.T) { func TestBindMountFailingMount(t *testing.T) {
@@ -31,24 +30,20 @@ func TestBindMountFailingMount(t *testing.T) {
fakeSource := filepath.Join(testDir, "fooFile") fakeSource := filepath.Join(testDir, "fooFile")
os.Remove(source) os.Remove(source)
os.Remove(fakeSource) os.Remove(fakeSource)
assert := assert.New(t)
_, err := os.OpenFile(fakeSource, os.O_CREATE, mountPerm) _, err := os.OpenFile(fakeSource, os.O_CREATE, mountPerm)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
err = os.Symlink(fakeSource, source) err = os.Symlink(fakeSource, source)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
err = bindMount(context.Background(), source, "", false) err = bindMount(context.Background(), source, "", false)
if err == nil { assert.Error(err)
t.Fatal()
}
} }
func TestBindMountSuccessful(t *testing.T) { func TestBindMountSuccessful(t *testing.T) {
assert := assert.New(t)
if tc.NotValid(ktu.NeedRoot()) { if tc.NotValid(ktu.NeedRoot()) {
t.Skip(testDisabledAsNonRoot) t.Skip(testDisabledAsNonRoot)
} }
@@ -60,24 +55,19 @@ func TestBindMountSuccessful(t *testing.T) {
os.Remove(dest) os.Remove(dest)
err := os.MkdirAll(source, mountPerm) err := os.MkdirAll(source, mountPerm)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
err = os.MkdirAll(dest, mountPerm) err = os.MkdirAll(dest, mountPerm)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
err = bindMount(context.Background(), source, dest, false) err = bindMount(context.Background(), source, dest, false)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
syscall.Unmount(dest, 0) syscall.Unmount(dest, 0)
} }
func TestBindMountReadonlySuccessful(t *testing.T) { func TestBindMountReadonlySuccessful(t *testing.T) {
assert := assert.New(t)
if tc.NotValid(ktu.NeedRoot()) { if tc.NotValid(ktu.NeedRoot()) {
t.Skip(testDisabledAsNonRoot) t.Skip(testDisabledAsNonRoot)
} }
@@ -89,35 +79,25 @@ func TestBindMountReadonlySuccessful(t *testing.T) {
os.Remove(dest) os.Remove(dest)
err := os.MkdirAll(source, mountPerm) err := os.MkdirAll(source, mountPerm)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
err = os.MkdirAll(dest, mountPerm) err = os.MkdirAll(dest, mountPerm)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
err = bindMount(context.Background(), source, dest, true) err = bindMount(context.Background(), source, dest, true)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer syscall.Unmount(dest, 0) defer syscall.Unmount(dest, 0)
// should not be able to create file in read-only mount // should not be able to create file in read-only mount
destFile := filepath.Join(dest, "foo") destFile := filepath.Join(dest, "foo")
_, err = os.OpenFile(destFile, os.O_CREATE, mountPerm) _, err = os.OpenFile(destFile, os.O_CREATE, mountPerm)
if err == nil { assert.Error(err)
t.Fatal(err)
}
} }
func TestEnsureDestinationExistsNonExistingSource(t *testing.T) { func TestEnsureDestinationExistsNonExistingSource(t *testing.T) {
err := ensureDestinationExists("", "") err := ensureDestinationExists("", "")
if err == nil { assert.Error(t, err)
t.Fatal()
}
} }
func TestEnsureDestinationExistsWrongParentDir(t *testing.T) { func TestEnsureDestinationExistsWrongParentDir(t *testing.T) {
@@ -125,16 +105,13 @@ func TestEnsureDestinationExistsWrongParentDir(t *testing.T) {
dest := filepath.Join(source, "fooDest") dest := filepath.Join(source, "fooDest")
os.Remove(source) os.Remove(source)
os.Remove(dest) os.Remove(dest)
assert := assert.New(t)
_, err := os.OpenFile(source, os.O_CREATE, mountPerm) _, err := os.OpenFile(source, os.O_CREATE, mountPerm)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
err = ensureDestinationExists(source, dest) err = ensureDestinationExists(source, dest)
if err == nil { assert.Error(err)
t.Fatal()
}
} }
func TestEnsureDestinationExistsSuccessfulSrcDir(t *testing.T) { func TestEnsureDestinationExistsSuccessfulSrcDir(t *testing.T) {
@@ -142,16 +119,13 @@ func TestEnsureDestinationExistsSuccessfulSrcDir(t *testing.T) {
dest := filepath.Join(testDir, "fooDirDest") dest := filepath.Join(testDir, "fooDirDest")
os.Remove(source) os.Remove(source)
os.Remove(dest) os.Remove(dest)
assert := assert.New(t)
err := os.MkdirAll(source, mountPerm) err := os.MkdirAll(source, mountPerm)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
err = ensureDestinationExists(source, dest) err = ensureDestinationExists(source, dest)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
} }
func TestEnsureDestinationExistsSuccessfulSrcFile(t *testing.T) { func TestEnsureDestinationExistsSuccessfulSrcFile(t *testing.T) {
@@ -159,14 +133,11 @@ func TestEnsureDestinationExistsSuccessfulSrcFile(t *testing.T) {
dest := filepath.Join(testDir, "fooDirDest") dest := filepath.Join(testDir, "fooDirDest")
os.Remove(source) os.Remove(source)
os.Remove(dest) os.Remove(dest)
assert := assert.New(t)
_, err := os.OpenFile(source, os.O_CREATE, mountPerm) _, err := os.OpenFile(source, os.O_CREATE, mountPerm)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
err = ensureDestinationExists(source, dest) err = ensureDestinationExists(source, dest)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
} }

View File

@@ -5,46 +5,32 @@
package types package types
import "testing" import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestBlockDeviceCapability(t *testing.T) { func TestBlockDeviceCapability(t *testing.T) {
var caps Capabilities var caps Capabilities
if caps.IsBlockDeviceSupported() { assert.False(t, caps.IsBlockDeviceSupported())
t.Fatal()
}
caps.SetBlockDeviceSupport() caps.SetBlockDeviceSupport()
assert.True(t, caps.IsBlockDeviceSupported())
if !caps.IsBlockDeviceSupported() {
t.Fatal()
}
} }
func TestBlockDeviceHotplugCapability(t *testing.T) { func TestBlockDeviceHotplugCapability(t *testing.T) {
var caps Capabilities var caps Capabilities
if caps.IsBlockDeviceHotplugSupported() { assert.False(t, caps.IsBlockDeviceHotplugSupported())
t.Fatal()
}
caps.SetBlockDeviceHotplugSupport() caps.SetBlockDeviceHotplugSupport()
assert.True(t, caps.IsBlockDeviceHotplugSupported())
if !caps.IsBlockDeviceHotplugSupported() {
t.Fatal()
}
} }
func TestFsSharingCapability(t *testing.T) { func TestFsSharingCapability(t *testing.T) {
var caps Capabilities var caps Capabilities
if !caps.IsFsSharingSupported() { assert.True(t, caps.IsFsSharingSupported())
t.Fatal()
}
caps.SetFsSharingUnsupported() caps.SetFsSharingUnsupported()
assert.False(t, caps.IsFsSharingSupported())
if caps.IsFsSharingSupported() {
t.Fatal()
}
} }

View File

@@ -7,12 +7,12 @@ package virtcontainers
import ( import (
"testing" "testing"
"github.com/stretchr/testify/assert"
) )
func testIsSandbox(t *testing.T, cType ContainerType, expected bool) { func testIsSandbox(t *testing.T, cType ContainerType, expected bool) {
if result := cType.IsSandbox(); result != expected { assert.Equal(t, cType.IsSandbox(), expected)
t.Fatalf("Got %t, Expecting %t", result, expected)
}
} }
func TestIsPodSandboxTrue(t *testing.T) { func TestIsPodSandboxTrue(t *testing.T) {

View File

@@ -17,127 +17,91 @@ import (
) )
func TestFileCopySuccessful(t *testing.T) { func TestFileCopySuccessful(t *testing.T) {
assert := assert.New(t)
fileContent := "testContent" fileContent := "testContent"
srcFile, err := ioutil.TempFile("", "test_src_copy") srcFile, err := ioutil.TempFile("", "test_src_copy")
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer os.Remove(srcFile.Name()) defer os.Remove(srcFile.Name())
defer srcFile.Close() defer srcFile.Close()
dstFile, err := ioutil.TempFile("", "test_dst_copy") dstFile, err := ioutil.TempFile("", "test_dst_copy")
if err != nil { assert.NoError(err)
t.Fatal(err)
}
defer os.Remove(dstFile.Name()) defer os.Remove(dstFile.Name())
dstPath := dstFile.Name() dstPath := dstFile.Name()
if err := dstFile.Close(); err != nil { assert.NoError(dstFile.Close())
t.Fatal(err)
}
if _, err := srcFile.WriteString(fileContent); err != nil { _, err = srcFile.WriteString(fileContent)
t.Fatal(err) assert.NoError(err)
}
if err := FileCopy(srcFile.Name(), dstPath); err != nil { err = FileCopy(srcFile.Name(), dstPath)
t.Fatal(err) assert.NoError(err)
}
dstContent, err := ioutil.ReadFile(dstPath) dstContent, err := ioutil.ReadFile(dstPath)
if err != nil { assert.NoError(err)
t.Fatal(err) assert.Equal(string(dstContent), fileContent)
}
if string(dstContent) != fileContent {
t.Fatalf("Got %q\nExpecting %q", string(dstContent), fileContent)
}
srcInfo, err := srcFile.Stat() srcInfo, err := srcFile.Stat()
if err != nil { assert.NoError(err)
t.Fatal(err)
}
dstInfo, err := os.Stat(dstPath) dstInfo, err := os.Stat(dstPath)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
if dstInfo.Mode() != srcInfo.Mode() { assert.Equal(dstInfo.Mode(), srcInfo.Mode())
t.Fatalf("Got FileMode %d\nExpecting FileMode %d", dstInfo.Mode(), srcInfo.Mode()) assert.Equal(dstInfo.IsDir(), srcInfo.IsDir())
} assert.Equal(dstInfo.Size(), srcInfo.Size())
if dstInfo.IsDir() != srcInfo.IsDir() {
t.Fatalf("Got IsDir() = %t\nExpecting IsDir() = %t", dstInfo.IsDir(), srcInfo.IsDir())
}
if dstInfo.Size() != srcInfo.Size() {
t.Fatalf("Got Size() = %d\nExpecting Size() = %d", dstInfo.Size(), srcInfo.Size())
}
} }
func TestFileCopySourceEmptyFailure(t *testing.T) { func TestFileCopySourceEmptyFailure(t *testing.T) {
if err := FileCopy("", "testDst"); err == nil { assert := assert.New(t)
t.Fatal("This test should fail because source path is empty") err := FileCopy("", "testDst")
} assert.Error(err)
} }
func TestFileCopyDestinationEmptyFailure(t *testing.T) { func TestFileCopyDestinationEmptyFailure(t *testing.T) {
if err := FileCopy("testSrc", ""); err == nil { assert := assert.New(t)
t.Fatal("This test should fail because destination path is empty") err := FileCopy("testSrc", "")
} assert.Error(err)
} }
func TestFileCopySourceNotExistFailure(t *testing.T) { func TestFileCopySourceNotExistFailure(t *testing.T) {
assert := assert.New(t)
srcFile, err := ioutil.TempFile("", "test_src_copy") srcFile, err := ioutil.TempFile("", "test_src_copy")
if err != nil { assert.NoError(err)
t.Fatal(err)
}
srcPath := srcFile.Name() srcPath := srcFile.Name()
assert.NoError(srcFile.Close())
assert.NoError(os.Remove(srcPath))
if err := srcFile.Close(); err != nil { err = FileCopy(srcPath, "testDest")
t.Fatal(err) assert.Error(err)
}
if err := os.Remove(srcPath); err != nil {
t.Fatal(err)
}
if err := FileCopy(srcPath, "testDest"); err == nil {
t.Fatal("This test should fail because source file does not exist")
}
} }
func TestGenerateRandomBytes(t *testing.T) { func TestGenerateRandomBytes(t *testing.T) {
assert := assert.New(t)
bytesNeeded := 8 bytesNeeded := 8
randBytes, err := GenerateRandomBytes(bytesNeeded) randBytes, err := GenerateRandomBytes(bytesNeeded)
if err != nil { assert.NoError(err)
t.Fatal(err) assert.Equal(len(randBytes), bytesNeeded)
}
if len(randBytes) != bytesNeeded {
t.Fatalf("Failed to generate %d random bytes", bytesNeeded)
}
} }
func TestRevereString(t *testing.T) { func TestRevereString(t *testing.T) {
assert := assert.New(t)
str := "Teststr" str := "Teststr"
reversed := ReverseString(str) reversed := ReverseString(str)
assert.Equal(reversed, "rtstseT")
if reversed != "rtstseT" {
t.Fatal("Incorrect String Reversal")
}
} }
func TestWriteToFile(t *testing.T) { func TestWriteToFile(t *testing.T) {
assert := assert.New(t)
err := WriteToFile("/file-does-not-exist", []byte("test-data")) err := WriteToFile("/file-does-not-exist", []byte("test-data"))
assert.NotNil(t, err) assert.NotNil(err)
tmpFile, err := ioutil.TempFile("", "test_append_file") tmpFile, err := ioutil.TempFile("", "test_append_file")
assert.Nil(t, err) assert.NoError(err)
filename := tmpFile.Name() filename := tmpFile.Name()
defer os.Remove(filename) defer os.Remove(filename)
@@ -146,12 +110,12 @@ func TestWriteToFile(t *testing.T) {
testData := []byte("test-data") testData := []byte("test-data")
err = WriteToFile(filename, testData) err = WriteToFile(filename, testData)
assert.Nil(t, err) assert.NoError(err)
data, err := ioutil.ReadFile(filename) data, err := ioutil.ReadFile(filename)
assert.Nil(t, err) assert.NoError(err)
assert.True(t, reflect.DeepEqual(testData, data)) assert.True(reflect.DeepEqual(testData, data))
} }
func TestConstraintsToVCPUs(t *testing.T) { func TestConstraintsToVCPUs(t *testing.T) {
@@ -172,14 +136,13 @@ func TestConstraintsToVCPUs(t *testing.T) {
} }
func TestGetVirtDriveNameInvalidIndex(t *testing.T) { func TestGetVirtDriveNameInvalidIndex(t *testing.T) {
assert := assert.New(t)
_, err := GetVirtDriveName(-1) _, err := GetVirtDriveName(-1)
assert.Error(err)
if err == nil {
t.Fatal(err)
}
} }
func TestGetVirtDriveName(t *testing.T) { func TestGetVirtDriveName(t *testing.T) {
assert := assert.New(t)
tests := []struct { tests := []struct {
index int index int
expectedDrive string expectedDrive string
@@ -193,17 +156,14 @@ func TestGetVirtDriveName(t *testing.T) {
for _, test := range tests { for _, test := range tests {
driveName, err := GetVirtDriveName(test.index) driveName, err := GetVirtDriveName(test.index)
if err != nil { assert.NoError(err)
t.Fatal(err) assert.Equal(driveName, test.expectedDrive)
}
if driveName != test.expectedDrive {
t.Fatalf("Incorrect drive Name: Got: %s, Expecting :%s", driveName, test.expectedDrive)
}
} }
} }
func TestGetSCSIIdLun(t *testing.T) { func TestGetSCSIIdLun(t *testing.T) {
assert := assert.New(t)
tests := []struct { tests := []struct {
index int index int
expectedScsiID int expectedScsiID int
@@ -222,18 +182,17 @@ func TestGetSCSIIdLun(t *testing.T) {
for _, test := range tests { for _, test := range tests {
scsiID, lun, err := GetSCSIIdLun(test.index) scsiID, lun, err := GetSCSIIdLun(test.index)
assert.Nil(t, err) assert.NoError(err)
assert.Equal(scsiID, test.expectedScsiID)
if scsiID != test.expectedScsiID && lun != test.expectedLun { assert.Equal(lun, test.expectedLun)
t.Fatalf("Expecting scsi-id:lun %d:%d, Got %d:%d", test.expectedScsiID, test.expectedLun, scsiID, lun)
}
} }
_, _, err := GetSCSIIdLun(maxSCSIDevices + 1) _, _, err := GetSCSIIdLun(maxSCSIDevices + 1)
assert.NotNil(t, err) assert.NotNil(err)
} }
func TestGetSCSIAddress(t *testing.T) { func TestGetSCSIAddress(t *testing.T) {
assert := assert.New(t)
tests := []struct { tests := []struct {
index int index int
expectedSCSIAddress string expectedSCSIAddress string
@@ -247,9 +206,8 @@ func TestGetSCSIAddress(t *testing.T) {
for _, test := range tests { for _, test := range tests {
scsiAddr, err := GetSCSIAddress(test.index) scsiAddr, err := GetSCSIAddress(test.index)
assert.Nil(t, err) assert.NoError(err)
assert.Equal(t, scsiAddr, test.expectedSCSIAddress) assert.Equal(scsiAddr, test.expectedSCSIAddress)
} }
} }

View File

@@ -7,11 +7,13 @@ package virtcontainers
import ( import (
"net" "net"
"reflect"
"testing" "testing"
"github.com/stretchr/testify/assert"
) )
func TestCreateVethNetworkEndpoint(t *testing.T) { func TestCreateVethNetworkEndpoint(t *testing.T) {
assert := assert.New(t)
macAddr := net.HardwareAddr{0x02, 0x00, 0xCA, 0xFE, 0x00, 0x04} macAddr := net.HardwareAddr{0x02, 0x00, 0xCA, 0xFE, 0x00, 0x04}
expected := &VethEndpoint{ expected := &VethEndpoint{
@@ -33,9 +35,7 @@ func TestCreateVethNetworkEndpoint(t *testing.T) {
} }
result, err := createVethNetworkEndpoint(4, "", DefaultNetInterworkingModel) result, err := createVethNetworkEndpoint(4, "", DefaultNetInterworkingModel)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
// the resulting ID will be random - so let's overwrite to test the rest of the flow // the resulting ID will be random - so let's overwrite to test the rest of the flow
result.NetPair.ID = "uniqueTestID-4" result.NetPair.ID = "uniqueTestID-4"
@@ -43,12 +43,11 @@ func TestCreateVethNetworkEndpoint(t *testing.T) {
// the resulting mac address will be random - so lets overwrite it // the resulting mac address will be random - so lets overwrite it
result.NetPair.VirtIface.HardAddr = macAddr.String() result.NetPair.VirtIface.HardAddr = macAddr.String()
if reflect.DeepEqual(result, expected) == false { assert.Exactly(result, expected)
t.Fatalf("\nGot: %+v, \n\nExpected: %+v", result, expected)
}
} }
func TestCreateVethNetworkEndpointChooseIfaceName(t *testing.T) { func TestCreateVethNetworkEndpointChooseIfaceName(t *testing.T) {
assert := assert.New(t)
macAddr := net.HardwareAddr{0x02, 0x00, 0xCA, 0xFE, 0x00, 0x04} macAddr := net.HardwareAddr{0x02, 0x00, 0xCA, 0xFE, 0x00, 0x04}
expected := &VethEndpoint{ expected := &VethEndpoint{
@@ -70,9 +69,7 @@ func TestCreateVethNetworkEndpointChooseIfaceName(t *testing.T) {
} }
result, err := createVethNetworkEndpoint(4, "eth1", DefaultNetInterworkingModel) result, err := createVethNetworkEndpoint(4, "eth1", DefaultNetInterworkingModel)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
// the resulting ID will be random - so let's overwrite to test the rest of the flow // the resulting ID will be random - so let's overwrite to test the rest of the flow
result.NetPair.ID = "uniqueTestID-4" result.NetPair.ID = "uniqueTestID-4"
@@ -80,9 +77,7 @@ func TestCreateVethNetworkEndpointChooseIfaceName(t *testing.T) {
// the resulting mac address will be random - so lets overwrite it // the resulting mac address will be random - so lets overwrite it
result.NetPair.VirtIface.HardAddr = macAddr.String() result.NetPair.VirtIface.HardAddr = macAddr.String()
if reflect.DeepEqual(result, expected) == false { assert.Exactly(result, expected)
t.Fatalf("\nGot: %+v, \n\nExpected: %+v", result, expected)
}
} }
func TestCreateVethNetworkEndpointInvalidArgs(t *testing.T) { func TestCreateVethNetworkEndpointInvalidArgs(t *testing.T) {
@@ -91,6 +86,8 @@ func TestCreateVethNetworkEndpointInvalidArgs(t *testing.T) {
ifName string ifName string
} }
assert := assert.New(t)
// all elements are expected to result in failure // all elements are expected to result in failure
failingValues := []endpointValues{ failingValues := []endpointValues{
{-1, "bar"}, {-1, "bar"},
@@ -98,9 +95,7 @@ func TestCreateVethNetworkEndpointInvalidArgs(t *testing.T) {
} }
for _, d := range failingValues { for _, d := range failingValues {
result, err := createVethNetworkEndpoint(d.idx, d.ifName, DefaultNetInterworkingModel) _, err := createVethNetworkEndpoint(d.idx, d.ifName, DefaultNetInterworkingModel)
if err == nil { assert.Error(err)
t.Fatalf("expected invalid endpoint for %v, got %v", d, result)
}
} }
} }

View File

@@ -9,7 +9,6 @@ import (
"fmt" "fmt"
"net" "net"
"os" "os"
"reflect"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@@ -17,6 +16,7 @@ import (
) )
func TestVhostUserSocketPath(t *testing.T) { func TestVhostUserSocketPath(t *testing.T) {
assert := assert.New(t)
// First test case: search for existing: // First test case: search for existing:
addresses := []netlink.Addr{ addresses := []netlink.Addr{
@@ -39,23 +39,16 @@ func TestVhostUserSocketPath(t *testing.T) {
expectedResult := fmt.Sprintf("%s/%s", expectedPath, expectedFileName) expectedResult := fmt.Sprintf("%s/%s", expectedPath, expectedFileName)
err := os.Mkdir(expectedPath, 0777) err := os.Mkdir(expectedPath, 0777)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
_, err = os.Create(expectedResult) _, err = os.Create(expectedResult)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
netinfo := NetworkInfo{ netinfo := NetworkInfo{
Addrs: addresses, Addrs: addresses,
} }
path, _ := vhostUserSocketPath(netinfo) path, _ := vhostUserSocketPath(netinfo)
assert.Equal(path, expectedResult)
if path != expectedResult {
t.Fatalf("Got %+v\nExpecting %+v", path, expectedResult)
}
// Second test case: search doesn't include matching vsock: // Second test case: search doesn't include matching vsock:
addressesFalse := []netlink.Addr{ addressesFalse := []netlink.Addr{
@@ -71,23 +64,14 @@ func TestVhostUserSocketPath(t *testing.T) {
} }
path, _ = vhostUserSocketPath(netinfoFail) path, _ = vhostUserSocketPath(netinfoFail)
if path != "" { assert.Empty(path)
t.Fatalf("Got %+v\nExpecting %+v", path, "")
}
err = os.Remove(expectedResult)
if err != nil {
t.Fatal(err)
}
err = os.Remove(expectedPath)
if err != nil {
t.Fatal(err)
}
assert.NoError(os.Remove(expectedResult))
assert.NoError(os.Remove(expectedPath))
} }
func TestVhostUserEndpointAttach(t *testing.T) { func TestVhostUserEndpointAttach(t *testing.T) {
assert := assert.New(t)
v := &VhostUserEndpoint{ v := &VhostUserEndpoint{
SocketPath: "/tmp/sock", SocketPath: "/tmp/sock",
HardAddr: "mac-addr", HardAddr: "mac-addr",
@@ -97,9 +81,7 @@ func TestVhostUserEndpointAttach(t *testing.T) {
h := &mockHypervisor{} h := &mockHypervisor{}
err := v.Attach(h) err := v.Attach(h)
if err != nil { assert.NoError(err)
t.Fatal(err)
}
} }
func TestVhostUserEndpoint_HotAttach(t *testing.T) { func TestVhostUserEndpoint_HotAttach(t *testing.T) {
@@ -134,6 +116,7 @@ func TestCreateVhostUserEndpoint(t *testing.T) {
macAddr := net.HardwareAddr{0x02, 0x00, 0xCA, 0xFE, 0x00, 0x48} macAddr := net.HardwareAddr{0x02, 0x00, 0xCA, 0xFE, 0x00, 0x48}
ifcName := "vhost-deadbeef" ifcName := "vhost-deadbeef"
socket := "/tmp/vhu_192.168.0.1" socket := "/tmp/vhu_192.168.0.1"
assert := assert.New(t)
netinfo := NetworkInfo{ netinfo := NetworkInfo{
Iface: NetlinkIface{ Iface: NetlinkIface{
@@ -152,11 +135,6 @@ func TestCreateVhostUserEndpoint(t *testing.T) {
} }
result, err := createVhostUserEndpoint(netinfo, socket) result, err := createVhostUserEndpoint(netinfo, socket)
if err != nil { assert.NoError(err)
t.Fatal(err) assert.Exactly(result, expected)
}
if reflect.DeepEqual(result, expected) == false {
t.Fatalf("\n\tGot %v\n\tExpecting %v", result, expected)
}
} }