clisuite.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package framework
  2. import (
  3. "context"
  4. "io/ioutil"
  5. "os"
  6. "github.com/stretchr/testify/require"
  7. "github.com/stretchr/testify/suite"
  8. apicontext "github.com/docker/api/context"
  9. "github.com/docker/api/context/store"
  10. )
  11. // CliSuite is a helper struct that creates a configured context
  12. // and captures the output of a command. it should be used in the
  13. // same way as testify.suite.Suite
  14. type CliSuite struct {
  15. suite.Suite
  16. ctx context.Context
  17. writer *os.File
  18. reader *os.File
  19. OriginalStdout *os.File
  20. storeRoot string
  21. }
  22. // BeforeTest is called by testify.suite
  23. func (sut *CliSuite) BeforeTest(suiteName, testName string) {
  24. ctx := context.Background()
  25. ctx = apicontext.WithCurrentContext(ctx, "example")
  26. dir, err := ioutil.TempDir("", "store")
  27. require.Nil(sut.T(), err)
  28. s, err := store.New(
  29. store.WithRoot(dir),
  30. )
  31. require.Nil(sut.T(), err)
  32. err = s.Create("example", "example", "", store.ContextMetadata{})
  33. require.Nil(sut.T(), err)
  34. sut.storeRoot = dir
  35. ctx = store.WithContextStore(ctx, s)
  36. sut.ctx = ctx
  37. sut.OriginalStdout = os.Stdout
  38. r, w, err := os.Pipe()
  39. require.Nil(sut.T(), err)
  40. os.Stdout = w
  41. sut.writer = w
  42. sut.reader = r
  43. }
  44. // Context returns a configured context
  45. func (sut *CliSuite) Context() context.Context {
  46. return sut.ctx
  47. }
  48. // GetStdOut returns the output of the command
  49. func (sut *CliSuite) GetStdOut() string {
  50. err := sut.writer.Close()
  51. require.Nil(sut.T(), err)
  52. out, _ := ioutil.ReadAll(sut.reader)
  53. return string(out)
  54. }
  55. // AfterTest is called by testify.suite
  56. func (sut *CliSuite) AfterTest(suiteName, testName string) {
  57. os.Stdout = sut.OriginalStdout
  58. err := os.RemoveAll(sut.storeRoot)
  59. require.Nil(sut.T(), err)
  60. }