-
Notifications
You must be signed in to change notification settings - Fork 9
/
sysctl_linux_test.go
112 lines (103 loc) · 2.12 KB
/
sysctl_linux_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
//go:build linux
// +build linux
package sysctl
import (
"os/user"
"testing"
)
func TestGet(t *testing.T) {
cases := []struct {
name string
skip bool
}{
{
name: "fs.protected_fifos",
skip: !isUserRoot(),
},
{
name: "net.ipv4.ip_forward",
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if c.skip {
t.Skip("skipping test")
}
got, err := Get(c.name)
if err != nil {
t.Fatalf("Could not get sysctl value: %s", err.Error())
}
if got != "0" && got != "1" {
t.Fatalf("expected 0 or 1, got %s", got)
}
})
}
}
func TestGetPattern(t *testing.T) {
cases := []struct {
pattern string
matches []string
skip bool
}{
{
pattern: "^fs.protected_",
matches: []string{
"fs.protected_fifos",
"fs.protected_hardlinks",
"fs.protected_regular",
"fs.protected_symlinks",
},
skip: !isUserRoot(),
},
{
pattern: "^net.ipv4.ipfrag",
matches: []string{
"net.ipv4.ipfrag_high_thresh",
"net.ipv4.ipfrag_low_thresh",
"net.ipv4.ipfrag_max_dist",
"net.ipv4.ipfrag_time",
},
},
}
for _, c := range cases {
t.Run(c.pattern, func(t *testing.T) {
if c.skip {
t.Skip("skipping test")
}
got, err := GetPattern(c.pattern)
if err != nil {
t.Fatalf("could not get sysctl values for pattern %s: %v", c.pattern, err)
}
if len(got) < len(c.matches) {
// We check if length is < than expected to prevent
// breaking test cases if new sysctls are added
t.Fatalf("expected at least %d matches, got %d. Matches: %+v",
len(c.matches), len(got), got)
}
for _, k := range c.matches {
if _, ok := got[k]; !ok {
t.Fatalf("key %s not matched. Matches: %+v", k, got)
}
}
})
}
}
func TestGetAll(t *testing.T) {
if !isUserRoot() {
t.Skip("user not root, skipping test")
}
got, err := GetAll()
if err != nil {
t.Fatalf("Could not get sysctl values: %s", err.Error())
}
if len(got) == 0 {
t.Fatal("no error returned but returned empty slice of sysctl values")
}
}
func isUserRoot() bool {
u, err := user.Current()
if err != nil {
return false
}
return u.Username == "root"
}