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

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -58,20 +58,18 @@ func testGenerateKataProxySockDir() (string, error) {
}
func TestKataAgentConnect(t *testing.T) {
assert := assert.New(t)
proxy := mock.ProxyUnixMock{
ClientHandler: proxyHandlerDiscard,
}
sockDir, err := testGenerateKataProxySockDir()
if err != nil {
t.Fatal(err)
}
assert.NoError(err)
defer os.RemoveAll(sockDir)
testKataProxyURL := fmt.Sprintf(testKataProxyURLTempl, sockDir)
if err := proxy.Start(testKataProxyURL); err != nil {
t.Fatal(err)
}
err = proxy.Start(testKataProxyURL)
assert.NoError(err)
defer proxy.Stop()
k := &kataAgent{
@@ -81,30 +79,24 @@ func TestKataAgentConnect(t *testing.T) {
},
}
if err := k.connect(); err != nil {
t.Fatal(err)
}
if k.client == nil {
t.Fatal("Kata agent client is not properly initialized")
}
err = k.connect()
assert.NoError(err)
assert.NotNil(k.client)
}
func TestKataAgentDisconnect(t *testing.T) {
assert := assert.New(t)
proxy := mock.ProxyUnixMock{
ClientHandler: proxyHandlerDiscard,
}
sockDir, err := testGenerateKataProxySockDir()
if err != nil {
t.Fatal(err)
}
assert.NoError(err)
defer os.RemoveAll(sockDir)
testKataProxyURL := fmt.Sprintf(testKataProxyURLTempl, sockDir)
if err := proxy.Start(testKataProxyURL); err != nil {
t.Fatal(err)
}
err = proxy.Start(testKataProxyURL)
assert.NoError(err)
defer proxy.Stop()
k := &kataAgent{
@@ -114,17 +106,9 @@ func TestKataAgentDisconnect(t *testing.T) {
},
}
if err := k.connect(); err != nil {
t.Fatal(err)
}
if err := k.disconnect(); err != nil {
t.Fatal(err)
}
if k.client != nil {
t.Fatal("Kata agent client pointer should be nil")
}
assert.NoError(k.connect())
assert.NoError(k.disconnect())
assert.Nil(k.client)
}
type gRPCProxy struct{}
@@ -816,15 +800,11 @@ func TestAgentNetworkOperation(t *testing.T) {
}
sockDir, err := testGenerateKataProxySockDir()
if err != nil {
t.Fatal(err)
}
assert.NoError(err)
defer os.RemoveAll(sockDir)
testKataProxyURL := fmt.Sprintf(testKataProxyURLTempl, sockDir)
if err := proxy.Start(testKataProxyURL); err != nil {
t.Fatal(err)
}
assert.NoError(proxy.Start(testKataProxyURL))
defer proxy.Stop()
k := &kataAgent{
@@ -956,9 +936,8 @@ func TestKataCleanupSandbox(t *testing.T) {
k := &kataAgent{}
k.cleanup(s.id)
if _, err = os.Stat(dir); os.IsExist(err) {
t.Fatalf("%s still exists\n", dir)
}
_, err = os.Stat(dir)
assert.False(os.IsExist(err))
}
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/utils"
"github.com/stretchr/testify/assert"
)
const (
@@ -41,23 +42,15 @@ func getMockKataShimBinPath() string {
func testKataShimStart(t *testing.T, sandbox *Sandbox, params ShimParams, expectFail bool) {
s := &kataShim{}
assert := assert.New(t)
pid, err := s.start(sandbox, params)
if expectFail {
if err == nil || pid != -1 {
t.Fatalf("This test should fail (sandbox %+v, params %+v, expectFail %t)",
sandbox, params, expectFail)
}
assert.Error(err)
assert.Equal(pid, -1)
} else {
if err != nil {
t.Fatalf("This test should pass (sandbox %+v, params %+v, expectFail %t): %s",
sandbox, params, expectFail, err)
}
if pid == -1 {
t.Fatalf("This test should pass (sandbox %+v, params %+v, expectFail %t)",
sandbox, params, expectFail)
}
assert.NoError(err)
assert.NotEqual(pid, -1)
}
}
@@ -145,9 +138,7 @@ func TestKataShimStartParamsContainerEmptyFailure(t *testing.T) {
func TestKataShimStartParamsInvalidCommand(t *testing.T) {
dir, err := ioutil.TempDir("", "")
if err != nil {
t.Fatal(err)
}
assert.NoError(t, err)
defer os.RemoveAll(dir)
cmd := filepath.Join(dir, "does-not-exist")
@@ -199,9 +190,8 @@ func startKataShimStartWithoutConsoleSuccessful(t *testing.T, detach bool) (*os.
func TestKataShimStartSuccessful(t *testing.T) {
rStdout, wStdout, saveStdout, sandbox, params, err := startKataShimStartWithoutConsoleSuccessful(t, false)
if err != nil {
t.Fatal(err)
}
assert := assert.New(t)
assert.NoError(err)
defer func() {
os.Stdout = saveStdout
@@ -212,20 +202,14 @@ func TestKataShimStartSuccessful(t *testing.T) {
testKataShimStart(t, sandbox, params, false)
bufStdout := make([]byte, 1024)
if _, err := rStdout.Read(bufStdout); err != nil {
t.Fatal(err)
}
if !strings.Contains(string(bufStdout), ShimStdoutOutput) {
t.Fatalf("Substring %q not found in %q", ShimStdoutOutput, string(bufStdout))
}
_, err = rStdout.Read(bufStdout)
assert.NoError(err)
assert.True(strings.Contains(string(bufStdout), ShimStdoutOutput))
}
func TestKataShimStartDetachSuccessful(t *testing.T) {
rStdout, wStdout, saveStdout, sandbox, params, err := startKataShimStartWithoutConsoleSuccessful(t, true)
if err != nil {
t.Fatal(err)
}
assert.NoError(t, err)
defer func() {
os.Stdout = saveStdout
@@ -255,9 +239,7 @@ func TestKataShimStartDetachSuccessful(t *testing.T) {
select {
case err := <-readCh:
if err != nil {
t.Fatal(err)
}
assert.NoError(t, err)
case <-time.After(time.Duration(20) * time.Millisecond):
return
}
@@ -327,10 +309,7 @@ func TestKataShimStartWithConsoleSuccessful(t *testing.T) {
master, console, err := newConsole()
t.Logf("Console created for tests:%s\n", console)
if err != nil {
t.Fatal(err)
}
assert.NoError(t, err)
sandbox := &Sandbox{
config: &SandboxConfig{

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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