github.com/bigcommerce/nomad@v0.9.3-bc/client/stats/cpu_test.go (about) 1 package stats 2 3 import ( 4 "math" 5 "os" 6 "testing" 7 "time" 8 9 shelpers "github.com/hashicorp/nomad/helper/stats" 10 "github.com/hashicorp/nomad/helper/testlog" 11 "github.com/stretchr/testify/assert" 12 ) 13 14 func TestCpuStatsPercent(t *testing.T) { 15 cs := NewCpuStats() 16 cs.Percent(79.7) 17 time.Sleep(1 * time.Second) 18 percent := cs.Percent(80.69) 19 expectedPercent := 98.00 20 if percent < expectedPercent && percent > (expectedPercent+1.00) { 21 t.Fatalf("expected: %v, actual: %v", expectedPercent, percent) 22 } 23 } 24 25 func TestHostStats_CPU(t *testing.T) { 26 assert := assert.New(t) 27 assert.Nil(shelpers.Init()) 28 29 logger := testlog.HCLogger(t) 30 cwd, err := os.Getwd() 31 assert.Nil(err) 32 hs := NewHostStatsCollector(logger, cwd, nil) 33 34 // Collect twice so we can calculate percents we need to generate some work 35 // so that the cpu values change 36 assert.Nil(hs.Collect()) 37 total := 0 38 for i := 1; i < 1000000000; i++ { 39 total *= i 40 total = total % i 41 } 42 assert.Nil(hs.Collect()) 43 stats := hs.Stats() 44 45 assert.NotZero(stats.CPUTicksConsumed) 46 assert.NotZero(len(stats.CPU)) 47 48 for _, cpu := range stats.CPU { 49 assert.False(math.IsNaN(cpu.Idle)) 50 assert.False(math.IsNaN(cpu.Total)) 51 assert.False(math.IsNaN(cpu.System)) 52 assert.False(math.IsNaN(cpu.User)) 53 54 assert.False(math.IsInf(cpu.Idle, 0)) 55 assert.False(math.IsInf(cpu.Total, 0)) 56 assert.False(math.IsInf(cpu.System, 0)) 57 assert.False(math.IsInf(cpu.User, 0)) 58 } 59 }