Browse Source

Add NewCPUStat which allows to create a new instance

This wraps around the creation of a new CPUStat, reading
the first line from /proc/stat is left out. This can be done using
an interface io.reader or simply without stubing in the main app.
Oz Tiram 5 years ago
parent
commit
55b1698ac5
2 changed files with 38 additions and 15 deletions
  1. 14 11
      gupta.go
  2. 24 4
      gupta_test.go

+ 14 - 11
gupta.go

@@ -3,6 +3,7 @@ package gupta
 import (
 	"fmt"
 	"strconv"
+	"strings"
 )
 
 const version = "0.0.1"
@@ -57,27 +58,29 @@ func (c *CPUStat) ReadInfo(rawInfo []string) {
 		c.idle = s
 	}
 	if s, err := strconv.ParseUint(rawInfo[4], 10, 64); err == nil {
-		c.idle = s
-	}
-	if s, err := strconv.ParseUint(rawInfo[5], 10, 64); err == nil {
 		c.iowait = s
 	}
-	if s, err := strconv.ParseUint(rawInfo[6], 10, 64); err == nil {
+	if s, err := strconv.ParseUint(rawInfo[5], 10, 64); err == nil {
 		c.irq = s
 	}
-	if s, err := strconv.ParseUint(rawInfo[7], 10, 64); err == nil {
-		c.softirq = s
-	}
-	if s, err := strconv.ParseUint(rawInfo[8], 10, 64); err == nil {
+	if s, err := strconv.ParseUint(rawInfo[6], 10, 64); err == nil {
 		c.softirq = s
 	}
-	if s, err := strconv.ParseUint(rawInfo[9], 10, 64); err == nil {
+	if s, err := strconv.ParseUint(rawInfo[7], 10, 64); err == nil {
 		c.steal = s
 	}
-	if s, err := strconv.ParseUint(rawInfo[10], 10, 64); err == nil {
+	if s, err := strconv.ParseUint(rawInfo[8], 10, 64); err == nil {
 		c.guest = s
 	}
-	if s, err := strconv.ParseUint(rawInfo[11], 10, 64); err == nil {
+	if s, err := strconv.ParseUint(rawInfo[9], 10, 64); err == nil {
 		c.guest_nice = s
 	}
 }
+
+func NewCPUStat(procstatline string) CPUStat {
+	cpustat := CPUStat{}
+	statline := strings.Fields(procstatline)
+	fmt.Println(statline)
+	cpustat.ReadInfo(statline)
+	return cpustat
+}

+ 24 - 4
gupta_test.go

@@ -49,10 +49,30 @@ func TestGuptaHasReport(t *testing.T) {
 }
 
 func TestGetCPULoad(t *testing.T) {
-	cpuload := CPULoad{}
-	cpuload.ReadInfo([]string{"1234", "5678", "9101112"})
+	cpustat := CPUStat{}
+	cpustat.ReadInfo([]string{"4705",
+		"356",
+		"584",
+		"3699",
+		"23",
+		"23",
+		"0",
+		"0",
+		"0",
+		"0"})
 
-	if cpuload.user != 1234 {
-		t.Errorf("got %v want %v", cpuload.user, 1234)
+	if cpustat.user != 4705 {
+		t.Errorf("got %v want %v", cpustat.user, 4705)
+	}
+}
+
+func TestCalculateCPUUsage(t *testing.T) {
+	//                0    1     2     3     4      5     6       7     8     9
+	//               user nice system idle iowait  irq  softirq steal guest guest_nice
+	procstatLine := "4705 356  584    3699   23    23     0       0     0    0"
+	cpustat := NewCPUStat(procstatLine)
+
+	if cpustat.user != 4705 {
+		t.Errorf("got %v want %v", cpustat.user, 4705)
 	}
 }