...
1 package cpu
2
3 import (
4 "os"
5 "os/exec"
6 "strconv"
7 "strings"
8 "testing"
9 )
10
11 func TestTimesEmpty(t *testing.T) {
12 orig := os.Getenv("HOST_PROC")
13 os.Setenv("HOST_PROC", "testdata/linux/times_empty")
14 _, err := Times(true)
15 if err != nil {
16 t.Error("Times(true) failed")
17 }
18 _, err = Times(false)
19 if err != nil {
20 t.Error("Times(false) failed")
21 }
22 os.Setenv("HOST_PROC", orig)
23 }
24
25 func TestCPUparseStatLine_424(t *testing.T) {
26 orig := os.Getenv("HOST_PROC")
27 os.Setenv("HOST_PROC", "testdata/linux/424/proc")
28 {
29 l, err := Times(true)
30 if err != nil || len(l) == 0 {
31 t.Error("Times(true) failed")
32 }
33 t.Logf("Times(true): %#v", l)
34 }
35 {
36 l, err := Times(false)
37 if err != nil || len(l) == 0 {
38 t.Error("Times(false) failed")
39 }
40 t.Logf("Times(false): %#v", l)
41 }
42 os.Setenv("HOST_PROC", orig)
43 }
44
45 func TestCPUCountsAgainstLscpu(t *testing.T) {
46 lscpu, err := exec.LookPath("lscpu")
47 if err != nil {
48 t.Skip("no lscpu to compare with")
49 }
50 cmd := exec.Command(lscpu)
51 cmd.Env = []string{"LC_ALL=C"}
52 out, err := cmd.Output()
53 if err != nil {
54 t.Errorf("error executing lscpu: %v", err)
55 }
56 var threadsPerCore, coresPerSocket, sockets int
57 lines := strings.Split(string(out), "\n")
58 for _, line := range lines {
59 fields := strings.Split(line, ":")
60 if len(fields) < 2 {
61 continue
62 }
63 switch fields[0] {
64 case "Thread(s) per core":
65 threadsPerCore, _ = strconv.Atoi(strings.TrimSpace(fields[1]))
66 case "Core(s) per socket":
67 coresPerSocket, _ = strconv.Atoi(strings.TrimSpace(fields[1]))
68 case "Socket(s)":
69 sockets, _ = strconv.Atoi(strings.TrimSpace(fields[1]))
70 }
71 }
72 if threadsPerCore == 0 || coresPerSocket == 0 || sockets == 0 {
73 t.Errorf("missing info from lscpu: threadsPerCore=%d coresPerSocket=%d sockets=%d", threadsPerCore, coresPerSocket, sockets)
74 }
75 expectedPhysical := coresPerSocket * sockets
76 expectedLogical := expectedPhysical * threadsPerCore
77 physical, err := Counts(false)
78 skipIfNotImplementedErr(t, err)
79 if err != nil {
80 t.Errorf("error %v", err)
81 }
82 logical, err := Counts(true)
83 skipIfNotImplementedErr(t, err)
84 if err != nil {
85 t.Errorf("error %v", err)
86 }
87 if expectedPhysical != physical {
88 t.Errorf("expected %v, got %v", expectedPhysical, physical)
89 }
90 if expectedLogical != logical {
91 t.Errorf("expected %v, got %v", expectedLogical, logical)
92 }
93 }
94
95 func TestCPUCountsLogicalAndroid_1037(t *testing.T) {
96 orig := os.Getenv("HOST_PROC")
97 os.Setenv("HOST_PROC", "testdata/linux/1037/proc")
98 defer os.Setenv("HOST_PROC", orig)
99
100 count, err := Counts(true)
101 if err != nil {
102 t.Errorf("error %v", err)
103 }
104 expected := 8
105 if count != expected {
106 t.Errorf("expected %v, got %v", expected, count)
107 }
108 }
109
View as plain text