1
16
17 package kuberuntime
18
19 import (
20 "fmt"
21 "math/rand"
22 "path/filepath"
23 "testing"
24
25 "github.com/stretchr/testify/assert"
26 )
27
28 const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
29
30 func randStringBytes(n int) string {
31 b := make([]byte, n)
32 for i := range b {
33 b[i] = letterBytes[rand.Intn(len(letterBytes))]
34 }
35 return string(b)
36 }
37
38 func TestLogSymLink(t *testing.T) {
39 as := assert.New(t)
40 containerLogsDir := "/foo/bar"
41 podFullName := randStringBytes(128)
42 containerName := randStringBytes(70)
43 containerID := randStringBytes(80)
44
45 expectedPath := filepath.Join(containerLogsDir, fmt.Sprintf("%s_%s-%s", podFullName, containerName, containerID)[:251]+".log")
46 as.Equal(expectedPath, logSymlink(containerLogsDir, podFullName, containerName, containerID))
47 }
48
49 func TestLegacyLogSymLink(t *testing.T) {
50 as := assert.New(t)
51 containerID := randStringBytes(80)
52 containerName := randStringBytes(70)
53 podName := randStringBytes(128)
54 podNamespace := randStringBytes(10)
55
56 expectedPath := filepath.Join(legacyContainerLogsDir, fmt.Sprintf("%s_%s_%s-%s", podName, podNamespace, containerName, containerID)[:251]+".log")
57 as.Equal(expectedPath, legacyLogSymlink(containerID, containerName, podName, podNamespace))
58 }
59
60 func TestGetContainerIDFromLegacyLogSymLink(t *testing.T) {
61 containerID := randStringBytes(80)
62 containerName := randStringBytes(70)
63 podName := randStringBytes(128)
64 podNamespace := randStringBytes(10)
65
66 for _, test := range []struct {
67 name string
68 logSymLink string
69 expected string
70 shouldError bool
71 }{
72 {
73 name: "unable to find separator",
74 logSymLink: "dummy.log",
75 expected: "",
76 shouldError: true,
77 },
78 {
79 name: "invalid suffix",
80 logSymLink: filepath.Join(legacyContainerLogsDir, fmt.Sprintf("%s_%s_%s-%s", podName, podNamespace, containerName, containerID)[:251]+".invalidsuffix"),
81 expected: "",
82 shouldError: true,
83 },
84 {
85 name: "container ID too short",
86 logSymLink: filepath.Join(legacyContainerLogsDir, fmt.Sprintf("%s_%s_%s-%s", podName, podNamespace, containerName, containerID[:5])+".log"),
87 expected: "",
88 shouldError: true,
89 },
90 {
91 name: "valid path",
92 logSymLink: filepath.Join(legacyContainerLogsDir, fmt.Sprintf("%s_%s_%s-%s", podName, podNamespace, containerName, containerID)[:251]+".log"),
93 expected: containerID[:40],
94 shouldError: false,
95 },
96 } {
97 t.Run(test.name, func(t *testing.T) {
98 containerID, err := getContainerIDFromLegacyLogSymlink(test.logSymLink)
99 if test.shouldError {
100 assert.Error(t, err)
101 } else {
102 assert.NoError(t, err)
103 }
104 assert.Equal(t, test.expected, containerID)
105 })
106 }
107 }
108
View as plain text