github.com/zhouyu0/docker-note@v0.0.0-20190722021225-b8d3825084db/pkg/sysinfo/sysinfo_linux_test.go (about) 1 package sysinfo // import "github.com/docker/docker/pkg/sysinfo" 2 3 import ( 4 "io/ioutil" 5 "os" 6 "path" 7 "path/filepath" 8 "testing" 9 10 "golang.org/x/sys/unix" 11 "gotest.tools/assert" 12 ) 13 14 func TestReadProcBool(t *testing.T) { 15 tmpDir, err := ioutil.TempDir("", "test-sysinfo-proc") 16 assert.NilError(t, err) 17 defer os.RemoveAll(tmpDir) 18 19 procFile := filepath.Join(tmpDir, "read-proc-bool") 20 err = ioutil.WriteFile(procFile, []byte("1"), 0644) 21 assert.NilError(t, err) 22 23 if !readProcBool(procFile) { 24 t.Fatal("expected proc bool to be true, got false") 25 } 26 27 if err := ioutil.WriteFile(procFile, []byte("0"), 0644); err != nil { 28 t.Fatal(err) 29 } 30 if readProcBool(procFile) { 31 t.Fatal("expected proc bool to be false, got true") 32 } 33 34 if readProcBool(path.Join(tmpDir, "no-exist")) { 35 t.Fatal("should be false for non-existent entry") 36 } 37 38 } 39 40 func TestCgroupEnabled(t *testing.T) { 41 cgroupDir, err := ioutil.TempDir("", "cgroup-test") 42 assert.NilError(t, err) 43 defer os.RemoveAll(cgroupDir) 44 45 if cgroupEnabled(cgroupDir, "test") { 46 t.Fatal("cgroupEnabled should be false") 47 } 48 49 err = ioutil.WriteFile(path.Join(cgroupDir, "test"), []byte{}, 0644) 50 assert.NilError(t, err) 51 52 if !cgroupEnabled(cgroupDir, "test") { 53 t.Fatal("cgroupEnabled should be true") 54 } 55 } 56 57 func TestNew(t *testing.T) { 58 sysInfo := New(false) 59 assert.Assert(t, sysInfo != nil) 60 checkSysInfo(t, sysInfo) 61 62 sysInfo = New(true) 63 assert.Assert(t, sysInfo != nil) 64 checkSysInfo(t, sysInfo) 65 } 66 67 func checkSysInfo(t *testing.T, sysInfo *SysInfo) { 68 // Check if Seccomp is supported, via CONFIG_SECCOMP.then sysInfo.Seccomp must be TRUE , else FALSE 69 if err := unix.Prctl(unix.PR_GET_SECCOMP, 0, 0, 0, 0); err != unix.EINVAL { 70 // Make sure the kernel has CONFIG_SECCOMP_FILTER. 71 if err := unix.Prctl(unix.PR_SET_SECCOMP, unix.SECCOMP_MODE_FILTER, 0, 0, 0); err != unix.EINVAL { 72 assert.Assert(t, sysInfo.Seccomp) 73 } 74 } else { 75 assert.Assert(t, !sysInfo.Seccomp) 76 } 77 } 78 79 func TestNewAppArmorEnabled(t *testing.T) { 80 // Check if AppArmor is supported. then it must be TRUE , else FALSE 81 if _, err := os.Stat("/sys/kernel/security/apparmor"); err != nil { 82 t.Skip("App Armor Must be Enabled") 83 } 84 85 sysInfo := New(true) 86 assert.Assert(t, sysInfo.AppArmor) 87 } 88 89 func TestNewAppArmorDisabled(t *testing.T) { 90 // Check if AppArmor is supported. then it must be TRUE , else FALSE 91 if _, err := os.Stat("/sys/kernel/security/apparmor"); !os.IsNotExist(err) { 92 t.Skip("App Armor Must be Disabled") 93 } 94 95 sysInfo := New(true) 96 assert.Assert(t, !sysInfo.AppArmor) 97 } 98 99 func TestNumCPU(t *testing.T) { 100 cpuNumbers := NumCPU() 101 if cpuNumbers <= 0 { 102 t.Fatal("CPU returned must be greater than zero") 103 } 104 }