harness.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. Copyright 2018 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package harness
  14. import (
  15. "io/ioutil"
  16. "os"
  17. "testing"
  18. "k8s.io/klog"
  19. )
  20. // Harness adds some functionality to testing.T, in particular resource cleanup.
  21. // It embeds testing.T, so should have the same signature.
  22. //
  23. // Example usage:
  24. // ```
  25. // func MyTest(tt *testing.T) {
  26. // t := harness.For(tt)
  27. // defer t.Close()
  28. // ...
  29. // }
  30. // ```
  31. type Harness struct {
  32. *testing.T
  33. defers []func() error
  34. }
  35. // For creates a Harness from a testing.T
  36. // Callers must call Close on the Harness so that resources can be cleaned up
  37. func For(t *testing.T) *Harness {
  38. h := &Harness{T: t}
  39. return h
  40. }
  41. // Close cleans up any owned resources, and should be called in a defer block after For
  42. func (h *Harness) Close() {
  43. for _, d := range h.defers {
  44. if err := d(); err != nil {
  45. klog.Warningf("error closing harness: %v", err)
  46. }
  47. }
  48. }
  49. // TempDir is a wrapper around ioutil.TempDir for tests.
  50. // It automatically fails the test if we can't create a temp file,
  51. // and deletes the temp directory when Close is called on the Harness
  52. func (h *Harness) TempDir(baseDir string, prefix string) string {
  53. tempDir, err := ioutil.TempDir(baseDir, prefix)
  54. if err != nil {
  55. h.Fatalf("unable to create tempdir: %v", err)
  56. }
  57. h.defers = append(h.defers, func() error {
  58. return os.RemoveAll(tempDir)
  59. })
  60. return tempDir
  61. }