clisuite.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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", store.TypedContext{
  33. Type: "example",
  34. })
  35. require.Nil(sut.T(), err)
  36. sut.storeRoot = dir
  37. ctx = store.WithContextStore(ctx, s)
  38. sut.ctx = ctx
  39. sut.OriginalStdout = os.Stdout
  40. r, w, err := os.Pipe()
  41. require.Nil(sut.T(), err)
  42. os.Stdout = w
  43. sut.writer = w
  44. sut.reader = r
  45. }
  46. // Context returns a configured context
  47. func (sut *CliSuite) Context() context.Context {
  48. return sut.ctx
  49. }
  50. // GetStdOut returns the output of the command
  51. func (sut *CliSuite) GetStdOut() string {
  52. err := sut.writer.Close()
  53. require.Nil(sut.T(), err)
  54. out, _ := ioutil.ReadAll(sut.reader)
  55. return string(out)
  56. }
  57. // AfterTest is called by testify.suite
  58. func (sut *CliSuite) AfterTest(suiteName, testName string) {
  59. os.Stdout = sut.OriginalStdout
  60. err := os.RemoveAll(sut.storeRoot)
  61. require.Nil(sut.T(), err)
  62. }