test_util.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. Utility for testing cgroup operations.
  3. Creates a mock of the cgroup filesystem for the duration of the test.
  4. */
  5. package fs
  6. import (
  7. "fmt"
  8. "io/ioutil"
  9. "log"
  10. "os"
  11. "testing"
  12. )
  13. type cgroupTestUtil struct {
  14. // data to use in tests.
  15. CgroupData *data
  16. // Path to the mock cgroup directory.
  17. CgroupPath string
  18. // Temporary directory to store mock cgroup filesystem.
  19. tempDir string
  20. t *testing.T
  21. }
  22. // Creates a new test util for the specified subsystem
  23. func NewCgroupTestUtil(subsystem string, t *testing.T) *cgroupTestUtil {
  24. d := &data{}
  25. tempDir, err := ioutil.TempDir("", fmt.Sprintf("%s_cgroup_test", subsystem))
  26. if err != nil {
  27. t.Fatal(err)
  28. }
  29. d.root = tempDir
  30. testCgroupPath, err := d.path(subsystem)
  31. if err != nil {
  32. t.Fatal(err)
  33. }
  34. // Ensure the full mock cgroup path exists.
  35. err = os.MkdirAll(testCgroupPath, 0755)
  36. if err != nil {
  37. t.Fatal(err)
  38. }
  39. return &cgroupTestUtil{CgroupData: d, CgroupPath: testCgroupPath, tempDir: tempDir, t: t}
  40. }
  41. func (c *cgroupTestUtil) cleanup() {
  42. os.RemoveAll(c.tempDir)
  43. }
  44. // Write the specified contents on the mock of the specified cgroup files.
  45. func (c *cgroupTestUtil) writeFileContents(fileContents map[string]string) {
  46. for file, contents := range fileContents {
  47. err := writeFile(c.CgroupPath, file, contents)
  48. if err != nil {
  49. c.t.Fatal(err)
  50. }
  51. }
  52. }
  53. // Expect the specified stats.
  54. func expectStats(t *testing.T, expected, actual map[string]int64) {
  55. for stat, expectedValue := range expected {
  56. actualValue, ok := actual[stat]
  57. if !ok {
  58. log.Printf("Expected stat %s to exist: %s", stat, actual)
  59. t.Fail()
  60. } else if actualValue != expectedValue {
  61. log.Printf("Expected stats %s to have value %f but had %f instead", stat, expectedValue, actualValue)
  62. t.Fail()
  63. }
  64. }
  65. }