github.com/distbuild/reclient@v0.0.0-20240401075343-3de72e395564/internal/pkg/localresources/usage/usage_test.go (about) 1 package usage 2 3 import ( 4 "testing" 5 "time" 6 7 "github.com/google/go-cmp/cmp" 8 "github.com/google/go-cmp/cmp/cmpopts" 9 "github.com/shirou/gopsutil/v3/process" 10 ) 11 12 type mockSampler struct { 13 idx int 14 cpu []float64 15 ram []float32 16 vms []uint64 17 rss []uint64 18 } 19 20 func (m *mockSampler) Percent(interval time.Duration) (float64, error) { 21 return m.cpu[m.idx], nil 22 } 23 24 func (m *mockSampler) MemoryPercent() (float32, error) { 25 return m.ram[m.idx], nil 26 } 27 28 func (m *mockSampler) MemoryInfo() (*process.MemoryInfoStat, error) { 29 p := &process.MemoryInfoStat{VMS: m.vms[m.idx], RSS: m.rss[m.idx]} 30 return p, nil 31 } 32 33 func (m *mockSampler) updateIdx() { 34 m.idx++ 35 } 36 37 var ( 38 cpuUsage = []float64{11, 12, 13, 14, 15} 39 ramUsage = []float32{5, 4, 3, 2, 1} 40 vmUsage = []uint64{10 * mb, 20 * mb, 30 * mb, 40 * mb, 50 * mb} 41 rssUsage = []uint64{5 * mb, 4 * mb, 3 * mb, 2 * mb, 1 * mb} 42 emptySampler = &mockSampler{} 43 nonEmptySampler = &mockSampler{idx: 0, cpu: cpuUsage, ram: ramUsage, vms: vmUsage, rss: rssUsage} 44 wantCPU = []int64{11, 12, 13, 14, 15} 45 wantRAM = []int64{5, 4, 3, 2, 1} 46 wantVIRT = []int64{10, 20, 30, 40, 50} 47 wantRES = []int64{5, 4, 3, 2, 1} 48 wantResults = map[string][]int64{CPUPct: wantCPU, MemPct: wantRAM, MemVirt: wantVIRT, MemRes: wantRES} 49 ) 50 51 func TestNew(t *testing.T) { 52 t.Run("New PsutilSampler Instance represents the current process's resource usage", func(t *testing.T) { 53 usage := New() 54 if usage == nil { 55 t.Fatalf("Failed to create a PsutilSampler instance.") 56 } 57 newUsage := New() // call New() again should return the same process. 58 if diff := cmp.Diff(usage.Sampler, newUsage.Sampler, cmpopts.IgnoreUnexported(process.Process{})); diff != "" { 59 t.Fatalf("New() returns diff in result: (-want +got)\n%s", diff) 60 } 61 }) 62 } 63 64 func TestSample(t *testing.T) { 65 t.Run("AddSample with resource usage data.", func(t *testing.T) { 66 for nonEmptySampler.idx <= 4 { 67 for key, val := range Sample(nonEmptySampler) { 68 want := wantResults[key][nonEmptySampler.idx] 69 if diff := cmp.Diff(want, val); diff != "" { 70 t.Errorf("Sample() generate diff : (-want +got)\n%s", diff) 71 } 72 } 73 nonEmptySampler.updateIdx() 74 } 75 }) 76 }