package fs import ( "io/ioutil" "os" "path/filepath" "sort" "testing" ) func TestGetMemoryLimit(t *testing.T) { tmpCgroupDir, err := ioutil.TempDir("/tmp", "cgroup-") if err != nil { t.Fatal("Cannot create temporary file", err) } defer os.RemoveAll(tmpCgroupDir) tmpMemLimitFile := filepath.Join(tmpCgroupDir, "memory.limit_in_bytes") DefaultMemLimit := float64(3 * 1024 * 1024 * 1024) type memTest struct { limitSet string limitGet float64 } memTests := []memTest{ {limitSet: defaultMem, limitGet: DefaultMemLimit}, {limitSet: "1024000000", limitGet: float64(1024000000)}, {limitSet: "0", limitGet: DefaultMemLimit}, } for i, test := range memTests { err = ioutil.WriteFile(tmpMemLimitFile, []byte(test.limitSet), 0) if err != nil { t.Fatal(i, "Failed to write to temporary file", err) } memLimit := GetMemoryLimit(tmpCgroupDir, DefaultMemLimit) if memLimit != test.limitGet { t.Fatalf("%d memLimit(%f) != expected(%f)", i, memLimit, test.limitGet) } } } func TestGetMemoryUsage(t *testing.T) { usage, workingSet, err := GetMemoryUsage("../testdata/cg1_memory") if err != nil { t.Error("err:", err) return } if usage != 102400000 { t.Errorf("unexpected usage %d, should be %d", usage, 102400000) return } if workingSet != 100000000 { t.Errorf("unexpected usage %d, should be %d", workingSet, 100000000) return } } func TestGetKernelMemoryUsage(t *testing.T) { kmemUsage, err := GetKernelMemoryUsage("../testdata/cg1_memory") if err != nil { t.Error("err:", err) return } if kmemUsage != 10240000 { t.Errorf("unexpected kmem usage %d, should be %d", kmemUsage, 10240000) return } } func TestGetKernelMemorySlabInfo(t *testing.T) { slabInfo, err := GetKernelMemorySlabInfo("../testdata/cg1_memory") if err != nil { t.Error("err:", err) return } sort.Sort(slabInfo) if len(slabInfo.Slabs) < 2 { t.Error("unexpected slabInfo len", len(slabInfo.Slabs)) return } if slabInfo.Slabs[0].Name != "proc_inode_cache" || slabInfo.Slabs[1].Name != "dentry" { t.Errorf("unexpected slabInfo sort, top1:%s, top2:%s", slabInfo.Slabs[0].Name, slabInfo.Slabs[1].Name) return } }