pkg/cri/server: sub-test uses array and capture range var

Using array to build sub-tests is to avoid random pick. The shuffle
thing should be handled by go-test framework. And we should capture
range var before runing sub-test.

Signed-off-by: Wei Fu <fuweid89@gmail.com>
This commit is contained in:
Wei Fu 2023-04-16 16:47:02 +08:00
parent ffc70c45c4
commit 4192ca8f8c
23 changed files with 948 additions and 479 deletions

File diff suppressed because it is too large Load Diff

View File

@ -81,18 +81,21 @@ func TestPodAnnotationPassthroughContainerSpec(t *testing.T) {
testContainerName := "container-name" testContainerName := "container-name"
testPid := uint32(1234) testPid := uint32(1234)
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
podAnnotations []string podAnnotations []string
configChange func(*runtime.PodSandboxConfig) configChange func(*runtime.PodSandboxConfig)
specCheck func(*testing.T, *runtimespec.Spec) specCheck func(*testing.T, *runtimespec.Spec)
}{ }{
"a passthrough annotation should be passed as an OCI annotation": { {
desc: "a passthrough annotation should be passed as an OCI annotation",
podAnnotations: []string{"c"}, podAnnotations: []string{"c"},
specCheck: func(t *testing.T, spec *runtimespec.Spec) { specCheck: func(t *testing.T, spec *runtimespec.Spec) {
assert.Equal(t, spec.Annotations["c"], "d") assert.Equal(t, spec.Annotations["c"], "d")
}, },
}, },
"a non-passthrough annotation should not be passed as an OCI annotation": { {
desc: "a non-passthrough annotation should not be passed as an OCI annotation",
configChange: func(c *runtime.PodSandboxConfig) { configChange: func(c *runtime.PodSandboxConfig) {
c.Annotations["d"] = "e" c.Annotations["d"] = "e"
}, },
@ -103,7 +106,8 @@ func TestPodAnnotationPassthroughContainerSpec(t *testing.T) {
assert.False(t, ok) assert.False(t, ok)
}, },
}, },
"passthrough annotations should support wildcard match": { {
desc: "passthrough annotations should support wildcard match",
configChange: func(c *runtime.PodSandboxConfig) { configChange: func(c *runtime.PodSandboxConfig) {
c.Annotations["t.f"] = "j" c.Annotations["t.f"] = "j"
c.Annotations["z.g"] = "o" c.Annotations["z.g"] = "o"
@ -124,7 +128,8 @@ func TestPodAnnotationPassthroughContainerSpec(t *testing.T) {
}, },
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
c := newTestCRIService() c := newTestCRIService()
containerConfig, sandboxConfig, imageConfig, specCheck := getCreateContainerTestData() containerConfig, sandboxConfig, imageConfig, specCheck := getCreateContainerTestData()
if test.configChange != nil { if test.configChange != nil {
@ -147,7 +152,8 @@ func TestPodAnnotationPassthroughContainerSpec(t *testing.T) {
} }
func TestContainerSpecCommand(t *testing.T) { func TestContainerSpecCommand(t *testing.T) {
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
criEntrypoint []string criEntrypoint []string
criArgs []string criArgs []string
imageEntrypoint []string imageEntrypoint []string
@ -155,42 +161,49 @@ func TestContainerSpecCommand(t *testing.T) {
expected []string expected []string
expectErr bool expectErr bool
}{ }{
"should use cri entrypoint if it's specified": { {
desc: "should use cri entrypoint if it's specified",
criEntrypoint: []string{"a", "b"}, criEntrypoint: []string{"a", "b"},
imageEntrypoint: []string{"c", "d"}, imageEntrypoint: []string{"c", "d"},
imageArgs: []string{"e", "f"}, imageArgs: []string{"e", "f"},
expected: []string{"a", "b"}, expected: []string{"a", "b"},
}, },
"should use cri entrypoint if it's specified even if it's empty": { {
desc: "should use cri entrypoint if it's specified even if it's empty",
criEntrypoint: []string{}, criEntrypoint: []string{},
criArgs: []string{"a", "b"}, criArgs: []string{"a", "b"},
imageEntrypoint: []string{"c", "d"}, imageEntrypoint: []string{"c", "d"},
imageArgs: []string{"e", "f"}, imageArgs: []string{"e", "f"},
expected: []string{"a", "b"}, expected: []string{"a", "b"},
}, },
"should use cri entrypoint and args if they are specified": { {
desc: "should use cri entrypoint and args if they are specified",
criEntrypoint: []string{"a", "b"}, criEntrypoint: []string{"a", "b"},
criArgs: []string{"c", "d"}, criArgs: []string{"c", "d"},
imageEntrypoint: []string{"e", "f"}, imageEntrypoint: []string{"e", "f"},
imageArgs: []string{"g", "h"}, imageArgs: []string{"g", "h"},
expected: []string{"a", "b", "c", "d"}, expected: []string{"a", "b", "c", "d"},
}, },
"should use image entrypoint if cri entrypoint is not specified": { {
desc: "should use image entrypoint if cri entrypoint is not specified",
criArgs: []string{"a", "b"}, criArgs: []string{"a", "b"},
imageEntrypoint: []string{"c", "d"}, imageEntrypoint: []string{"c", "d"},
imageArgs: []string{"e", "f"}, imageArgs: []string{"e", "f"},
expected: []string{"c", "d", "a", "b"}, expected: []string{"c", "d", "a", "b"},
}, },
"should use image args if both cri entrypoint and args are not specified": { {
desc: "should use image args if both cri entrypoint and args are not specified",
imageEntrypoint: []string{"c", "d"}, imageEntrypoint: []string{"c", "d"},
imageArgs: []string{"e", "f"}, imageArgs: []string{"e", "f"},
expected: []string{"c", "d", "e", "f"}, expected: []string{"c", "d", "e", "f"},
}, },
"should return error if both entrypoint and args are empty": { {
desc: "should return error if both entrypoint and args are empty",
expectErr: true, expectErr: true,
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
config, _, imageConfig, _ := getCreateContainerTestData() config, _, imageConfig, _ := getCreateContainerTestData()
config.Command = test.criEntrypoint config.Command = test.criEntrypoint
config.Args = test.criArgs config.Args = test.criArgs
@ -204,19 +217,21 @@ func TestContainerSpecCommand(t *testing.T) {
return return
} }
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, test.expected, spec.Process.Args, desc) assert.Equal(t, test.expected, spec.Process.Args, test.desc)
}) })
} }
} }
func TestVolumeMounts(t *testing.T) { func TestVolumeMounts(t *testing.T) {
testContainerRootDir := "test-container-root" testContainerRootDir := "test-container-root"
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
criMounts []*runtime.Mount criMounts []*runtime.Mount
imageVolumes map[string]struct{} imageVolumes map[string]struct{}
expectedMountDest []string expectedMountDest []string
}{ }{
"should setup rw mount for image volumes": { {
desc: "should setup rw mount for image volumes",
imageVolumes: map[string]struct{}{ imageVolumes: map[string]struct{}{
"/test-volume-1": {}, "/test-volume-1": {},
"/test-volume-2": {}, "/test-volume-2": {},
@ -226,7 +241,8 @@ func TestVolumeMounts(t *testing.T) {
"/test-volume-2", "/test-volume-2",
}, },
}, },
"should skip image volumes if already mounted by CRI": { {
desc: "should skip image volumes if already mounted by CRI",
criMounts: []*runtime.Mount{ criMounts: []*runtime.Mount{
{ {
ContainerPath: "/test-volume-1", ContainerPath: "/test-volume-1",
@ -241,7 +257,8 @@ func TestVolumeMounts(t *testing.T) {
"/test-volume-2", "/test-volume-2",
}, },
}, },
"should compare and return cleanpath": { {
desc: "should compare and return cleanpath",
criMounts: []*runtime.Mount{ criMounts: []*runtime.Mount{
{ {
ContainerPath: "/test-volume-1", ContainerPath: "/test-volume-1",
@ -257,7 +274,8 @@ func TestVolumeMounts(t *testing.T) {
}, },
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
config := &imagespec.ImageConfig{ config := &imagespec.ImageConfig{
Volumes: test.imageVolumes, Volumes: test.imageVolumes,
} }
@ -294,14 +312,16 @@ func TestContainerAnnotationPassthroughContainerSpec(t *testing.T) {
testContainerName := "container-name" testContainerName := "container-name"
testPid := uint32(1234) testPid := uint32(1234)
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
podAnnotations []string podAnnotations []string
containerAnnotations []string containerAnnotations []string
podConfigChange func(*runtime.PodSandboxConfig) podConfigChange func(*runtime.PodSandboxConfig)
configChange func(*runtime.ContainerConfig) configChange func(*runtime.ContainerConfig)
specCheck func(*testing.T, *runtimespec.Spec) specCheck func(*testing.T, *runtimespec.Spec)
}{ }{
"passthrough annotations from pod and container should be passed as an OCI annotation": { {
desc: "passthrough annotations from pod and container should be passed as an OCI annotation",
podConfigChange: func(p *runtime.PodSandboxConfig) { podConfigChange: func(p *runtime.PodSandboxConfig) {
p.Annotations["pod.annotation.1"] = "1" p.Annotations["pod.annotation.1"] = "1"
p.Annotations["pod.annotation.2"] = "2" p.Annotations["pod.annotation.2"] = "2"
@ -327,7 +347,8 @@ func TestContainerAnnotationPassthroughContainerSpec(t *testing.T) {
assert.False(t, ok) assert.False(t, ok)
}, },
}, },
"passthrough annotations from pod and container should support wildcard": { {
desc: "passthrough annotations from pod and container should support wildcard",
podConfigChange: func(p *runtime.PodSandboxConfig) { podConfigChange: func(p *runtime.PodSandboxConfig) {
p.Annotations["pod.annotation.1"] = "1" p.Annotations["pod.annotation.1"] = "1"
p.Annotations["pod.annotation.2"] = "2" p.Annotations["pod.annotation.2"] = "2"
@ -349,7 +370,8 @@ func TestContainerAnnotationPassthroughContainerSpec(t *testing.T) {
assert.Equal(t, "3", spec.Annotations["pod.annotation.3"]) assert.Equal(t, "3", spec.Annotations["pod.annotation.3"])
}, },
}, },
"annotations should not pass through if no passthrough annotations are configured": { {
desc: "annotations should not pass through if no passthrough annotations are configured",
podConfigChange: func(p *runtime.PodSandboxConfig) { podConfigChange: func(p *runtime.PodSandboxConfig) {
p.Annotations["pod.annotation.1"] = "1" p.Annotations["pod.annotation.1"] = "1"
p.Annotations["pod.annotation.2"] = "2" p.Annotations["pod.annotation.2"] = "2"
@ -378,7 +400,8 @@ func TestContainerAnnotationPassthroughContainerSpec(t *testing.T) {
}, },
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
c := newTestCRIService() c := newTestCRIService()
containerConfig, sandboxConfig, imageConfig, specCheck := getCreateContainerTestData() containerConfig, sandboxConfig, imageConfig, specCheck := getCreateContainerTestData()
if test.configChange != nil { if test.configChange != nil {
@ -440,20 +463,24 @@ func TestRuntimeSnapshotter(t *testing.T) {
Snapshotter: "devmapper", Snapshotter: "devmapper",
} }
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
runtime config.Runtime runtime config.Runtime
expectSnapshotter string expectSnapshotter string
}{ }{
"should return default snapshotter when runtime.Snapshotter is not set": { {
desc: "should return default snapshotter when runtime.Snapshotter is not set",
runtime: defaultRuntime, runtime: defaultRuntime,
expectSnapshotter: config.DefaultConfig().Snapshotter, expectSnapshotter: config.DefaultConfig().Snapshotter,
}, },
"should return overridden snapshotter when runtime.Snapshotter is set": { {
desc: "should return overridden snapshotter when runtime.Snapshotter is set",
runtime: fooRuntime, runtime: fooRuntime,
expectSnapshotter: "devmapper", expectSnapshotter: "devmapper",
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
cri := newTestCRIService() cri := newTestCRIService()
cri.config = config.Config{ cri.config = config.Config{
PluginConfig: config.DefaultConfig(), PluginConfig: config.DefaultConfig(),

View File

@ -213,33 +213,39 @@ func TestHostProcessRequirements(t *testing.T) {
containerConfig, sandboxConfig, imageConfig, _ := getCreateContainerTestData() containerConfig, sandboxConfig, imageConfig, _ := getCreateContainerTestData()
ociRuntime := config.Runtime{} ociRuntime := config.Runtime{}
c := newTestCRIService() c := newTestCRIService()
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
containerHostProcess bool containerHostProcess bool
sandboxHostProcess bool sandboxHostProcess bool
expectError bool expectError bool
}{ }{
"hostprocess container in non-hostprocess sandbox should fail": { {
desc: "hostprocess container in non-hostprocess sandbox should fail",
containerHostProcess: true, containerHostProcess: true,
sandboxHostProcess: false, sandboxHostProcess: false,
expectError: true, expectError: true,
}, },
"hostprocess container in hostprocess sandbox should be fine": { {
desc: "hostprocess container in hostprocess sandbox should be fine",
containerHostProcess: true, containerHostProcess: true,
sandboxHostProcess: true, sandboxHostProcess: true,
expectError: false, expectError: false,
}, },
"non-hostprocess container in hostprocess sandbox should fail": { {
desc: "non-hostprocess container in hostprocess sandbox should fail",
containerHostProcess: false, containerHostProcess: false,
sandboxHostProcess: true, sandboxHostProcess: true,
expectError: true, expectError: true,
}, },
"non-hostprocess container in non-hostprocess sandbox should be fine": { {
desc: "non-hostprocess container in non-hostprocess sandbox should be fine",
containerHostProcess: false, containerHostProcess: false,
sandboxHostProcess: false, sandboxHostProcess: false,
expectError: false, expectError: false,
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
containerConfig.Windows.SecurityContext.HostProcess = test.containerHostProcess containerConfig.Windows.SecurityContext.HostProcess = test.containerHostProcess
sandboxConfig.Windows.SecurityContext = &runtime.WindowsSandboxSecurityContext{ sandboxConfig.Windows.SecurityContext = &runtime.WindowsSandboxSecurityContext{
HostProcess: test.sandboxHostProcess, HostProcess: test.sandboxHostProcess,
@ -262,7 +268,8 @@ func TestEntrypointAndCmdForArgsEscaped(t *testing.T) {
nsPath := "test-ns" nsPath := "test-ns"
c := newTestCRIService() c := newTestCRIService()
for name, test := range map[string]struct { for _, test := range []struct {
name string
imgEntrypoint []string imgEntrypoint []string
imgCmd []string imgCmd []string
command []string command []string
@ -272,7 +279,8 @@ func TestEntrypointAndCmdForArgsEscaped(t *testing.T) {
ArgsEscaped bool ArgsEscaped bool
}{ }{
// override image entrypoint and cmd in shell form with container args and verify expected runtime spec // override image entrypoint and cmd in shell form with container args and verify expected runtime spec
"TestShellFormImgEntrypointCmdWithCtrArgs": { {
name: "TestShellFormImgEntrypointCmdWithCtrArgs",
imgEntrypoint: []string{`"C:\My Folder\MyProcess.exe" -arg1 "test value"`}, imgEntrypoint: []string{`"C:\My Folder\MyProcess.exe" -arg1 "test value"`},
imgCmd: []string{`cmd -args "hello world"`}, imgCmd: []string{`cmd -args "hello world"`},
command: nil, command: nil,
@ -282,7 +290,8 @@ func TestEntrypointAndCmdForArgsEscaped(t *testing.T) {
ArgsEscaped: true, ArgsEscaped: true,
}, },
// check image entrypoint and cmd in shell form without overriding with container command and args and verify expected runtime spec // check image entrypoint and cmd in shell form without overriding with container command and args and verify expected runtime spec
"TestShellFormImgEntrypointCmdWithoutCtrArgs": { {
name: "TestShellFormImgEntrypointCmdWithoutCtrArgs",
imgEntrypoint: []string{`"C:\My Folder\MyProcess.exe" -arg1 "test value"`}, imgEntrypoint: []string{`"C:\My Folder\MyProcess.exe" -arg1 "test value"`},
imgCmd: []string{`cmd -args "hello world"`}, imgCmd: []string{`cmd -args "hello world"`},
command: nil, command: nil,
@ -292,7 +301,8 @@ func TestEntrypointAndCmdForArgsEscaped(t *testing.T) {
ArgsEscaped: true, ArgsEscaped: true,
}, },
// override image entrypoint and cmd by container command and args in shell form and verify expected runtime spec // override image entrypoint and cmd by container command and args in shell form and verify expected runtime spec
"TestShellFormImgEntrypointCmdWithCtrEntrypointAndArgs": { {
name: "TestShellFormImgEntrypointCmdWithCtrEntrypointAndArgs",
imgEntrypoint: []string{`"C:\My Folder\MyProcess.exe" -arg1 "test value"`}, imgEntrypoint: []string{`"C:\My Folder\MyProcess.exe" -arg1 "test value"`},
imgCmd: []string{`cmd -args "hello world"`}, imgCmd: []string{`cmd -args "hello world"`},
command: []string{`C:\My Folder\MyProcess.exe`, "-arg1", "additional test value"}, command: []string{`C:\My Folder\MyProcess.exe`, "-arg1", "additional test value"},
@ -302,7 +312,8 @@ func TestEntrypointAndCmdForArgsEscaped(t *testing.T) {
ArgsEscaped: true, ArgsEscaped: true,
}, },
// override image cmd by container args in exec form and verify expected runtime spec // override image cmd by container args in exec form and verify expected runtime spec
"TestExecFormImgEntrypointCmdWithCtrArgs": { {
name: "TestExecFormImgEntrypointCmdWithCtrArgs",
imgEntrypoint: []string{`C:\My Folder\MyProcess.exe`, "-arg1", "test value"}, imgEntrypoint: []string{`C:\My Folder\MyProcess.exe`, "-arg1", "test value"},
imgCmd: []string{"cmd", "-args", "hello world"}, imgCmd: []string{"cmd", "-args", "hello world"},
command: nil, command: nil,
@ -312,7 +323,8 @@ func TestEntrypointAndCmdForArgsEscaped(t *testing.T) {
ArgsEscaped: false, ArgsEscaped: false,
}, },
// check image entrypoint and cmd in exec form without overriding with container command and args and verify expected runtime spec // check image entrypoint and cmd in exec form without overriding with container command and args and verify expected runtime spec
"TestExecFormImgEntrypointCmdWithoutCtrArgs": { {
name: "TestExecFormImgEntrypointCmdWithoutCtrArgs",
imgEntrypoint: []string{`C:\My Folder\MyProcess.exe`, "-arg1", "test value"}, imgEntrypoint: []string{`C:\My Folder\MyProcess.exe`, "-arg1", "test value"},
imgCmd: []string{"cmd", "-args", "hello world"}, imgCmd: []string{"cmd", "-args", "hello world"},
command: nil, command: nil,
@ -322,7 +334,8 @@ func TestEntrypointAndCmdForArgsEscaped(t *testing.T) {
ArgsEscaped: false, ArgsEscaped: false,
}, },
} { } {
t.Run(name, func(t *testing.T) { test := test
t.Run(test.name, func(t *testing.T) {
imageConfig := &imagespec.ImageConfig{ imageConfig := &imagespec.ImageConfig{
Entrypoint: test.imgEntrypoint, Entrypoint: test.imgEntrypoint,
Cmd: test.imgCmd, Cmd: test.imgCmd,

View File

@ -101,18 +101,22 @@ func TestFilterContainers(t *testing.T) {
Labels: map[string]string{"c": "d"}, Labels: map[string]string{"c": "d"},
}, },
} }
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
filter *runtime.ContainerFilter filter *runtime.ContainerFilter
expect []*runtime.Container expect []*runtime.Container
}{ }{
"no filter": { {
desc: "no filter",
expect: testContainers, expect: testContainers,
}, },
"id filter": { {
desc: "id filter",
filter: &runtime.ContainerFilter{Id: "2"}, filter: &runtime.ContainerFilter{Id: "2"},
expect: []*runtime.Container{testContainers[1]}, expect: []*runtime.Container{testContainers[1]},
}, },
"state filter": { {
desc: "state filter",
filter: &runtime.ContainerFilter{ filter: &runtime.ContainerFilter{
State: &runtime.ContainerStateValue{ State: &runtime.ContainerStateValue{
State: runtime.ContainerState_CONTAINER_EXITED, State: runtime.ContainerState_CONTAINER_EXITED,
@ -120,17 +124,20 @@ func TestFilterContainers(t *testing.T) {
}, },
expect: []*runtime.Container{testContainers[1]}, expect: []*runtime.Container{testContainers[1]},
}, },
"label filter": { {
desc: "label filter",
filter: &runtime.ContainerFilter{ filter: &runtime.ContainerFilter{
LabelSelector: map[string]string{"a": "b"}, LabelSelector: map[string]string{"a": "b"},
}, },
expect: []*runtime.Container{testContainers[1]}, expect: []*runtime.Container{testContainers[1]},
}, },
"sandbox id filter": { {
desc: "sandbox id filter",
filter: &runtime.ContainerFilter{PodSandboxId: "s-2"}, filter: &runtime.ContainerFilter{PodSandboxId: "s-2"},
expect: []*runtime.Container{testContainers[1], testContainers[2]}, expect: []*runtime.Container{testContainers[1], testContainers[2]},
}, },
"mixed filter not matched": { {
desc: "mixed filter not matched",
filter: &runtime.ContainerFilter{ filter: &runtime.ContainerFilter{
Id: "1", Id: "1",
PodSandboxId: "s-2", PodSandboxId: "s-2",
@ -138,7 +145,8 @@ func TestFilterContainers(t *testing.T) {
}, },
expect: []*runtime.Container{}, expect: []*runtime.Container{},
}, },
"mixed filter matched": { {
desc: "mixed filter matched",
filter: &runtime.ContainerFilter{ filter: &runtime.ContainerFilter{
PodSandboxId: "s-2", PodSandboxId: "s-2",
State: &runtime.ContainerStateValue{ State: &runtime.ContainerStateValue{
@ -149,9 +157,10 @@ func TestFilterContainers(t *testing.T) {
expect: []*runtime.Container{testContainers[2]}, expect: []*runtime.Container{testContainers[2]},
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
filtered := c.filterCRIContainers(testContainers, test.filter) filtered := c.filterCRIContainers(testContainers, test.filter)
assert.Equal(t, test.expect, filtered, desc) assert.Equal(t, test.expect, filtered, test.desc)
}) })
} }
} }
@ -287,46 +296,54 @@ func TestListContainers(t *testing.T) {
assert.NoError(t, c.containerStore.Add(container)) assert.NoError(t, c.containerStore.Add(container))
} }
for testdesc, testdata := range map[string]struct { for _, testdata := range []struct {
desc string
filter *runtime.ContainerFilter filter *runtime.ContainerFilter
expect []*runtime.Container expect []*runtime.Container
}{ }{
"test without filter": { {
desc: "test without filter",
filter: &runtime.ContainerFilter{}, filter: &runtime.ContainerFilter{},
expect: expectedContainers, expect: expectedContainers,
}, },
"test filter by sandboxid": { {
desc: "test filter by sandboxid",
filter: &runtime.ContainerFilter{ filter: &runtime.ContainerFilter{
PodSandboxId: "s-1abcdef1234", PodSandboxId: "s-1abcdef1234",
}, },
expect: expectedContainers[:3], expect: expectedContainers[:3],
}, },
"test filter by truncated sandboxid": { {
desc: "test filter by truncated sandboxid",
filter: &runtime.ContainerFilter{ filter: &runtime.ContainerFilter{
PodSandboxId: "s-1", PodSandboxId: "s-1",
}, },
expect: expectedContainers[:3], expect: expectedContainers[:3],
}, },
"test filter by containerid": { {
desc: "test filter by containerid",
filter: &runtime.ContainerFilter{ filter: &runtime.ContainerFilter{
Id: "c-1container", Id: "c-1container",
}, },
expect: expectedContainers[:1], expect: expectedContainers[:1],
}, },
"test filter by truncated containerid": { {
desc: "test filter by truncated containerid",
filter: &runtime.ContainerFilter{ filter: &runtime.ContainerFilter{
Id: "c-1", Id: "c-1",
}, },
expect: expectedContainers[:1], expect: expectedContainers[:1],
}, },
"test filter by containerid and sandboxid": { {
desc: "test filter by containerid and sandboxid",
filter: &runtime.ContainerFilter{ filter: &runtime.ContainerFilter{
Id: "c-1container", Id: "c-1container",
PodSandboxId: "s-1abcdef1234", PodSandboxId: "s-1abcdef1234",
}, },
expect: expectedContainers[:1], expect: expectedContainers[:1],
}, },
"test filter by truncated containerid and truncated sandboxid": { {
desc: "test filter by truncated containerid and truncated sandboxid",
filter: &runtime.ContainerFilter{ filter: &runtime.ContainerFilter{
Id: "c-1", Id: "c-1",
PodSandboxId: "s-1", PodSandboxId: "s-1",
@ -334,7 +351,8 @@ func TestListContainers(t *testing.T) {
expect: expectedContainers[:1], expect: expectedContainers[:1],
}, },
} { } {
t.Run(testdesc, func(t *testing.T) { testdata := testdata
t.Run(testdata.desc, func(t *testing.T) {
resp, err := c.ListContainers(context.Background(), &runtime.ListContainersRequest{Filter: testdata.filter}) resp, err := c.ListContainers(context.Background(), &runtime.ListContainersRequest{Filter: testdata.filter})
assert.NoError(t, err) assert.NoError(t, err)
require.NotNil(t, resp) require.NotNil(t, resp)

View File

@ -29,25 +29,29 @@ import (
// state correctly. // state correctly.
func TestSetContainerRemoving(t *testing.T) { func TestSetContainerRemoving(t *testing.T) {
testID := "test-id" testID := "test-id"
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
status containerstore.Status status containerstore.Status
expectErr bool expectErr bool
}{ }{
"should return error when container is in running state": { {
desc: "should return error when container is in running state",
status: containerstore.Status{ status: containerstore.Status{
CreatedAt: time.Now().UnixNano(), CreatedAt: time.Now().UnixNano(),
StartedAt: time.Now().UnixNano(), StartedAt: time.Now().UnixNano(),
}, },
expectErr: true, expectErr: true,
}, },
"should return error when container is in starting state": { {
desc: "should return error when container is in starting state",
status: containerstore.Status{ status: containerstore.Status{
CreatedAt: time.Now().UnixNano(), CreatedAt: time.Now().UnixNano(),
Starting: true, Starting: true,
}, },
expectErr: true, expectErr: true,
}, },
"should return error when container is in removing state": { {
desc: "should return error when container is in removing state",
status: containerstore.Status{ status: containerstore.Status{
CreatedAt: time.Now().UnixNano(), CreatedAt: time.Now().UnixNano(),
StartedAt: time.Now().UnixNano(), StartedAt: time.Now().UnixNano(),
@ -56,7 +60,8 @@ func TestSetContainerRemoving(t *testing.T) {
}, },
expectErr: true, expectErr: true,
}, },
"should not return error when container is not running and removing": { {
desc: "should not return error when container is not running and removing",
status: containerstore.Status{ status: containerstore.Status{
CreatedAt: time.Now().UnixNano(), CreatedAt: time.Now().UnixNano(),
StartedAt: time.Now().UnixNano(), StartedAt: time.Now().UnixNano(),
@ -65,7 +70,8 @@ func TestSetContainerRemoving(t *testing.T) {
expectErr: false, expectErr: false,
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
container, err := containerstore.NewContainer( container, err := containerstore.NewContainer(
containerstore.Metadata{ID: testID}, containerstore.Metadata{ID: testID},
containerstore.WithFakeStatus(test.status), containerstore.WithFakeStatus(test.status),

View File

@ -29,25 +29,29 @@ import (
// state correctly. // state correctly.
func TestSetContainerStarting(t *testing.T) { func TestSetContainerStarting(t *testing.T) {
testID := "test-id" testID := "test-id"
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
status containerstore.Status status containerstore.Status
expectErr bool expectErr bool
}{ }{
"should not return error when container is in created state": { {
desc: "should not return error when container is in created state",
status: containerstore.Status{ status: containerstore.Status{
CreatedAt: time.Now().UnixNano(), CreatedAt: time.Now().UnixNano(),
}, },
expectErr: false, expectErr: false,
}, },
"should return error when container is in running state": { {
desc: "should return error when container is in running state",
status: containerstore.Status{ status: containerstore.Status{
CreatedAt: time.Now().UnixNano(), CreatedAt: time.Now().UnixNano(),
StartedAt: time.Now().UnixNano(), StartedAt: time.Now().UnixNano(),
}, },
expectErr: true, expectErr: true,
}, },
"should return error when container is in exited state": { {
desc: "should return error when container is in exited state",
status: containerstore.Status{ status: containerstore.Status{
CreatedAt: time.Now().UnixNano(), CreatedAt: time.Now().UnixNano(),
StartedAt: time.Now().UnixNano(), StartedAt: time.Now().UnixNano(),
@ -55,7 +59,8 @@ func TestSetContainerStarting(t *testing.T) {
}, },
expectErr: true, expectErr: true,
}, },
"should return error when container is in unknown state": { {
desc: "should return error when container is in unknown state",
status: containerstore.Status{ status: containerstore.Status{
CreatedAt: 0, CreatedAt: 0,
StartedAt: 0, StartedAt: 0,
@ -63,14 +68,16 @@ func TestSetContainerStarting(t *testing.T) {
}, },
expectErr: true, expectErr: true,
}, },
"should return error when container is in starting state": { {
desc: "should return error when container is in starting state",
status: containerstore.Status{ status: containerstore.Status{
CreatedAt: time.Now().UnixNano(), CreatedAt: time.Now().UnixNano(),
Starting: true, Starting: true,
}, },
expectErr: true, expectErr: true,
}, },
"should return error when container is in removing state": { {
desc: "should return error when container is in removing state",
status: containerstore.Status{ status: containerstore.Status{
CreatedAt: time.Now().UnixNano(), CreatedAt: time.Now().UnixNano(),
Removing: true, Removing: true,
@ -78,7 +85,8 @@ func TestSetContainerStarting(t *testing.T) {
expectErr: true, expectErr: true,
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
container, err := containerstore.NewContainer( container, err := containerstore.NewContainer(
containerstore.Metadata{ID: testID}, containerstore.Metadata{ID: testID},
containerstore.WithFakeStatus(test.status), containerstore.WithFakeStatus(test.status),

View File

@ -28,22 +28,26 @@ import (
) )
func TestGetWorkingSet(t *testing.T) { func TestGetWorkingSet(t *testing.T) {
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
memory *v1.MemoryStat memory *v1.MemoryStat
expected uint64 expected uint64
}{ }{
"nil memory usage": { {
desc: "nil memory usage",
memory: &v1.MemoryStat{}, memory: &v1.MemoryStat{},
expected: 0, expected: 0,
}, },
"memory usage higher than inactive_total_file": { {
desc: "memory usage higher than inactive_total_file",
memory: &v1.MemoryStat{ memory: &v1.MemoryStat{
TotalInactiveFile: 1000, TotalInactiveFile: 1000,
Usage: &v1.MemoryEntry{Usage: 2000}, Usage: &v1.MemoryEntry{Usage: 2000},
}, },
expected: 1000, expected: 1000,
}, },
"memory usage lower than inactive_total_file": { {
desc: "memory usage lower than inactive_total_file",
memory: &v1.MemoryStat{ memory: &v1.MemoryStat{
TotalInactiveFile: 2000, TotalInactiveFile: 2000,
Usage: &v1.MemoryEntry{Usage: 1000}, Usage: &v1.MemoryEntry{Usage: 1000},
@ -51,7 +55,8 @@ func TestGetWorkingSet(t *testing.T) {
expected: 0, expected: 0,
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
got := getWorkingSet(test.memory) got := getWorkingSet(test.memory)
assert.Equal(t, test.expected, got) assert.Equal(t, test.expected, got)
}) })
@ -59,22 +64,26 @@ func TestGetWorkingSet(t *testing.T) {
} }
func TestGetWorkingSetV2(t *testing.T) { func TestGetWorkingSetV2(t *testing.T) {
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
memory *v2.MemoryStat memory *v2.MemoryStat
expected uint64 expected uint64
}{ }{
"nil memory usage": { {
desc: "nil memory usage",
memory: &v2.MemoryStat{}, memory: &v2.MemoryStat{},
expected: 0, expected: 0,
}, },
"memory usage higher than inactive_total_file": { {
desc: "memory usage higher than inactive_total_file",
memory: &v2.MemoryStat{ memory: &v2.MemoryStat{
InactiveFile: 1000, InactiveFile: 1000,
Usage: 2000, Usage: 2000,
}, },
expected: 1000, expected: 1000,
}, },
"memory usage lower than inactive_total_file": { {
desc: "memory usage lower than inactive_total_file",
memory: &v2.MemoryStat{ memory: &v2.MemoryStat{
InactiveFile: 2000, InactiveFile: 2000,
Usage: 1000, Usage: 1000,
@ -82,7 +91,8 @@ func TestGetWorkingSetV2(t *testing.T) {
expected: 0, expected: 0,
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
got := getWorkingSetV2(test.memory) got := getWorkingSetV2(test.memory)
assert.Equal(t, test.expected, got) assert.Equal(t, test.expected, got)
}) })
@ -90,13 +100,15 @@ func TestGetWorkingSetV2(t *testing.T) {
} }
func TestGetAvailableBytes(t *testing.T) { func TestGetAvailableBytes(t *testing.T) {
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
memory *v1.MemoryStat memory *v1.MemoryStat
workingSetBytes uint64 workingSetBytes uint64
expected uint64 expected uint64
}{ }{
"no limit": { {
desc: "no limit",
memory: &v1.MemoryStat{ memory: &v1.MemoryStat{
Usage: &v1.MemoryEntry{ Usage: &v1.MemoryEntry{
Limit: math.MaxUint64, // no limit Limit: math.MaxUint64, // no limit
@ -106,7 +118,8 @@ func TestGetAvailableBytes(t *testing.T) {
workingSetBytes: 500, workingSetBytes: 500,
expected: 0, expected: 0,
}, },
"with limit": { {
desc: "with limit",
memory: &v1.MemoryStat{ memory: &v1.MemoryStat{
Usage: &v1.MemoryEntry{ Usage: &v1.MemoryEntry{
Limit: 5000, Limit: 5000,
@ -117,7 +130,8 @@ func TestGetAvailableBytes(t *testing.T) {
expected: 5000 - 500, expected: 5000 - 500,
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
got := getAvailableBytes(test.memory, test.workingSetBytes) got := getAvailableBytes(test.memory, test.workingSetBytes)
assert.Equal(t, test.expected, got) assert.Equal(t, test.expected, got)
}) })
@ -125,13 +139,15 @@ func TestGetAvailableBytes(t *testing.T) {
} }
func TestGetAvailableBytesV2(t *testing.T) { func TestGetAvailableBytesV2(t *testing.T) {
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
memory *v2.MemoryStat memory *v2.MemoryStat
workingSetBytes uint64 workingSetBytes uint64
expected uint64 expected uint64
}{ }{
"no limit": { {
desc: "no limit",
memory: &v2.MemoryStat{ memory: &v2.MemoryStat{
UsageLimit: math.MaxUint64, // no limit UsageLimit: math.MaxUint64, // no limit
Usage: 1000, Usage: 1000,
@ -139,7 +155,8 @@ func TestGetAvailableBytesV2(t *testing.T) {
workingSetBytes: 500, workingSetBytes: 500,
expected: 0, expected: 0,
}, },
"with limit": { {
desc: "with limit",
memory: &v2.MemoryStat{ memory: &v2.MemoryStat{
UsageLimit: 5000, UsageLimit: 5000,
Usage: 1000, Usage: 1000,
@ -148,7 +165,8 @@ func TestGetAvailableBytesV2(t *testing.T) {
expected: 5000 - 500, expected: 5000 - 500,
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
got := getAvailableBytesV2(test.memory, test.workingSetBytes) got := getAvailableBytesV2(test.memory, test.workingSetBytes)
assert.Equal(t, test.expected, got) assert.Equal(t, test.expected, got)
}) })
@ -159,11 +177,13 @@ func TestContainerMetricsMemory(t *testing.T) {
c := newTestCRIService() c := newTestCRIService()
timestamp := time.Now() timestamp := time.Now()
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
metrics interface{} metrics interface{}
expected *runtime.MemoryUsage expected *runtime.MemoryUsage
}{ }{
"v1 metrics - no memory limit": { {
desc: "v1 metrics - no memory limit",
metrics: &v1.Metrics{ metrics: &v1.Metrics{
Memory: &v1.MemoryStat{ Memory: &v1.MemoryStat{
Usage: &v1.MemoryEntry{ Usage: &v1.MemoryEntry{
@ -186,7 +206,8 @@ func TestContainerMetricsMemory(t *testing.T) {
MajorPageFaults: &runtime.UInt64Value{Value: 12}, MajorPageFaults: &runtime.UInt64Value{Value: 12},
}, },
}, },
"v1 metrics - memory limit": { {
desc: "v1 metrics - memory limit",
metrics: &v1.Metrics{ metrics: &v1.Metrics{
Memory: &v1.MemoryStat{ Memory: &v1.MemoryStat{
Usage: &v1.MemoryEntry{ Usage: &v1.MemoryEntry{
@ -209,7 +230,8 @@ func TestContainerMetricsMemory(t *testing.T) {
MajorPageFaults: &runtime.UInt64Value{Value: 12}, MajorPageFaults: &runtime.UInt64Value{Value: 12},
}, },
}, },
"v2 metrics - memory limit": { {
desc: "v2 metrics - memory limit",
metrics: &v2.Metrics{ metrics: &v2.Metrics{
Memory: &v2.MemoryStat{ Memory: &v2.MemoryStat{
Usage: 1000, Usage: 1000,
@ -229,7 +251,8 @@ func TestContainerMetricsMemory(t *testing.T) {
MajorPageFaults: &runtime.UInt64Value{Value: 12}, MajorPageFaults: &runtime.UInt64Value{Value: 12},
}, },
}, },
"v2 metrics - no memory limit": { {
desc: "v2 metrics - no memory limit",
metrics: &v2.Metrics{ metrics: &v2.Metrics{
Memory: &v2.MemoryStat{ Memory: &v2.MemoryStat{
Usage: 1000, Usage: 1000,
@ -250,7 +273,8 @@ func TestContainerMetricsMemory(t *testing.T) {
}, },
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
got, err := c.memoryContainerStats("ID", test.metrics, timestamp) got, err := c.memoryContainerStats("ID", test.metrics, timestamp)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, test.expected, got) assert.Equal(t, test.expected, got)

View File

@ -30,20 +30,23 @@ func TestContainerMetricsCPUNanoCoreUsage(t *testing.T) {
secondAfterTimeStamp := timestamp.Add(time.Second) secondAfterTimeStamp := timestamp.Add(time.Second)
ID := "ID" ID := "ID"
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
firstCPUValue uint64 firstCPUValue uint64
secondCPUValue uint64 secondCPUValue uint64
expectedNanoCoreUsageFirst uint64 expectedNanoCoreUsageFirst uint64
expectedNanoCoreUsageSecond uint64 expectedNanoCoreUsageSecond uint64
}{ }{
"metrics": { {
desc: "metrics",
firstCPUValue: 50, firstCPUValue: 50,
secondCPUValue: 500, secondCPUValue: 500,
expectedNanoCoreUsageFirst: 0, expectedNanoCoreUsageFirst: 0,
expectedNanoCoreUsageSecond: 450, expectedNanoCoreUsageSecond: 450,
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
container, err := containerstore.NewContainer( container, err := containerstore.NewContainer(
containerstore.Metadata{ID: ID}, containerstore.Metadata{ID: ID},
) )

View File

@ -85,7 +85,8 @@ func getContainerStatusTestData() (*containerstore.Metadata, *containerstore.Sta
} }
func TestToCRIContainerStatus(t *testing.T) { func TestToCRIContainerStatus(t *testing.T) {
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
startedAt int64 startedAt int64
finishedAt int64 finishedAt int64
exitCode int32 exitCode int32
@ -94,14 +95,17 @@ func TestToCRIContainerStatus(t *testing.T) {
expectedState runtime.ContainerState expectedState runtime.ContainerState
expectedReason string expectedReason string
}{ }{
"container created": { {
desc: "container created",
expectedState: runtime.ContainerState_CONTAINER_CREATED, expectedState: runtime.ContainerState_CONTAINER_CREATED,
}, },
"container running": { {
desc: "container running",
startedAt: time.Now().UnixNano(), startedAt: time.Now().UnixNano(),
expectedState: runtime.ContainerState_CONTAINER_RUNNING, expectedState: runtime.ContainerState_CONTAINER_RUNNING,
}, },
"container exited with reason": { {
desc: "container exited with reason",
startedAt: time.Now().UnixNano(), startedAt: time.Now().UnixNano(),
finishedAt: time.Now().UnixNano(), finishedAt: time.Now().UnixNano(),
exitCode: 1, exitCode: 1,
@ -110,7 +114,8 @@ func TestToCRIContainerStatus(t *testing.T) {
expectedState: runtime.ContainerState_CONTAINER_EXITED, expectedState: runtime.ContainerState_CONTAINER_EXITED,
expectedReason: "test-reason", expectedReason: "test-reason",
}, },
"container exited with exit code 0 without reason": { {
desc: "container exited with exit code 0 without reason",
startedAt: time.Now().UnixNano(), startedAt: time.Now().UnixNano(),
finishedAt: time.Now().UnixNano(), finishedAt: time.Now().UnixNano(),
exitCode: 0, exitCode: 0,
@ -118,7 +123,8 @@ func TestToCRIContainerStatus(t *testing.T) {
expectedState: runtime.ContainerState_CONTAINER_EXITED, expectedState: runtime.ContainerState_CONTAINER_EXITED,
expectedReason: completeExitReason, expectedReason: completeExitReason,
}, },
"container exited with non-zero exit code without reason": { {
desc: "container exited with non-zero exit code without reason",
startedAt: time.Now().UnixNano(), startedAt: time.Now().UnixNano(),
finishedAt: time.Now().UnixNano(), finishedAt: time.Now().UnixNano(),
exitCode: 1, exitCode: 1,
@ -127,7 +133,8 @@ func TestToCRIContainerStatus(t *testing.T) {
expectedReason: errorExitReason, expectedReason: errorExitReason,
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
metadata, status, _, expected := getContainerStatusTestData() metadata, status, _, expected := getContainerStatusTestData()
// Update status with test case. // Update status with test case.
@ -151,7 +158,7 @@ func TestToCRIContainerStatus(t *testing.T) {
containerStatus := toCRIContainerStatus(container, containerStatus := toCRIContainerStatus(container,
expected.Image, expected.Image,
expected.ImageRef) expected.ImageRef)
assert.Equal(t, expected, containerStatus, desc) assert.Equal(t, expected, containerStatus, test.desc)
}) })
} }
} }
@ -173,7 +180,8 @@ func TestToCRIContainerInfo(t *testing.T) {
} }
func TestContainerStatus(t *testing.T) { func TestContainerStatus(t *testing.T) {
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
exist bool exist bool
imageExist bool imageExist bool
startedAt int64 startedAt int64
@ -182,18 +190,21 @@ func TestContainerStatus(t *testing.T) {
expectedState runtime.ContainerState expectedState runtime.ContainerState
expectErr bool expectErr bool
}{ }{
"container created": { {
desc: "container created",
exist: true, exist: true,
imageExist: true, imageExist: true,
expectedState: runtime.ContainerState_CONTAINER_CREATED, expectedState: runtime.ContainerState_CONTAINER_CREATED,
}, },
"container running": { {
desc: "container running",
exist: true, exist: true,
imageExist: true, imageExist: true,
startedAt: time.Now().UnixNano(), startedAt: time.Now().UnixNano(),
expectedState: runtime.ContainerState_CONTAINER_RUNNING, expectedState: runtime.ContainerState_CONTAINER_RUNNING,
}, },
"container exited": { {
desc: "container exited",
exist: true, exist: true,
imageExist: true, imageExist: true,
startedAt: time.Now().UnixNano(), startedAt: time.Now().UnixNano(),
@ -201,18 +212,21 @@ func TestContainerStatus(t *testing.T) {
reason: "test-reason", reason: "test-reason",
expectedState: runtime.ContainerState_CONTAINER_EXITED, expectedState: runtime.ContainerState_CONTAINER_EXITED,
}, },
"container not exist": { {
desc: "container not exist",
exist: false, exist: false,
imageExist: true, imageExist: true,
expectErr: true, expectErr: true,
}, },
"image not exist": { {
desc: "image not exist",
exist: false, exist: false,
imageExist: false, imageExist: false,
expectErr: true, expectErr: true,
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
c := newTestCRIService() c := newTestCRIService()
metadata, status, image, expected := getContainerStatusTestData() metadata, status, image, expected := getContainerStatusTestData()
// Update status with test case. // Update status with test case.

View File

@ -28,13 +28,15 @@ import (
func TestWaitContainerStop(t *testing.T) { func TestWaitContainerStop(t *testing.T) {
id := "test-id" id := "test-id"
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
status *containerstore.Status status *containerstore.Status
cancel bool cancel bool
timeout time.Duration timeout time.Duration
expectErr bool expectErr bool
}{ }{
"should return error if timeout exceeds": { {
desc: "should return error if timeout exceeds",
status: &containerstore.Status{ status: &containerstore.Status{
CreatedAt: time.Now().UnixNano(), CreatedAt: time.Now().UnixNano(),
StartedAt: time.Now().UnixNano(), StartedAt: time.Now().UnixNano(),
@ -42,7 +44,8 @@ func TestWaitContainerStop(t *testing.T) {
timeout: 200 * time.Millisecond, timeout: 200 * time.Millisecond,
expectErr: true, expectErr: true,
}, },
"should return error if context is cancelled": { {
desc: "should return error if context is cancelled",
status: &containerstore.Status{ status: &containerstore.Status{
CreatedAt: time.Now().UnixNano(), CreatedAt: time.Now().UnixNano(),
StartedAt: time.Now().UnixNano(), StartedAt: time.Now().UnixNano(),
@ -51,7 +54,8 @@ func TestWaitContainerStop(t *testing.T) {
cancel: true, cancel: true,
expectErr: true, expectErr: true,
}, },
"should not return error if container is stopped before timeout": { {
desc: "should not return error if container is stopped before timeout",
status: &containerstore.Status{ status: &containerstore.Status{
CreatedAt: time.Now().UnixNano(), CreatedAt: time.Now().UnixNano(),
StartedAt: time.Now().UnixNano(), StartedAt: time.Now().UnixNano(),
@ -61,7 +65,8 @@ func TestWaitContainerStop(t *testing.T) {
expectErr: false, expectErr: false,
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
c := newTestCRIService() c := newTestCRIService()
container, err := containerstore.NewContainer( container, err := containerstore.NewContainer(
containerstore.Metadata{ID: id}, containerstore.Metadata{ID: id},
@ -81,7 +86,7 @@ func TestWaitContainerStop(t *testing.T) {
ctx = timeoutCtx ctx = timeoutCtx
} }
err = c.waitContainerStop(ctx, container) err = c.waitContainerStop(ctx, container)
assert.Equal(t, test.expectErr, err != nil, desc) assert.Equal(t, test.expectErr, err != nil, test.desc)
}) })
} }
} }

View File

@ -38,13 +38,15 @@ func TestUpdateOCILinuxResource(t *testing.T) {
} }
return nil return nil
} }
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
spec *runtimespec.Spec spec *runtimespec.Spec
request *runtime.UpdateContainerResourcesRequest request *runtime.UpdateContainerResourcesRequest
expected *runtimespec.Spec expected *runtimespec.Spec
expectErr bool expectErr bool
}{ }{
"should be able to update each resource": { {
desc: "should be able to update each resource",
spec: &runtimespec.Spec{ spec: &runtimespec.Spec{
Process: &runtimespec.Process{OOMScoreAdj: oomscoreadj}, Process: &runtimespec.Process{OOMScoreAdj: oomscoreadj},
Linux: &runtimespec.Linux{ Linux: &runtimespec.Linux{
@ -93,7 +95,8 @@ func TestUpdateOCILinuxResource(t *testing.T) {
}, },
}, },
}, },
"should skip empty fields": { {
desc: "should skip empty fields",
spec: &runtimespec.Spec{ spec: &runtimespec.Spec{
Process: &runtimespec.Process{OOMScoreAdj: oomscoreadj}, Process: &runtimespec.Process{OOMScoreAdj: oomscoreadj},
Linux: &runtimespec.Linux{ Linux: &runtimespec.Linux{
@ -139,7 +142,8 @@ func TestUpdateOCILinuxResource(t *testing.T) {
}, },
}, },
}, },
"should be able to fill empty fields": { {
desc: "should be able to fill empty fields",
spec: &runtimespec.Spec{ spec: &runtimespec.Spec{
Process: &runtimespec.Process{OOMScoreAdj: oomscoreadj}, Process: &runtimespec.Process{OOMScoreAdj: oomscoreadj},
Linux: &runtimespec.Linux{ Linux: &runtimespec.Linux{
@ -180,7 +184,8 @@ func TestUpdateOCILinuxResource(t *testing.T) {
}, },
}, },
}, },
"should be able to patch the unified map": { {
desc: "should be able to patch the unified map",
spec: &runtimespec.Spec{ spec: &runtimespec.Spec{
Process: &runtimespec.Process{OOMScoreAdj: oomscoreadj}, Process: &runtimespec.Process{OOMScoreAdj: oomscoreadj},
Linux: &runtimespec.Linux{ Linux: &runtimespec.Linux{
@ -230,7 +235,8 @@ func TestUpdateOCILinuxResource(t *testing.T) {
}, },
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
config := criconfig.Config{ config := criconfig.Config{
PluginConfig: criconfig.PluginConfig{ PluginConfig: criconfig.PluginConfig{
TolerateMissingHugetlbController: true, TolerateMissingHugetlbController: true,

View File

@ -29,32 +29,38 @@ import (
func TestGetCgroupsPath(t *testing.T) { func TestGetCgroupsPath(t *testing.T) {
testID := "test-id" testID := "test-id"
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
cgroupsParent string cgroupsParent string
expected string expected string
}{ }{
"should support regular cgroup path": { {
desc: "should support regular cgroup path",
cgroupsParent: "/a/b", cgroupsParent: "/a/b",
expected: "/a/b/test-id", expected: "/a/b/test-id",
}, },
"should support systemd cgroup path": { {
desc: "should support systemd cgroup path",
cgroupsParent: "/a.slice/b.slice", cgroupsParent: "/a.slice/b.slice",
expected: "b.slice:cri-containerd:test-id", expected: "b.slice:cri-containerd:test-id"},
}, {
"should support tailing slash for regular cgroup path": { desc: "should support tailing slash for regular cgroup path",
cgroupsParent: "/a/b/", cgroupsParent: "/a/b/",
expected: "/a/b/test-id", expected: "/a/b/test-id",
}, },
"should support tailing slash for systemd cgroup path": { {
desc: "should support tailing slash for systemd cgroup path",
cgroupsParent: "/a.slice/b.slice/", cgroupsParent: "/a.slice/b.slice/",
expected: "b.slice:cri-containerd:test-id", expected: "b.slice:cri-containerd:test-id",
}, },
"should treat root cgroup as regular cgroup path": { {
desc: "should treat root cgroup as regular cgroup path",
cgroupsParent: "/", cgroupsParent: "/",
expected: "/test-id", expected: "/test-id",
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
got := getCgroupsPath(test.cgroupsParent, testID) got := getCgroupsPath(test.cgroupsParent, testID)
assert.Equal(t, test.expected, got) assert.Equal(t, test.expected, got)
}) })

View File

@ -29,18 +29,21 @@ func TestInitSelinuxOpts(t *testing.T) {
t.Skip("selinux is not enabled") t.Skip("selinux is not enabled")
} }
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
selinuxOpt *runtime.SELinuxOption selinuxOpt *runtime.SELinuxOption
processLabel string processLabel string
mountLabel string mountLabel string
expectErr bool expectErr bool
}{ }{
"Should return empty strings for processLabel and mountLabel when selinuxOpt is nil": { {
desc: "Should return empty strings for processLabel and mountLabel when selinuxOpt is nil",
selinuxOpt: nil, selinuxOpt: nil,
processLabel: ".*:c[0-9]{1,3},c[0-9]{1,3}", processLabel: ".*:c[0-9]{1,3},c[0-9]{1,3}",
mountLabel: ".*:c[0-9]{1,3},c[0-9]{1,3}", mountLabel: ".*:c[0-9]{1,3},c[0-9]{1,3}",
}, },
"Should overlay fields on processLabel when selinuxOpt has been initialized partially": { {
desc: "Should overlay fields on processLabel when selinuxOpt has been initialized partially",
selinuxOpt: &runtime.SELinuxOption{ selinuxOpt: &runtime.SELinuxOption{
User: "", User: "",
Role: "user_r", Role: "user_r",
@ -50,7 +53,8 @@ func TestInitSelinuxOpts(t *testing.T) {
processLabel: "system_u:user_r:(container_file_t|svirt_lxc_net_t):s0:c1,c2", processLabel: "system_u:user_r:(container_file_t|svirt_lxc_net_t):s0:c1,c2",
mountLabel: "system_u:object_r:(container_file_t|svirt_sandbox_file_t):s0:c1,c2", mountLabel: "system_u:object_r:(container_file_t|svirt_sandbox_file_t):s0:c1,c2",
}, },
"Should be resolved correctly when selinuxOpt has been initialized completely": { {
desc: "Should be resolved correctly when selinuxOpt has been initialized completely",
selinuxOpt: &runtime.SELinuxOption{ selinuxOpt: &runtime.SELinuxOption{
User: "user_u", User: "user_u",
Role: "user_r", Role: "user_r",
@ -60,7 +64,8 @@ func TestInitSelinuxOpts(t *testing.T) {
processLabel: "user_u:user_r:user_t:s0:c1,c2", processLabel: "user_u:user_r:user_t:s0:c1,c2",
mountLabel: "user_u:object_r:(container_file_t|svirt_sandbox_file_t):s0:c1,c2", mountLabel: "user_u:object_r:(container_file_t|svirt_sandbox_file_t):s0:c1,c2",
}, },
"Should be resolved correctly when selinuxOpt has been initialized with level=''": { {
desc: "Should be resolved correctly when selinuxOpt has been initialized with level=''",
selinuxOpt: &runtime.SELinuxOption{ selinuxOpt: &runtime.SELinuxOption{
User: "user_u", User: "user_u",
Role: "user_r", Role: "user_r",
@ -70,7 +75,8 @@ func TestInitSelinuxOpts(t *testing.T) {
processLabel: "user_u:user_r:user_t:s0:c[0-9]{1,3},c[0-9]{1,3}", processLabel: "user_u:user_r:user_t:s0:c[0-9]{1,3},c[0-9]{1,3}",
mountLabel: "user_u:object_r:(container_file_t|svirt_sandbox_file_t):s0", mountLabel: "user_u:object_r:(container_file_t|svirt_sandbox_file_t):s0",
}, },
"Should return error when the format of 'level' is not correct": { {
desc: "Should return error when the format of 'level' is not correct",
selinuxOpt: &runtime.SELinuxOption{ selinuxOpt: &runtime.SELinuxOption{
User: "user_u", User: "user_u",
Role: "user_r", Role: "user_r",
@ -80,7 +86,8 @@ func TestInitSelinuxOpts(t *testing.T) {
expectErr: true, expectErr: true,
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
processLabel, mountLabel, err := initLabelsFromOpt(test.selinuxOpt) processLabel, mountLabel, err := initLabelsFromOpt(test.selinuxOpt)
if test.expectErr { if test.expectErr {
assert.Error(t, err) assert.Error(t, err)
@ -93,59 +100,75 @@ func TestInitSelinuxOpts(t *testing.T) {
} }
func TestCheckSelinuxLevel(t *testing.T) { func TestCheckSelinuxLevel(t *testing.T) {
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
level string level string
expectNoMatch bool expectNoMatch bool
}{ }{
"s0": { {
desc: "s0",
level: "s0", level: "s0",
}, },
"s0-s0": { {
desc: "s0-s0",
level: "s0-s0", level: "s0-s0",
}, },
"s0:c0": { {
desc: "s0:c0",
level: "s0:c0", level: "s0:c0",
}, },
"s0:c0.c3": { {
desc: "s0:c0.c3",
level: "s0:c0.c3", level: "s0:c0.c3",
}, },
"s0:c0,c3": { {
desc: "s0:c0,c3",
level: "s0:c0,c3", level: "s0:c0,c3",
}, },
"s0-s0:c0,c3": { {
desc: "s0-s0:c0,c3",
level: "s0-s0:c0,c3", level: "s0-s0:c0,c3",
}, },
"s0-s0:c0,c3.c6": { {
desc: "s0-s0:c0,c3.c6",
level: "s0-s0:c0,c3.c6", level: "s0-s0:c0,c3.c6",
}, },
"s0-s0:c0,c3.c6,c8.c10": { {
desc: "s0-s0:c0,c3.c6,c8.c10",
level: "s0-s0:c0,c3.c6,c8.c10", level: "s0-s0:c0,c3.c6,c8.c10",
}, },
"s0-s0:c0,c3.c6,c8,c10": { {
desc: "s0-s0:c0,c3.c6,c8,c10",
level: "s0-s0:c0,c3.c6", level: "s0-s0:c0,c3.c6",
}, },
"s0,c0,c3": { {
desc: "s0,c0,c3",
level: "s0,c0,c3", level: "s0,c0,c3",
expectNoMatch: true, expectNoMatch: true,
}, },
"s0:c0.c3.c6": { {
desc: "s0:c0.c3.c6",
level: "s0:c0.c3.c6", level: "s0:c0.c3.c6",
expectNoMatch: true, expectNoMatch: true,
}, },
"s0-s0,c0,c3": { {
desc: "s0-s0,c0,c3",
level: "s0-s0,c0,c3", level: "s0-s0,c0,c3",
expectNoMatch: true, expectNoMatch: true,
}, },
"s0-s0:c0.c3.c6": { {
desc: "s0-s0:c0.c3.c6",
level: "s0-s0:c0.c3.c6", level: "s0-s0:c0.c3.c6",
expectNoMatch: true, expectNoMatch: true,
}, },
"s0-s0:c0,c3.c6.c8": { {
desc: "s0-s0:c0,c3.c6.c8",
level: "s0-s0:c0,c3.c6.c8", level: "s0-s0:c0,c3.c6.c8",
expectNoMatch: true, expectNoMatch: true,
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
err := checkSelinuxLevel(test.level) err := checkSelinuxLevel(test.level)
if test.expectNoMatch { if test.expectNoMatch {
assert.Error(t, err) assert.Error(t, err)

View File

@ -48,36 +48,44 @@ import (
// TestGetUserFromImage tests the logic of getting image uid or user name of image user. // TestGetUserFromImage tests the logic of getting image uid or user name of image user.
func TestGetUserFromImage(t *testing.T) { func TestGetUserFromImage(t *testing.T) {
newI64 := func(i int64) *int64 { return &i } newI64 := func(i int64) *int64 { return &i }
for c, test := range map[string]struct { for _, test := range []struct {
desc string
user string user string
uid *int64 uid *int64
name string name string
}{ }{
"no gid": { {
desc: "no gid",
user: "0", user: "0",
uid: newI64(0), uid: newI64(0),
}, },
"uid/gid": { {
desc: "uid/gid",
user: "0:1", user: "0:1",
uid: newI64(0), uid: newI64(0),
}, },
"empty user": { {
desc: "empty user",
user: "", user: "",
}, },
"multiple separators": { {
desc: "multiple separators",
user: "1:2:3", user: "1:2:3",
uid: newI64(1), uid: newI64(1),
}, },
"root username": { {
desc: "root username",
user: "root:root", user: "root:root",
name: "root", name: "root",
}, },
"username": { {
desc: "username",
user: "test:test", user: "test:test",
name: "test", name: "test",
}, },
} { } {
t.Run(c, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
actualUID, actualName := getUserFromImage(test.user) actualUID, actualName := getUserFromImage(test.user)
assert.Equal(t, test.uid, actualUID) assert.Equal(t, test.uid, actualUID)
assert.Equal(t, test.name, actualName) assert.Equal(t, test.name, actualName)
@ -87,35 +95,41 @@ func TestGetUserFromImage(t *testing.T) {
func TestGetRepoDigestAndTag(t *testing.T) { func TestGetRepoDigestAndTag(t *testing.T) {
digest := imagedigest.Digest("sha256:e6693c20186f837fc393390135d8a598a96a833917917789d63766cab6c59582") digest := imagedigest.Digest("sha256:e6693c20186f837fc393390135d8a598a96a833917917789d63766cab6c59582")
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
ref string ref string
schema1 bool schema1 bool
expectedRepoDigest string expectedRepoDigest string
expectedRepoTag string expectedRepoTag string
}{ }{
"repo tag should be empty if original ref has no tag": { {
desc: "repo tag should be empty if original ref has no tag",
ref: "gcr.io/library/busybox@" + digest.String(), ref: "gcr.io/library/busybox@" + digest.String(),
expectedRepoDigest: "gcr.io/library/busybox@" + digest.String(), expectedRepoDigest: "gcr.io/library/busybox@" + digest.String(),
}, },
"repo tag should not be empty if original ref has tag": { {
desc: "repo tag should not be empty if original ref has tag",
ref: "gcr.io/library/busybox:latest", ref: "gcr.io/library/busybox:latest",
expectedRepoDigest: "gcr.io/library/busybox@" + digest.String(), expectedRepoDigest: "gcr.io/library/busybox@" + digest.String(),
expectedRepoTag: "gcr.io/library/busybox:latest", expectedRepoTag: "gcr.io/library/busybox:latest",
}, },
"repo digest should be empty if original ref is schema1 and has no digest": { {
desc: "repo digest should be empty if original ref is schema1 and has no digest",
ref: "gcr.io/library/busybox:latest", ref: "gcr.io/library/busybox:latest",
schema1: true, schema1: true,
expectedRepoDigest: "", expectedRepoDigest: "",
expectedRepoTag: "gcr.io/library/busybox:latest", expectedRepoTag: "gcr.io/library/busybox:latest",
}, },
"repo digest should not be empty if original ref is schema1 but has digest": { {
desc: "repo digest should not be empty if original ref is schema1 but has digest",
ref: "gcr.io/library/busybox@sha256:e6693c20186f837fc393390135d8a598a96a833917917789d63766cab6c59594", ref: "gcr.io/library/busybox@sha256:e6693c20186f837fc393390135d8a598a96a833917917789d63766cab6c59594",
schema1: true, schema1: true,
expectedRepoDigest: "gcr.io/library/busybox@sha256:e6693c20186f837fc393390135d8a598a96a833917917789d63766cab6c59594", expectedRepoDigest: "gcr.io/library/busybox@sha256:e6693c20186f837fc393390135d8a598a96a833917917789d63766cab6c59594",
expectedRepoTag: "", expectedRepoTag: "",
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
named, err := docker.ParseDockerRef(test.ref) named, err := docker.ParseDockerRef(test.ref)
assert.NoError(t, err) assert.NoError(t, err)
repoDigest, repoTag := getRepoDigestAndTag(named, digest, test.schema1) repoDigest, repoTag := getRepoDigestAndTag(named, digest, test.schema1)
@ -242,19 +256,22 @@ func TestGenerateRuntimeOptions(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
require.Len(t, nonNilOptsConfig.Runtimes, 3) require.Len(t, nonNilOptsConfig.Runtimes, 3)
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
r criconfig.Runtime r criconfig.Runtime
c criconfig.Config c criconfig.Config
expectedOptions interface{} expectedOptions interface{}
}{ }{
"when options is nil, should return nil option for io.containerd.runc.v2": { {
desc: "when options is nil, should return nil option for io.containerd.runc.v2",
r: nilOptsConfig.Runtimes["runcv2"], r: nilOptsConfig.Runtimes["runcv2"],
c: nilOptsConfig, c: nilOptsConfig,
expectedOptions: nil, expectedOptions: nil,
}, },
"when options is not nil, should be able to decode for io.containerd.runc.v2": { {
r: nonNilOptsConfig.Runtimes["runcv2"], desc: "when options is not nil, should be able to decode for io.containerd.runc.v2",
c: nonNilOptsConfig, r: nonNilOptsConfig.Runtimes["runcv2"],
c: nonNilOptsConfig,
expectedOptions: &runcoptions.Options{ expectedOptions: &runcoptions.Options{
BinaryName: "runc", BinaryName: "runc",
Root: "/runcv2", Root: "/runcv2",
@ -262,7 +279,8 @@ func TestGenerateRuntimeOptions(t *testing.T) {
}, },
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
opts, err := generateRuntimeOptions(test.r, test.c) opts, err := generateRuntimeOptions(test.r, test.c)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, test.expectedOptions, opts) assert.Equal(t, test.expectedOptions, opts)
@ -271,18 +289,21 @@ func TestGenerateRuntimeOptions(t *testing.T) {
} }
func TestEnvDeduplication(t *testing.T) { func TestEnvDeduplication(t *testing.T) {
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
existing []string existing []string
kv [][2]string kv [][2]string
expected []string expected []string
}{ }{
"single env": { {
desc: "single env",
kv: [][2]string{ kv: [][2]string{
{"a", "b"}, {"a", "b"},
}, },
expected: []string{"a=b"}, expected: []string{"a=b"},
}, },
"multiple envs": { {
desc: "multiple envs",
kv: [][2]string{ kv: [][2]string{
{"a", "b"}, {"a", "b"},
{"c", "d"}, {"c", "d"},
@ -294,7 +315,8 @@ func TestEnvDeduplication(t *testing.T) {
"e=f", "e=f",
}, },
}, },
"env override": { {
desc: "env override",
kv: [][2]string{ kv: [][2]string{
{"k1", "v1"}, {"k1", "v1"},
{"k2", "v2"}, {"k2", "v2"},
@ -310,7 +332,8 @@ func TestEnvDeduplication(t *testing.T) {
"k4=v6", "k4=v6",
}, },
}, },
"existing env": { {
desc: "existing env",
existing: []string{ existing: []string{
"k1=v1", "k1=v1",
"k2=v2", "k2=v2",
@ -329,7 +352,8 @@ func TestEnvDeduplication(t *testing.T) {
}, },
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
var spec runtimespec.Spec var spec runtimespec.Spec
if len(test.existing) > 0 { if len(test.existing) > 0 {
spec.Process = &runtimespec.Process{ spec.Process = &runtimespec.Process{
@ -345,17 +369,20 @@ func TestEnvDeduplication(t *testing.T) {
} }
func TestPassThroughAnnotationsFilter(t *testing.T) { func TestPassThroughAnnotationsFilter(t *testing.T) {
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
podAnnotations map[string]string podAnnotations map[string]string
runtimePodAnnotations []string runtimePodAnnotations []string
passthroughAnnotations map[string]string passthroughAnnotations map[string]string
}{ }{
"should support direct match": { {
desc: "should support direct match",
podAnnotations: map[string]string{"c": "d", "d": "e"}, podAnnotations: map[string]string{"c": "d", "d": "e"},
runtimePodAnnotations: []string{"c"}, runtimePodAnnotations: []string{"c"},
passthroughAnnotations: map[string]string{"c": "d"}, passthroughAnnotations: map[string]string{"c": "d"},
}, },
"should support wildcard match": { {
desc: "should support wildcard match",
podAnnotations: map[string]string{ podAnnotations: map[string]string{
"t.f": "j", "t.f": "j",
"z.g": "o", "z.g": "o",
@ -370,7 +397,8 @@ func TestPassThroughAnnotationsFilter(t *testing.T) {
"y.ca": "b", "y.ca": "b",
}, },
}, },
"should support wildcard match all": { {
desc: "should support wildcard match all",
podAnnotations: map[string]string{ podAnnotations: map[string]string{
"t.f": "j", "t.f": "j",
"z.g": "o", "z.g": "o",
@ -387,7 +415,8 @@ func TestPassThroughAnnotationsFilter(t *testing.T) {
"y": "b", "y": "b",
}, },
}, },
"should support match including path separator": { {
desc: "should support match including path separator",
podAnnotations: map[string]string{ podAnnotations: map[string]string{
"matchend.com/end": "1", "matchend.com/end": "1",
"matchend.com/end1": "2", "matchend.com/end1": "2",
@ -446,7 +475,8 @@ func TestPassThroughAnnotationsFilter(t *testing.T) {
}, },
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
passthroughAnnotations := getPassthroughAnnotations(test.podAnnotations, test.runtimePodAnnotations) passthroughAnnotations := getPassthroughAnnotations(test.podAnnotations, test.runtimePodAnnotations)
assert.Equal(t, test.passthroughAnnotations, passthroughAnnotations) assert.Equal(t, test.passthroughAnnotations, passthroughAnnotations)
}) })
@ -534,28 +564,34 @@ func TestValidateTargetContainer(t *testing.T) {
err = addContainer(c, testOtherContainerID, testOtherContainerSandboxID, testOtherContainerPID, createdAt, startedAt, 0) err = addContainer(c, testOtherContainerID, testOtherContainerSandboxID, testOtherContainerPID, createdAt, startedAt, 0)
require.NoError(t, err, "error creating test container in other pod") require.NoError(t, err, "error creating test container in other pod")
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
targetContainerID string targetContainerID string
expectError bool expectError bool
}{ }{
"target container in pod": { {
desc: "target container in pod",
targetContainerID: testTargetContainerID, targetContainerID: testTargetContainerID,
expectError: false, expectError: false,
}, },
"target stopped container in pod": { {
desc: "target stopped container in pod",
targetContainerID: testStoppedContainerID, targetContainerID: testStoppedContainerID,
expectError: true, expectError: true,
}, },
"target container does not exist": { {
desc: "target container does not exist",
targetContainerID: "no-container-with-this-id", targetContainerID: "no-container-with-this-id",
expectError: true, expectError: true,
}, },
"target container in other pod": { {
desc: "target container in other pod",
targetContainerID: testOtherContainerID, targetContainerID: testOtherContainerID,
expectError: true, expectError: true,
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
targetContainer, err := c.validateTargetContainer(testSandboxID, test.targetContainerID) targetContainer, err := c.validateTargetContainer(testSandboxID, test.targetContainerID)
if test.expectError { if test.expectError {
require.Error(t, err, "target should have been invalid but no error") require.Error(t, err, "target should have been invalid but no error")
@ -617,6 +653,7 @@ func TestHostNetwork(t *testing.T) {
if goruntime.GOOS != "linux" { if goruntime.GOOS != "linux" {
t.Skip() t.Skip()
} }
tt := tt
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
if hostNetwork(tt.c) != tt.expected { if hostNetwork(tt.c) != tt.expected {
t.Errorf("failed hostNetwork got %t expected %t", hostNetwork(tt.c), tt.expected) t.Errorf("failed hostNetwork got %t expected %t", hostNetwork(tt.c), tt.expected)

View File

@ -37,23 +37,29 @@ func TestParseAuth(t *testing.T) {
base64.StdEncoding.Encode(testAuth, []byte(testUser+":"+testPasswd)) base64.StdEncoding.Encode(testAuth, []byte(testUser+":"+testPasswd))
invalidAuth := make([]byte, testAuthLen) invalidAuth := make([]byte, testAuthLen)
base64.StdEncoding.Encode(invalidAuth, []byte(testUser+"@"+testPasswd)) base64.StdEncoding.Encode(invalidAuth, []byte(testUser+"@"+testPasswd))
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
auth *runtime.AuthConfig auth *runtime.AuthConfig
host string host string
expectedUser string expectedUser string
expectedSecret string expectedSecret string
expectErr bool expectErr bool
}{ }{
"should not return error if auth config is nil": {}, {
"should not return error if empty auth is provided for access to anonymous registry": { desc: "should not return error if auth config is nil",
},
{
desc: "should not return error if empty auth is provided for access to anonymous registry",
auth: &runtime.AuthConfig{}, auth: &runtime.AuthConfig{},
expectErr: false, expectErr: false,
}, },
"should support identity token": { {
desc: "should support identity token",
auth: &runtime.AuthConfig{IdentityToken: "abcd"}, auth: &runtime.AuthConfig{IdentityToken: "abcd"},
expectedSecret: "abcd", expectedSecret: "abcd",
}, },
"should support username and password": { {
desc: "should support username and password",
auth: &runtime.AuthConfig{ auth: &runtime.AuthConfig{
Username: testUser, Username: testUser,
Password: testPasswd, Password: testPasswd,
@ -61,16 +67,19 @@ func TestParseAuth(t *testing.T) {
expectedUser: testUser, expectedUser: testUser,
expectedSecret: testPasswd, expectedSecret: testPasswd,
}, },
"should support auth": { {
desc: "should support auth",
auth: &runtime.AuthConfig{Auth: string(testAuth)}, auth: &runtime.AuthConfig{Auth: string(testAuth)},
expectedUser: testUser, expectedUser: testUser,
expectedSecret: testPasswd, expectedSecret: testPasswd,
}, },
"should return error for invalid auth": { {
desc: "should return error for invalid auth",
auth: &runtime.AuthConfig{Auth: string(invalidAuth)}, auth: &runtime.AuthConfig{Auth: string(invalidAuth)},
expectErr: true, expectErr: true,
}, },
"should return empty auth if server address doesn't match": { {
desc: "should return empty auth if server address doesn't match",
auth: &runtime.AuthConfig{ auth: &runtime.AuthConfig{
Username: testUser, Username: testUser,
Password: testPasswd, Password: testPasswd,
@ -80,7 +89,8 @@ func TestParseAuth(t *testing.T) {
expectedUser: "", expectedUser: "",
expectedSecret: "", expectedSecret: "",
}, },
"should return auth if server address matches": { {
desc: "should return auth if server address matches",
auth: &runtime.AuthConfig{ auth: &runtime.AuthConfig{
Username: testUser, Username: testUser,
Password: testPasswd, Password: testPasswd,
@ -90,7 +100,8 @@ func TestParseAuth(t *testing.T) {
expectedUser: testUser, expectedUser: testUser,
expectedSecret: testPasswd, expectedSecret: testPasswd,
}, },
"should return auth if server address is not specified": { {
desc: "should return auth if server address is not specified",
auth: &runtime.AuthConfig{ auth: &runtime.AuthConfig{
Username: testUser, Username: testUser,
Password: testPasswd, Password: testPasswd,
@ -100,7 +111,8 @@ func TestParseAuth(t *testing.T) {
expectedSecret: testPasswd, expectedSecret: testPasswd,
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
u, s, err := ParseAuth(test.auth, test.host) u, s, err := ParseAuth(test.auth, test.host)
assert.Equal(t, test.expectErr, err != nil) assert.Equal(t, test.expectErr, err != nil)
assert.Equal(t, test.expectedUser, u) assert.Equal(t, test.expectedUser, u)
@ -110,12 +122,14 @@ func TestParseAuth(t *testing.T) {
} }
func TestRegistryEndpoints(t *testing.T) { func TestRegistryEndpoints(t *testing.T) {
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
mirrors map[string]criconfig.Mirror mirrors map[string]criconfig.Mirror
host string host string
expected []string expected []string
}{ }{
"no mirror configured": { {
desc: "no mirror configured",
mirrors: map[string]criconfig.Mirror{ mirrors: map[string]criconfig.Mirror{
"registry-1.io": { "registry-1.io": {
Endpoints: []string{ Endpoints: []string{
@ -129,7 +143,8 @@ func TestRegistryEndpoints(t *testing.T) {
"https://registry-3.io", "https://registry-3.io",
}, },
}, },
"mirror configured": { {
desc: "mirror configured",
mirrors: map[string]criconfig.Mirror{ mirrors: map[string]criconfig.Mirror{
"registry-3.io": { "registry-3.io": {
Endpoints: []string{ Endpoints: []string{
@ -145,7 +160,8 @@ func TestRegistryEndpoints(t *testing.T) {
"https://registry-3.io", "https://registry-3.io",
}, },
}, },
"wildcard mirror configured": { {
desc: "wildcard mirror configured",
mirrors: map[string]criconfig.Mirror{ mirrors: map[string]criconfig.Mirror{
"*": { "*": {
Endpoints: []string{ Endpoints: []string{
@ -161,7 +177,8 @@ func TestRegistryEndpoints(t *testing.T) {
"https://registry-3.io", "https://registry-3.io",
}, },
}, },
"host should take precedence if both host and wildcard mirrors are configured": { {
desc: "host should take precedence if both host and wildcard mirrors are configured",
mirrors: map[string]criconfig.Mirror{ mirrors: map[string]criconfig.Mirror{
"*": { "*": {
Endpoints: []string{ Endpoints: []string{
@ -180,7 +197,8 @@ func TestRegistryEndpoints(t *testing.T) {
"https://registry-3.io", "https://registry-3.io",
}, },
}, },
"default endpoint in list with http": { {
desc: "default endpoint in list with http",
mirrors: map[string]criconfig.Mirror{ mirrors: map[string]criconfig.Mirror{
"registry-3.io": { "registry-3.io": {
Endpoints: []string{ Endpoints: []string{
@ -197,7 +215,8 @@ func TestRegistryEndpoints(t *testing.T) {
"http://registry-3.io", "http://registry-3.io",
}, },
}, },
"default endpoint in list with https": { {
desc: "default endpoint in list with https",
mirrors: map[string]criconfig.Mirror{ mirrors: map[string]criconfig.Mirror{
"registry-3.io": { "registry-3.io": {
Endpoints: []string{ Endpoints: []string{
@ -214,7 +233,8 @@ func TestRegistryEndpoints(t *testing.T) {
"https://registry-3.io", "https://registry-3.io",
}, },
}, },
"default endpoint in list with path": { {
desc: "default endpoint in list with path",
mirrors: map[string]criconfig.Mirror{ mirrors: map[string]criconfig.Mirror{
"registry-3.io": { "registry-3.io": {
Endpoints: []string{ Endpoints: []string{
@ -231,7 +251,8 @@ func TestRegistryEndpoints(t *testing.T) {
"https://registry-3.io/path", "https://registry-3.io/path",
}, },
}, },
"miss scheme endpoint in list with path": { {
desc: "miss scheme endpoint in list with path",
mirrors: map[string]criconfig.Mirror{ mirrors: map[string]criconfig.Mirror{
"registry-3.io": { "registry-3.io": {
Endpoints: []string{ Endpoints: []string{
@ -249,7 +270,8 @@ func TestRegistryEndpoints(t *testing.T) {
}, },
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
c := newTestCRIService() c := newTestCRIService()
c.config.Registry.Mirrors = test.mirrors c.config.Registry.Mirrors = test.mirrors
got, err := c.registryEndpoints(test.host) got, err := c.registryEndpoints(test.host)
@ -260,52 +282,64 @@ func TestRegistryEndpoints(t *testing.T) {
} }
func TestDefaultScheme(t *testing.T) { func TestDefaultScheme(t *testing.T) {
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
host string host string
expected string expected string
}{ }{
"should use http by default for localhost": { {
desc: "should use http by default for localhost",
host: "localhost", host: "localhost",
expected: "http", expected: "http",
}, },
"should use http by default for localhost with port": { {
desc: "should use http by default for localhost with port",
host: "localhost:8080", host: "localhost:8080",
expected: "http", expected: "http",
}, },
"should use http by default for 127.0.0.1": { {
desc: "should use http by default for 127.0.0.1",
host: "127.0.0.1", host: "127.0.0.1",
expected: "http", expected: "http",
}, },
"should use http by default for 127.0.0.1 with port": { {
desc: "should use http by default for 127.0.0.1 with port",
host: "127.0.0.1:8080", host: "127.0.0.1:8080",
expected: "http", expected: "http",
}, },
"should use http by default for ::1": { {
desc: "should use http by default for ::1",
host: "::1", host: "::1",
expected: "http", expected: "http",
}, },
"should use http by default for ::1 with port": { {
desc: "should use http by default for ::1 with port",
host: "[::1]:8080", host: "[::1]:8080",
expected: "http", expected: "http",
}, },
"should use https by default for remote host": { {
desc: "should use https by default for remote host",
host: "remote", host: "remote",
expected: "https", expected: "https",
}, },
"should use https by default for remote host with port": { {
desc: "should use https by default for remote host with port",
host: "remote:8080", host: "remote:8080",
expected: "https", expected: "https",
}, },
"should use https by default for remote ip": { {
desc: "should use https by default for remote ip",
host: "8.8.8.8", host: "8.8.8.8",
expected: "https", expected: "https",
}, },
"should use https by default for remote ip with port": { {
desc: "should use https by default for remote ip with port",
host: "8.8.8.8:8080", host: "8.8.8.8:8080",
expected: "https", expected: "https",
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
got := defaultScheme(test.host) got := defaultScheme(test.host)
assert.Equal(t, test.expected, got) assert.Equal(t, test.expected, got)
}) })
@ -313,20 +347,24 @@ func TestDefaultScheme(t *testing.T) {
} }
func TestEncryptedImagePullOpts(t *testing.T) { func TestEncryptedImagePullOpts(t *testing.T) {
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
keyModel string keyModel string
expectedOpts int expectedOpts int
}{ }{
"node key model should return one unpack opt": { {
desc: "node key model should return one unpack opt",
keyModel: criconfig.KeyModelNode, keyModel: criconfig.KeyModelNode,
expectedOpts: 1, expectedOpts: 1,
}, },
"no key model selected should default to node key model": { {
desc: "no key model selected should default to node key model",
keyModel: "", keyModel: "",
expectedOpts: 0, expectedOpts: 0,
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
c := newTestCRIService() c := newTestCRIService()
c.config.ImageDecryption.KeyModel = test.keyModel c.config.ImageDecryption.KeyModel = test.keyModel
got := len(c.encryptedImagesPullOpts()) got := len(c.encryptedImagesPullOpts())
@ -382,6 +420,7 @@ func TestSnapshotterFromPodSandboxConfig(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
tt := tt
t.Run(tt.desc, func(t *testing.T) { t.Run(tt.desc, func(t *testing.T) {
cri := newTestCRIService() cri := newTestCRIService()
cri.config.ContainerdConfig.Snapshotter = defaultSnashotter cri.config.ContainerdConfig.Snapshotter = defaultSnashotter

View File

@ -53,31 +53,36 @@ func TestToCRISandbox(t *testing.T) {
Annotations: config.GetAnnotations(), Annotations: config.GetAnnotations(),
RuntimeHandler: "test-runtime-handler", RuntimeHandler: "test-runtime-handler",
} }
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
state sandboxstore.State state sandboxstore.State
expectedState runtime.PodSandboxState expectedState runtime.PodSandboxState
}{ }{
"sandbox state ready": { {
desc: "sandbox state ready",
state: sandboxstore.StateReady, state: sandboxstore.StateReady,
expectedState: runtime.PodSandboxState_SANDBOX_READY, expectedState: runtime.PodSandboxState_SANDBOX_READY,
}, },
"sandbox state not ready": { {
desc: "sandbox state not ready",
state: sandboxstore.StateNotReady, state: sandboxstore.StateNotReady,
expectedState: runtime.PodSandboxState_SANDBOX_NOTREADY, expectedState: runtime.PodSandboxState_SANDBOX_NOTREADY,
}, },
"sandbox state unknown": { {
desc: "sandbox state unknown",
state: sandboxstore.StateUnknown, state: sandboxstore.StateUnknown,
expectedState: runtime.PodSandboxState_SANDBOX_NOTREADY, expectedState: runtime.PodSandboxState_SANDBOX_NOTREADY,
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
status := sandboxstore.Status{ status := sandboxstore.Status{
CreatedAt: createdAt, CreatedAt: createdAt,
State: test.state, State: test.state,
} }
expect.State = test.expectedState expect.State = test.expectedState
s := toCRISandbox(meta, status) s := toCRISandbox(meta, status)
assert.Equal(t, expect, s, desc) assert.Equal(t, expect, s, test.desc)
}) })
} }
} }
@ -157,22 +162,27 @@ func TestFilterSandboxes(t *testing.T) {
assert.NoError(t, c.sandboxStore.Add(sb)) assert.NoError(t, c.sandboxStore.Add(sb))
} }
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
filter *runtime.PodSandboxFilter filter *runtime.PodSandboxFilter
expect []*runtime.PodSandbox expect []*runtime.PodSandbox
}{ }{
"no filter": { {
desc: "no filter",
expect: testSandboxes, expect: testSandboxes,
}, },
"id filter": { {
desc: "id filter",
filter: &runtime.PodSandboxFilter{Id: "2abcdef"}, filter: &runtime.PodSandboxFilter{Id: "2abcdef"},
expect: []*runtime.PodSandbox{testSandboxes[1]}, expect: []*runtime.PodSandbox{testSandboxes[1]},
}, },
"truncid filter": { {
desc: "truncid filter",
filter: &runtime.PodSandboxFilter{Id: "2"}, filter: &runtime.PodSandboxFilter{Id: "2"},
expect: []*runtime.PodSandbox{testSandboxes[1]}, expect: []*runtime.PodSandbox{testSandboxes[1]},
}, },
"state filter": { {
desc: "state filter",
filter: &runtime.PodSandboxFilter{ filter: &runtime.PodSandboxFilter{
State: &runtime.PodSandboxStateValue{ State: &runtime.PodSandboxStateValue{
State: runtime.PodSandboxState_SANDBOX_READY, State: runtime.PodSandboxState_SANDBOX_READY,
@ -180,20 +190,23 @@ func TestFilterSandboxes(t *testing.T) {
}, },
expect: []*runtime.PodSandbox{testSandboxes[0], testSandboxes[2]}, expect: []*runtime.PodSandbox{testSandboxes[0], testSandboxes[2]},
}, },
"label filter": { {
desc: "label filter",
filter: &runtime.PodSandboxFilter{ filter: &runtime.PodSandboxFilter{
LabelSelector: map[string]string{"a": "b"}, LabelSelector: map[string]string{"a": "b"},
}, },
expect: []*runtime.PodSandbox{testSandboxes[1]}, expect: []*runtime.PodSandbox{testSandboxes[1]},
}, },
"mixed filter not matched": { {
desc: "mixed filter not matched",
filter: &runtime.PodSandboxFilter{ filter: &runtime.PodSandboxFilter{
Id: "1", Id: "1",
LabelSelector: map[string]string{"a": "b"}, LabelSelector: map[string]string{"a": "b"},
}, },
expect: []*runtime.PodSandbox{}, expect: []*runtime.PodSandbox{},
}, },
"mixed filter matched": { {
desc: "mixed filter matched",
filter: &runtime.PodSandboxFilter{ filter: &runtime.PodSandboxFilter{
State: &runtime.PodSandboxStateValue{ State: &runtime.PodSandboxStateValue{
State: runtime.PodSandboxState_SANDBOX_READY, State: runtime.PodSandboxState_SANDBOX_READY,
@ -203,9 +216,10 @@ func TestFilterSandboxes(t *testing.T) {
expect: []*runtime.PodSandbox{testSandboxes[2]}, expect: []*runtime.PodSandbox{testSandboxes[2]},
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
filtered := c.filterCRISandboxes(testSandboxes, test.filter) filtered := c.filterCRISandboxes(testSandboxes, test.filter)
assert.Equal(t, test.expect, filtered, desc) assert.Equal(t, test.expect, filtered, test.desc)
}) })
} }
} }

View File

@ -117,12 +117,14 @@ func TestLinuxSandboxContainerSpec(t *testing.T) {
Size: 10, Size: 10,
} }
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
configChange func(*runtime.PodSandboxConfig) configChange func(*runtime.PodSandboxConfig)
specCheck func(*testing.T, *runtimespec.Spec) specCheck func(*testing.T, *runtimespec.Spec)
expectErr bool expectErr bool
}{ }{
"spec should reflect original config": { {
desc: "spec should reflect original config",
specCheck: func(t *testing.T, spec *runtimespec.Spec) { specCheck: func(t *testing.T, spec *runtimespec.Spec) {
// runtime spec should have expected namespaces enabled by default. // runtime spec should have expected namespaces enabled by default.
require.NotNil(t, spec.Linux) require.NotNil(t, spec.Linux)
@ -146,7 +148,8 @@ func TestLinuxSandboxContainerSpec(t *testing.T) {
}) })
}, },
}, },
"host namespace": { {
desc: "host namespace",
configChange: func(c *runtime.PodSandboxConfig) { configChange: func(c *runtime.PodSandboxConfig) {
c.Linux.SecurityContext = &runtime.LinuxSandboxSecurityContext{ c.Linux.SecurityContext = &runtime.LinuxSandboxSecurityContext{
NamespaceOptions: &runtime.NamespaceOption{ NamespaceOptions: &runtime.NamespaceOption{
@ -178,7 +181,8 @@ func TestLinuxSandboxContainerSpec(t *testing.T) {
assert.NotContains(t, spec.Linux.Sysctl["net.ipv4.ping_group_range"], "0 2147483647") assert.NotContains(t, spec.Linux.Sysctl["net.ipv4.ping_group_range"], "0 2147483647")
}, },
}, },
"user namespace": { {
desc: "user namespace",
configChange: func(c *runtime.PodSandboxConfig) { configChange: func(c *runtime.PodSandboxConfig) {
c.Linux.SecurityContext = &runtime.LinuxSandboxSecurityContext{ c.Linux.SecurityContext = &runtime.LinuxSandboxSecurityContext{
NamespaceOptions: &runtime.NamespaceOption{ NamespaceOptions: &runtime.NamespaceOption{
@ -200,7 +204,8 @@ func TestLinuxSandboxContainerSpec(t *testing.T) {
}, },
}, },
"user namespace mode node and mappings": { {
desc: "user namespace mode node and mappings",
configChange: func(c *runtime.PodSandboxConfig) { configChange: func(c *runtime.PodSandboxConfig) {
c.Linux.SecurityContext = &runtime.LinuxSandboxSecurityContext{ c.Linux.SecurityContext = &runtime.LinuxSandboxSecurityContext{
NamespaceOptions: &runtime.NamespaceOption{ NamespaceOptions: &runtime.NamespaceOption{
@ -214,7 +219,8 @@ func TestLinuxSandboxContainerSpec(t *testing.T) {
}, },
expectErr: true, expectErr: true,
}, },
"user namespace with several mappings": { {
desc: "user namespace with several mappings",
configChange: func(c *runtime.PodSandboxConfig) { configChange: func(c *runtime.PodSandboxConfig) {
c.Linux.SecurityContext = &runtime.LinuxSandboxSecurityContext{ c.Linux.SecurityContext = &runtime.LinuxSandboxSecurityContext{
NamespaceOptions: &runtime.NamespaceOption{ NamespaceOptions: &runtime.NamespaceOption{
@ -228,7 +234,8 @@ func TestLinuxSandboxContainerSpec(t *testing.T) {
}, },
expectErr: true, expectErr: true,
}, },
"user namespace with uneven mappings": { {
desc: "user namespace with uneven mappings",
configChange: func(c *runtime.PodSandboxConfig) { configChange: func(c *runtime.PodSandboxConfig) {
c.Linux.SecurityContext = &runtime.LinuxSandboxSecurityContext{ c.Linux.SecurityContext = &runtime.LinuxSandboxSecurityContext{
NamespaceOptions: &runtime.NamespaceOption{ NamespaceOptions: &runtime.NamespaceOption{
@ -242,7 +249,8 @@ func TestLinuxSandboxContainerSpec(t *testing.T) {
}, },
expectErr: true, expectErr: true,
}, },
"user namespace mode container": { {
desc: "user namespace mode container",
configChange: func(c *runtime.PodSandboxConfig) { configChange: func(c *runtime.PodSandboxConfig) {
c.Linux.SecurityContext = &runtime.LinuxSandboxSecurityContext{ c.Linux.SecurityContext = &runtime.LinuxSandboxSecurityContext{
NamespaceOptions: &runtime.NamespaceOption{ NamespaceOptions: &runtime.NamespaceOption{
@ -254,7 +262,8 @@ func TestLinuxSandboxContainerSpec(t *testing.T) {
}, },
expectErr: true, expectErr: true,
}, },
"user namespace mode target": { {
desc: "user namespace mode target",
configChange: func(c *runtime.PodSandboxConfig) { configChange: func(c *runtime.PodSandboxConfig) {
c.Linux.SecurityContext = &runtime.LinuxSandboxSecurityContext{ c.Linux.SecurityContext = &runtime.LinuxSandboxSecurityContext{
NamespaceOptions: &runtime.NamespaceOption{ NamespaceOptions: &runtime.NamespaceOption{
@ -266,7 +275,8 @@ func TestLinuxSandboxContainerSpec(t *testing.T) {
}, },
expectErr: true, expectErr: true,
}, },
"user namespace unknown mode": { {
desc: "user namespace unknown mode",
configChange: func(c *runtime.PodSandboxConfig) { configChange: func(c *runtime.PodSandboxConfig) {
c.Linux.SecurityContext = &runtime.LinuxSandboxSecurityContext{ c.Linux.SecurityContext = &runtime.LinuxSandboxSecurityContext{
NamespaceOptions: &runtime.NamespaceOption{ NamespaceOptions: &runtime.NamespaceOption{
@ -278,7 +288,8 @@ func TestLinuxSandboxContainerSpec(t *testing.T) {
}, },
expectErr: true, expectErr: true,
}, },
"should set supplemental groups correctly": { {
desc: "should set supplemental groups correctly",
configChange: func(c *runtime.PodSandboxConfig) { configChange: func(c *runtime.PodSandboxConfig) {
c.Linux.SecurityContext = &runtime.LinuxSandboxSecurityContext{ c.Linux.SecurityContext = &runtime.LinuxSandboxSecurityContext{
SupplementalGroups: []int64{1111, 2222}, SupplementalGroups: []int64{1111, 2222},
@ -290,7 +301,8 @@ func TestLinuxSandboxContainerSpec(t *testing.T) {
assert.Contains(t, spec.Process.User.AdditionalGids, uint32(2222)) assert.Contains(t, spec.Process.User.AdditionalGids, uint32(2222))
}, },
}, },
"should overwrite default sysctls": { {
desc: "should overwrite default sysctls",
configChange: func(c *runtime.PodSandboxConfig) { configChange: func(c *runtime.PodSandboxConfig) {
c.Linux.Sysctls = map[string]string{ c.Linux.Sysctls = map[string]string{
"net.ipv4.ip_unprivileged_port_start": "500", "net.ipv4.ip_unprivileged_port_start": "500",
@ -303,7 +315,8 @@ func TestLinuxSandboxContainerSpec(t *testing.T) {
assert.Contains(t, spec.Linux.Sysctl["net.ipv4.ping_group_range"], "1 1000") assert.Contains(t, spec.Linux.Sysctl["net.ipv4.ping_group_range"], "1 1000")
}, },
}, },
"sandbox sizing annotations should be set if LinuxContainerResources were provided": { {
desc: "sandbox sizing annotations should be set if LinuxContainerResources were provided",
configChange: func(c *runtime.PodSandboxConfig) { configChange: func(c *runtime.PodSandboxConfig) {
c.Linux.Resources = &v1.LinuxContainerResources{ c.Linux.Resources = &v1.LinuxContainerResources{
CpuPeriod: 100, CpuPeriod: 100,
@ -331,7 +344,8 @@ func TestLinuxSandboxContainerSpec(t *testing.T) {
assert.EqualValues(t, "1024", value) assert.EqualValues(t, "1024", value)
}, },
}, },
"sandbox sizing annotations should not be set if LinuxContainerResources were not provided": { {
desc: "sandbox sizing annotations should not be set if LinuxContainerResources were not provided",
specCheck: func(t *testing.T, spec *runtimespec.Spec) { specCheck: func(t *testing.T, spec *runtimespec.Spec) {
_, ok := spec.Annotations[annotations.SandboxCPUPeriod] _, ok := spec.Annotations[annotations.SandboxCPUPeriod]
assert.False(t, ok) assert.False(t, ok)
@ -343,7 +357,8 @@ func TestLinuxSandboxContainerSpec(t *testing.T) {
assert.False(t, ok) assert.False(t, ok)
}, },
}, },
"sandbox sizing annotations are zero if the resources are set to 0": { {
desc: "sandbox sizing annotations are zero if the resources are set to 0",
configChange: func(c *runtime.PodSandboxConfig) { configChange: func(c *runtime.PodSandboxConfig) {
c.Linux.Resources = &v1.LinuxContainerResources{} c.Linux.Resources = &v1.LinuxContainerResources{}
}, },
@ -363,7 +378,8 @@ func TestLinuxSandboxContainerSpec(t *testing.T) {
}, },
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
c := newTestCRIService() c := newTestCRIService()
c.config.EnableUnprivilegedICMP = true c.config.EnableUnprivilegedICMP = true
c.config.EnableUnprivilegedPorts = true c.config.EnableUnprivilegedPorts = true
@ -392,13 +408,15 @@ func TestSetupSandboxFiles(t *testing.T) {
testID = "test-id" testID = "test-id"
realhostname = "test-real-hostname" realhostname = "test-real-hostname"
) )
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
dnsConfig *runtime.DNSConfig dnsConfig *runtime.DNSConfig
hostname string hostname string
ipcMode runtime.NamespaceMode ipcMode runtime.NamespaceMode
expectedCalls []ostesting.CalledDetail expectedCalls []ostesting.CalledDetail
}{ }{
"should check host /dev/shm existence when ipc mode is NODE": { {
desc: "should check host /dev/shm existence when ipc mode is NODE",
ipcMode: runtime.NamespaceMode_NODE, ipcMode: runtime.NamespaceMode_NODE,
expectedCalls: []ostesting.CalledDetail{ expectedCalls: []ostesting.CalledDetail{
{ {
@ -434,7 +452,8 @@ func TestSetupSandboxFiles(t *testing.T) {
}, },
}, },
}, },
"should create new /etc/resolv.conf if DNSOptions is set": { {
desc: "should create new /etc/resolv.conf if DNSOptions is set",
dnsConfig: &runtime.DNSConfig{ dnsConfig: &runtime.DNSConfig{
Servers: []string{"8.8.8.8"}, Servers: []string{"8.8.8.8"},
Searches: []string{"114.114.114.114"}, Searches: []string{"114.114.114.114"},
@ -477,7 +496,8 @@ options timeout:1
}, },
}, },
}, },
"should create sandbox shm when ipc namespace mode is not NODE": { {
desc: "should create sandbox shm when ipc namespace mode is not NODE",
ipcMode: runtime.NamespaceMode_POD, ipcMode: runtime.NamespaceMode_POD,
expectedCalls: []ostesting.CalledDetail{ expectedCalls: []ostesting.CalledDetail{
{ {
@ -520,7 +540,8 @@ options timeout:1
}, },
}, },
}, },
"should create /etc/hostname when hostname is set": { {
desc: "should create /etc/hostname when hostname is set",
hostname: "test-hostname", hostname: "test-hostname",
ipcMode: runtime.NamespaceMode_NODE, ipcMode: runtime.NamespaceMode_NODE,
expectedCalls: []ostesting.CalledDetail{ expectedCalls: []ostesting.CalledDetail{
@ -555,7 +576,8 @@ options timeout:1
}, },
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
c := newTestCRIService() c := newTestCRIService()
c.os.(*ostesting.FakeOS).HostnameFn = func() (string, error) { c.os.(*ostesting.FakeOS).HostnameFn = func() (string, error) {
return realhostname, nil return realhostname, nil
@ -586,15 +608,19 @@ options timeout:1
} }
func TestParseDNSOption(t *testing.T) { func TestParseDNSOption(t *testing.T) {
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
servers []string servers []string
searches []string searches []string
options []string options []string
expectedContent string expectedContent string
expectErr bool expectErr bool
}{ }{
"empty dns options should return empty content": {}, {
"non-empty dns options should return correct content": { desc: "empty dns options should return empty content",
},
{
desc: "non-empty dns options should return correct content",
servers: []string{"8.8.8.8", "server.google.com"}, servers: []string{"8.8.8.8", "server.google.com"},
searches: []string{"114.114.114.114"}, searches: []string{"114.114.114.114"},
options: []string{"timeout:1"}, options: []string{"timeout:1"},
@ -604,7 +630,8 @@ nameserver server.google.com
options timeout:1 options timeout:1
`, `,
}, },
"expanded dns config should return correct content on modern libc (e.g. glibc 2.26 and above)": { {
desc: "expanded dns config should return correct content on modern libc (e.g. glibc 2.26 and above)",
servers: []string{"8.8.8.8", "server.google.com"}, servers: []string{"8.8.8.8", "server.google.com"},
searches: []string{ searches: []string{
"server0.google.com", "server0.google.com",
@ -623,7 +650,8 @@ options timeout:1
`, `,
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
resolvContent, err := parseDNSOptions(test.servers, test.searches, test.options) resolvContent, err := parseDNSOptions(test.servers, test.searches, test.options)
if test.expectErr { if test.expectErr {
assert.Error(t, err) assert.Error(t, err)

View File

@ -41,27 +41,31 @@ func TestSandboxContainerSpec(t *testing.T) {
} }
testID := "test-id" testID := "test-id"
nsPath := "test-cni" nsPath := "test-cni"
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
configChange func(*runtime.PodSandboxConfig) configChange func(*runtime.PodSandboxConfig)
podAnnotations []string podAnnotations []string
imageConfigChange func(*imagespec.ImageConfig) imageConfigChange func(*imagespec.ImageConfig)
specCheck func(*testing.T, *runtimespec.Spec) specCheck func(*testing.T, *runtimespec.Spec)
expectErr bool expectErr bool
}{ }{
"should return error when entrypoint and cmd are empty": { {
desc: "should return error when entrypoint and cmd are empty",
imageConfigChange: func(c *imagespec.ImageConfig) { imageConfigChange: func(c *imagespec.ImageConfig) {
c.Entrypoint = nil c.Entrypoint = nil
c.Cmd = nil c.Cmd = nil
}, },
expectErr: true, expectErr: true,
}, },
"a passthrough annotation should be passed as an OCI annotation": { {
desc: "a passthrough annotation should be passed as an OCI annotation",
podAnnotations: []string{"c"}, podAnnotations: []string{"c"},
specCheck: func(t *testing.T, spec *runtimespec.Spec) { specCheck: func(t *testing.T, spec *runtimespec.Spec) {
assert.Equal(t, spec.Annotations["c"], "d") assert.Equal(t, spec.Annotations["c"], "d")
}, },
}, },
"a non-passthrough annotation should not be passed as an OCI annotation": { {
desc: "a non-passthrough annotation should not be passed as an OCI annotation",
configChange: func(c *runtime.PodSandboxConfig) { configChange: func(c *runtime.PodSandboxConfig) {
c.Annotations["d"] = "e" c.Annotations["d"] = "e"
}, },
@ -72,7 +76,8 @@ func TestSandboxContainerSpec(t *testing.T) {
assert.False(t, ok) assert.False(t, ok)
}, },
}, },
"passthrough annotations should support wildcard match": { {
desc: "passthrough annotations should support wildcard match",
configChange: func(c *runtime.PodSandboxConfig) { configChange: func(c *runtime.PodSandboxConfig) {
c.Annotations["t.f"] = "j" c.Annotations["t.f"] = "j"
c.Annotations["z.g"] = "o" c.Annotations["z.g"] = "o"
@ -92,7 +97,8 @@ func TestSandboxContainerSpec(t *testing.T) {
}, },
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
c := newTestCRIService() c := newTestCRIService()
config, imageConfig, specCheck := getRunPodSandboxTestData() config, imageConfig, specCheck := getRunPodSandboxTestData()
if test.configChange != nil { if test.configChange != nil {
@ -120,11 +126,15 @@ func TestSandboxContainerSpec(t *testing.T) {
} }
func TestTypeurlMarshalUnmarshalSandboxMeta(t *testing.T) { func TestTypeurlMarshalUnmarshalSandboxMeta(t *testing.T) {
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
configChange func(*runtime.PodSandboxConfig) configChange func(*runtime.PodSandboxConfig)
}{ }{
"should marshal original config": {}, {
"should marshal Linux": { desc: "should marshal original config",
},
{
desc: "should marshal Linux",
configChange: func(c *runtime.PodSandboxConfig) { configChange: func(c *runtime.PodSandboxConfig) {
if c.Linux == nil { if c.Linux == nil {
c.Linux = &runtime.LinuxPodSandboxConfig{} c.Linux = &runtime.LinuxPodSandboxConfig{}
@ -140,7 +150,8 @@ func TestTypeurlMarshalUnmarshalSandboxMeta(t *testing.T) {
}, },
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
meta := &sandboxstore.Metadata{ meta := &sandboxstore.Metadata{
ID: "1", ID: "1",
Name: "sandbox_1", Name: "sandbox_1",
@ -164,12 +175,16 @@ func TestTypeurlMarshalUnmarshalSandboxMeta(t *testing.T) {
} }
func TestToCNIPortMappings(t *testing.T) { func TestToCNIPortMappings(t *testing.T) {
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
criPortMappings []*runtime.PortMapping criPortMappings []*runtime.PortMapping
cniPortMappings []cni.PortMapping cniPortMappings []cni.PortMapping
}{ }{
"empty CRI port mapping should map to empty CNI port mapping": {}, {
"CRI port mapping should be converted to CNI port mapping properly": { desc: "empty CRI port mapping should map to empty CNI port mapping",
},
{
desc: "CRI port mapping should be converted to CNI port mapping properly",
criPortMappings: []*runtime.PortMapping{ criPortMappings: []*runtime.PortMapping{
{ {
Protocol: runtime.Protocol_UDP, Protocol: runtime.Protocol_UDP,
@ -211,7 +226,8 @@ func TestToCNIPortMappings(t *testing.T) {
}, },
}, },
}, },
"CRI port mapping without host port should be skipped": { {
desc: "CRI port mapping without host port should be skipped",
criPortMappings: []*runtime.PortMapping{ criPortMappings: []*runtime.PortMapping{
{ {
Protocol: runtime.Protocol_UDP, Protocol: runtime.Protocol_UDP,
@ -234,7 +250,8 @@ func TestToCNIPortMappings(t *testing.T) {
}, },
}, },
}, },
"CRI port mapping with unsupported protocol should be skipped": { {
desc: "CRI port mapping with unsupported protocol should be skipped",
criPortMappings: []*runtime.PortMapping{ criPortMappings: []*runtime.PortMapping{
{ {
Protocol: runtime.Protocol_TCP, Protocol: runtime.Protocol_TCP,
@ -253,54 +270,63 @@ func TestToCNIPortMappings(t *testing.T) {
}, },
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
assert.Equal(t, test.cniPortMappings, toCNIPortMappings(test.criPortMappings)) assert.Equal(t, test.cniPortMappings, toCNIPortMappings(test.criPortMappings))
}) })
} }
} }
func TestSelectPodIP(t *testing.T) { func TestSelectPodIP(t *testing.T) {
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
ips []string ips []string
expectedIP string expectedIP string
expectedAdditionalIPs []string expectedAdditionalIPs []string
pref string pref string
}{ }{
"ipv4 should be picked even if ipv6 comes first": { {
desc: "ipv4 should be picked even if ipv6 comes first",
ips: []string{"2001:db8:85a3::8a2e:370:7334", "192.168.17.43"}, ips: []string{"2001:db8:85a3::8a2e:370:7334", "192.168.17.43"},
expectedIP: "192.168.17.43", expectedIP: "192.168.17.43",
expectedAdditionalIPs: []string{"2001:db8:85a3::8a2e:370:7334"}, expectedAdditionalIPs: []string{"2001:db8:85a3::8a2e:370:7334"},
}, },
"ipv6 should be picked even if ipv4 comes first": { {
desc: "ipv6 should be picked even if ipv4 comes first",
ips: []string{"2001:db8:85a3::8a2e:370:7334", "192.168.17.43"}, ips: []string{"2001:db8:85a3::8a2e:370:7334", "192.168.17.43"},
expectedIP: "2001:db8:85a3::8a2e:370:7334", expectedIP: "2001:db8:85a3::8a2e:370:7334",
expectedAdditionalIPs: []string{"192.168.17.43"}, expectedAdditionalIPs: []string{"192.168.17.43"},
pref: "ipv6", pref: "ipv6",
}, },
"order should reflect ip selection": { {
desc: "order should reflect ip selection",
ips: []string{"2001:db8:85a3::8a2e:370:7334", "192.168.17.43"}, ips: []string{"2001:db8:85a3::8a2e:370:7334", "192.168.17.43"},
expectedIP: "2001:db8:85a3::8a2e:370:7334", expectedIP: "2001:db8:85a3::8a2e:370:7334",
expectedAdditionalIPs: []string{"192.168.17.43"}, expectedAdditionalIPs: []string{"192.168.17.43"},
pref: "cni", pref: "cni",
}, },
"ipv4 should be picked when there is only ipv4": { {
desc: "ipv4 should be picked when there is only ipv4",
ips: []string{"192.168.17.43"}, ips: []string{"192.168.17.43"},
expectedIP: "192.168.17.43", expectedIP: "192.168.17.43",
expectedAdditionalIPs: nil, expectedAdditionalIPs: nil,
}, },
"ipv6 should be picked when there is no ipv4": { {
desc: "ipv6 should be picked when there is no ipv4",
ips: []string{"2001:db8:85a3::8a2e:370:7334"}, ips: []string{"2001:db8:85a3::8a2e:370:7334"},
expectedIP: "2001:db8:85a3::8a2e:370:7334", expectedIP: "2001:db8:85a3::8a2e:370:7334",
expectedAdditionalIPs: nil, expectedAdditionalIPs: nil,
}, },
"the first ipv4 should be picked when there are multiple ipv4": { // unlikely to happen {
desc: "the first ipv4 should be picked when there are multiple ipv4", // unlikely to happen
ips: []string{"2001:db8:85a3::8a2e:370:7334", "192.168.17.43", "2001:db8:85a3::8a2e:370:7335", "192.168.17.45"}, ips: []string{"2001:db8:85a3::8a2e:370:7334", "192.168.17.43", "2001:db8:85a3::8a2e:370:7335", "192.168.17.45"},
expectedIP: "192.168.17.43", expectedIP: "192.168.17.43",
expectedAdditionalIPs: []string{"2001:db8:85a3::8a2e:370:7334", "2001:db8:85a3::8a2e:370:7335", "192.168.17.45"}, expectedAdditionalIPs: []string{"2001:db8:85a3::8a2e:370:7334", "2001:db8:85a3::8a2e:370:7335", "192.168.17.45"},
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
var ipConfigs []*cni.IPConfig var ipConfigs []*cni.IPConfig
for _, ip := range test.ips { for _, ip := range test.ips {
ipConfigs = append(ipConfigs, &cni.IPConfig{ ipConfigs = append(ipConfigs, &cni.IPConfig{

View File

@ -33,20 +33,23 @@ func TestGetUsageNanoCores(t *testing.T) {
secondAfterTimeStamp := timestamp.Add(time.Second) secondAfterTimeStamp := timestamp.Add(time.Second)
ID := "ID" ID := "ID"
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
firstCPUValue uint64 firstCPUValue uint64
secondCPUValue uint64 secondCPUValue uint64
expectedNanoCoreUsageFirst uint64 expectedNanoCoreUsageFirst uint64
expectedNanoCoreUsageSecond uint64 expectedNanoCoreUsageSecond uint64
}{ }{
"metrics": { {
desc: "metrics",
firstCPUValue: 50, firstCPUValue: 50,
secondCPUValue: 500, secondCPUValue: 500,
expectedNanoCoreUsageFirst: 0, expectedNanoCoreUsageFirst: 0,
expectedNanoCoreUsageSecond: 450, expectedNanoCoreUsageSecond: 450,
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
container, err := containerstore.NewContainer( container, err := containerstore.NewContainer(
containerstore.Metadata{ID: ID}, containerstore.Metadata{ID: ID},
) )
@ -85,7 +88,8 @@ func Test_criService_podSandboxStats(t *testing.T) {
UsageNanoCores uint64 UsageNanoCores uint64
WorkingSetBytes uint64 WorkingSetBytes uint64
} }
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
metrics map[string]*wstats.Statistics metrics map[string]*wstats.Statistics
sandbox sandboxstore.Sandbox sandbox sandboxstore.Sandbox
containers []containerstore.Container containers []containerstore.Container
@ -93,7 +97,8 @@ func Test_criService_podSandboxStats(t *testing.T) {
expectedContainerStats []expectedStats expectedContainerStats []expectedStats
expectError bool expectError bool
}{ }{
"no metrics found should return error": { {
desc: "no metrics found should return error",
metrics: map[string]*wstats.Statistics{}, metrics: map[string]*wstats.Statistics{},
sandbox: sandboxstore.Sandbox{}, sandbox: sandboxstore.Sandbox{},
containers: []containerstore.Container{}, containers: []containerstore.Container{},
@ -101,7 +106,8 @@ func Test_criService_podSandboxStats(t *testing.T) {
expectedContainerStats: []expectedStats{}, expectedContainerStats: []expectedStats{},
expectError: true, expectError: true,
}, },
"pod stats will include the container stats": { {
desc: "pod stats will include the container stats",
metrics: map[string]*wstats.Statistics{ metrics: map[string]*wstats.Statistics{
"c1": { "c1": {
Container: windowsStat(currentStatsTimestamp, 200, 20), Container: windowsStat(currentStatsTimestamp, 200, 20),
@ -128,7 +134,8 @@ func Test_criService_podSandboxStats(t *testing.T) {
}, },
expectError: false, expectError: false,
}, },
"pod with existing stats will have usagenanocores totalled across pods and containers": { {
desc: "pod with existing stats will have usagenanocores totalled across pods and containers",
metrics: map[string]*wstats.Statistics{ metrics: map[string]*wstats.Statistics{
"c1": { "c1": {
Container: windowsStat(currentStatsTimestamp, 400, 20), Container: windowsStat(currentStatsTimestamp, 400, 20),
@ -161,7 +168,8 @@ func Test_criService_podSandboxStats(t *testing.T) {
}, },
expectError: false, expectError: false,
}, },
"pod sandbox with nil stats still works (hostprocess container scenario)": { {
desc: "pod sandbox with nil stats still works (hostprocess container scenario)",
metrics: map[string]*wstats.Statistics{ metrics: map[string]*wstats.Statistics{
"c1": { "c1": {
Container: windowsStat(currentStatsTimestamp, 400, 20), Container: windowsStat(currentStatsTimestamp, 400, 20),
@ -193,7 +201,8 @@ func Test_criService_podSandboxStats(t *testing.T) {
expectError: false, expectError: false,
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
actualPodStats, actualContainerStats, err := c.toPodSandboxStats(test.sandbox, test.metrics, test.containers, currentStatsTimestamp) actualPodStats, actualContainerStats, err := c.toPodSandboxStats(test.sandbox, test.metrics, test.containers, currentStatsTimestamp)
if test.expectError { if test.expectError {
assert.NotNil(t, err) assert.NotNil(t, err)
@ -240,25 +249,29 @@ func Test_criService_saveSandBoxMetrics(t *testing.T) {
timestamp := time.Now() timestamp := time.Now()
containerID := "c1" containerID := "c1"
sandboxID := "s1" sandboxID := "s1"
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
sandboxStats *runtime.PodSandboxStats sandboxStats *runtime.PodSandboxStats
expectError bool expectError bool
expectedSandboxvalue *stats.ContainerStats expectedSandboxvalue *stats.ContainerStats
expectedContainervalue *stats.ContainerStats expectedContainervalue *stats.ContainerStats
}{ }{
"if sandboxstats is nil then skip ": { {
desc: "if sandboxstats is nil then skip ",
sandboxStats: nil, sandboxStats: nil,
expectError: false, expectError: false,
expectedSandboxvalue: nil, expectedSandboxvalue: nil,
}, },
"if sandboxstats.windows is nil then skip": { {
desc: "if sandboxstats.windows is nil then skip",
sandboxStats: &runtime.PodSandboxStats{ sandboxStats: &runtime.PodSandboxStats{
Windows: nil, Windows: nil,
}, },
expectError: false, expectError: false,
expectedSandboxvalue: nil, expectedSandboxvalue: nil,
}, },
"if sandboxstats.windows.cpu is nil then skip": { {
desc: "if sandboxstats.windows.cpu is nil then skip",
sandboxStats: &runtime.PodSandboxStats{ sandboxStats: &runtime.PodSandboxStats{
Windows: &runtime.WindowsPodSandboxStats{ Windows: &runtime.WindowsPodSandboxStats{
Cpu: nil, Cpu: nil,
@ -267,7 +280,8 @@ func Test_criService_saveSandBoxMetrics(t *testing.T) {
expectError: false, expectError: false,
expectedSandboxvalue: nil, expectedSandboxvalue: nil,
}, },
"if sandboxstats.windows.cpu.UsageCoreNanoSeconds is nil then skip": { {
desc: "if sandboxstats.windows.cpu.UsageCoreNanoSeconds is nil then skip",
sandboxStats: &runtime.PodSandboxStats{ sandboxStats: &runtime.PodSandboxStats{
Windows: &runtime.WindowsPodSandboxStats{ Windows: &runtime.WindowsPodSandboxStats{
Cpu: &runtime.WindowsCpuUsage{ Cpu: &runtime.WindowsCpuUsage{
@ -278,7 +292,8 @@ func Test_criService_saveSandBoxMetrics(t *testing.T) {
expectError: false, expectError: false,
expectedSandboxvalue: nil, expectedSandboxvalue: nil,
}, },
"Stats for containers that have cpu nil are skipped": { {
desc: "Stats for containers that have cpu nil are skipped",
sandboxStats: &runtime.PodSandboxStats{ sandboxStats: &runtime.PodSandboxStats{
Windows: &runtime.WindowsPodSandboxStats{ Windows: &runtime.WindowsPodSandboxStats{
Cpu: &runtime.WindowsCpuUsage{ Cpu: &runtime.WindowsCpuUsage{
@ -300,7 +315,8 @@ func Test_criService_saveSandBoxMetrics(t *testing.T) {
}, },
expectedContainervalue: nil, expectedContainervalue: nil,
}, },
"Stats for containers that have UsageCoreNanoSeconds nil are skipped": { {
desc: "Stats for containers that have UsageCoreNanoSeconds nil are skipped",
sandboxStats: &runtime.PodSandboxStats{ sandboxStats: &runtime.PodSandboxStats{
Windows: &runtime.WindowsPodSandboxStats{ Windows: &runtime.WindowsPodSandboxStats{
Cpu: &runtime.WindowsCpuUsage{ Cpu: &runtime.WindowsCpuUsage{
@ -324,7 +340,8 @@ func Test_criService_saveSandBoxMetrics(t *testing.T) {
}, },
expectedContainervalue: nil, expectedContainervalue: nil,
}, },
"Stats are updated for sandbox and containers": { {
desc: "Stats are updated for sandbox and containers",
sandboxStats: &runtime.PodSandboxStats{ sandboxStats: &runtime.PodSandboxStats{
Windows: &runtime.WindowsPodSandboxStats{ Windows: &runtime.WindowsPodSandboxStats{
Cpu: &runtime.WindowsCpuUsage{ Cpu: &runtime.WindowsCpuUsage{
@ -353,7 +370,8 @@ func Test_criService_saveSandBoxMetrics(t *testing.T) {
}, },
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
c := newTestCRIService() c := newTestCRIService()
c.sandboxStore.Add(sandboxstore.Sandbox{ c.sandboxStore.Add(sandboxstore.Sandbox{
Metadata: sandboxstore.Metadata{ID: sandboxID}, Metadata: sandboxstore.Metadata{ID: sandboxID},

View File

@ -87,24 +87,29 @@ func TestPodSandboxStatus(t *testing.T) {
Annotations: config.GetAnnotations(), Annotations: config.GetAnnotations(),
RuntimeHandler: "test-runtime-handler", RuntimeHandler: "test-runtime-handler",
} }
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
state sandboxstore.State state sandboxstore.State
expectedState runtime.PodSandboxState expectedState runtime.PodSandboxState
}{ }{
"sandbox state ready": { {
desc: "sandbox state ready",
state: sandboxstore.StateReady, state: sandboxstore.StateReady,
expectedState: runtime.PodSandboxState_SANDBOX_READY, expectedState: runtime.PodSandboxState_SANDBOX_READY,
}, },
"sandbox state not ready": { {
desc: "sandbox state not ready",
state: sandboxstore.StateNotReady, state: sandboxstore.StateNotReady,
expectedState: runtime.PodSandboxState_SANDBOX_NOTREADY, expectedState: runtime.PodSandboxState_SANDBOX_NOTREADY,
}, },
"sandbox state unknown": { {
desc: "sandbox state unknown",
state: sandboxstore.StateUnknown, state: sandboxstore.StateUnknown,
expectedState: runtime.PodSandboxState_SANDBOX_NOTREADY, expectedState: runtime.PodSandboxState_SANDBOX_NOTREADY,
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
status := sandboxstore.Status{ status := sandboxstore.Status{
CreatedAt: createdAt, CreatedAt: createdAt,
State: test.state, State: test.state,

View File

@ -28,30 +28,35 @@ import (
func TestWaitSandboxStop(t *testing.T) { func TestWaitSandboxStop(t *testing.T) {
id := "test-id" id := "test-id"
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
state sandboxstore.State state sandboxstore.State
cancel bool cancel bool
timeout time.Duration timeout time.Duration
expectErr bool expectErr bool
}{ }{
"should return error if timeout exceeds": { {
desc: "should return error if timeout exceeds",
state: sandboxstore.StateReady, state: sandboxstore.StateReady,
timeout: 200 * time.Millisecond, timeout: 200 * time.Millisecond,
expectErr: true, expectErr: true,
}, },
"should return error if context is cancelled": { {
desc: "should return error if context is cancelled",
state: sandboxstore.StateReady, state: sandboxstore.StateReady,
timeout: time.Hour, timeout: time.Hour,
cancel: true, cancel: true,
expectErr: true, expectErr: true,
}, },
"should not return error if sandbox is stopped before timeout": { {
desc: "should not return error if sandbox is stopped before timeout",
state: sandboxstore.StateNotReady, state: sandboxstore.StateNotReady,
timeout: time.Hour, timeout: time.Hour,
expectErr: false, expectErr: false,
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
c := newTestCRIService() c := newTestCRIService()
sandbox := sandboxstore.NewSandbox( sandbox := sandboxstore.NewSandbox(
sandboxstore.Metadata{ID: id}, sandboxstore.Metadata{ID: id},
@ -69,7 +74,7 @@ func TestWaitSandboxStop(t *testing.T) {
ctx = timeoutCtx ctx = timeoutCtx
} }
err := c.waitSandboxStop(ctx, sandbox) err := c.waitSandboxStop(ctx, sandbox)
assert.Equal(t, test.expectErr, err != nil, desc) assert.Equal(t, test.expectErr, err != nil, test.desc)
}) })
} }
} }

View File

@ -24,12 +24,14 @@ import (
) )
func TestValidateStreamServer(t *testing.T) { func TestValidateStreamServer(t *testing.T) {
for desc, test := range map[string]struct { for _, test := range []struct {
desc string
*criService *criService
tlsMode streamListenerMode tlsMode streamListenerMode
expectErr bool expectErr bool
}{ }{
"should pass with default withoutTLS": { {
desc: "should pass with default withoutTLS",
criService: &criService{ criService: &criService{
config: config.Config{ config: config.Config{
PluginConfig: config.DefaultConfig(), PluginConfig: config.DefaultConfig(),
@ -38,7 +40,8 @@ func TestValidateStreamServer(t *testing.T) {
tlsMode: withoutTLS, tlsMode: withoutTLS,
expectErr: false, expectErr: false,
}, },
"should pass with x509KeyPairTLS": { {
desc: "should pass with x509KeyPairTLS",
criService: &criService{ criService: &criService{
config: config.Config{ config: config.Config{
PluginConfig: config.PluginConfig{ PluginConfig: config.PluginConfig{
@ -53,7 +56,8 @@ func TestValidateStreamServer(t *testing.T) {
tlsMode: x509KeyPairTLS, tlsMode: x509KeyPairTLS,
expectErr: false, expectErr: false,
}, },
"should pass with selfSign": { {
desc: "should pass with selfSign",
criService: &criService{ criService: &criService{
config: config.Config{ config: config.Config{
PluginConfig: config.PluginConfig{ PluginConfig: config.PluginConfig{
@ -64,7 +68,8 @@ func TestValidateStreamServer(t *testing.T) {
tlsMode: selfSignTLS, tlsMode: selfSignTLS,
expectErr: false, expectErr: false,
}, },
"should return error with X509 keypair but not EnableTLSStreaming": { {
desc: "should return error with X509 keypair but not EnableTLSStreaming",
criService: &criService{ criService: &criService{
config: config.Config{ config: config.Config{
PluginConfig: config.PluginConfig{ PluginConfig: config.PluginConfig{
@ -79,7 +84,8 @@ func TestValidateStreamServer(t *testing.T) {
tlsMode: -1, tlsMode: -1,
expectErr: true, expectErr: true,
}, },
"should return error with X509 TLSCertFile empty": { {
desc: "should return error with X509 TLSCertFile empty",
criService: &criService{ criService: &criService{
config: config.Config{ config: config.Config{
PluginConfig: config.PluginConfig{ PluginConfig: config.PluginConfig{
@ -94,7 +100,8 @@ func TestValidateStreamServer(t *testing.T) {
tlsMode: -1, tlsMode: -1,
expectErr: true, expectErr: true,
}, },
"should return error with X509 TLSKeyFile empty": { {
desc: "should return error with X509 TLSKeyFile empty",
criService: &criService{ criService: &criService{
config: config.Config{ config: config.Config{
PluginConfig: config.PluginConfig{ PluginConfig: config.PluginConfig{
@ -109,7 +116,8 @@ func TestValidateStreamServer(t *testing.T) {
tlsMode: -1, tlsMode: -1,
expectErr: true, expectErr: true,
}, },
"should return error without EnableTLSStreaming and only TLSCertFile set": { {
desc: "should return error without EnableTLSStreaming and only TLSCertFile set",
criService: &criService{ criService: &criService{
config: config.Config{ config: config.Config{
PluginConfig: config.PluginConfig{ PluginConfig: config.PluginConfig{
@ -124,7 +132,8 @@ func TestValidateStreamServer(t *testing.T) {
tlsMode: -1, tlsMode: -1,
expectErr: true, expectErr: true,
}, },
"should return error without EnableTLSStreaming and only TLSKeyFile set": { {
desc: "should return error without EnableTLSStreaming and only TLSKeyFile set",
criService: &criService{ criService: &criService{
config: config.Config{ config: config.Config{
PluginConfig: config.PluginConfig{ PluginConfig: config.PluginConfig{
@ -140,7 +149,8 @@ func TestValidateStreamServer(t *testing.T) {
expectErr: true, expectErr: true,
}, },
} { } {
t.Run(desc, func(t *testing.T) { test := test
t.Run(test.desc, func(t *testing.T) {
tlsMode, err := getStreamListenerMode(test.criService) tlsMode, err := getStreamListenerMode(test.criService)
if test.expectErr { if test.expectErr {
assert.Error(t, err) assert.Error(t, err)

View File

@ -70,29 +70,35 @@ func TestUpdateRuntimeConfig(t *testing.T) {
}` }`
) )
for name, test := range map[string]struct { for _, test := range []struct {
name string
noTemplate bool noTemplate bool
emptyCIDR bool emptyCIDR bool
networkReady bool networkReady bool
expectCNIConfig bool expectCNIConfig bool
}{ }{
"should not generate cni config if cidr is empty": { {
name: "should not generate cni config if cidr is empty",
emptyCIDR: true, emptyCIDR: true,
expectCNIConfig: false, expectCNIConfig: false,
}, },
"should not generate cni config if template file is not specified": { {
name: "should not generate cni config if template file is not specified",
noTemplate: true, noTemplate: true,
expectCNIConfig: false, expectCNIConfig: false,
}, },
"should not generate cni config if network is ready": { {
name: "should not generate cni config if network is ready",
networkReady: true, networkReady: true,
expectCNIConfig: false, expectCNIConfig: false,
}, },
"should generate cni config if template is specified and cidr is provided": { {
name: "should generate cni config if template is specified and cidr is provided",
expectCNIConfig: true, expectCNIConfig: true,
}, },
} { } {
t.Run(name, func(t *testing.T) { test := test
t.Run(test.name, func(t *testing.T) {
testDir := t.TempDir() testDir := t.TempDir()
templateName := filepath.Join(testDir, "template") templateName := filepath.Join(testDir, "template")
err := os.WriteFile(templateName, []byte(testTemplate), 0666) err := os.WriteFile(templateName, []byte(testTemplate), 0666)