clisuite.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. Copyright 2020 Docker, Inc.
  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 framework
  14. import (
  15. "context"
  16. "io/ioutil"
  17. "os"
  18. "github.com/stretchr/testify/require"
  19. "github.com/stretchr/testify/suite"
  20. apicontext "github.com/docker/api/context"
  21. "github.com/docker/api/context/store"
  22. )
  23. // CliSuite is a helper struct that creates a configured context
  24. // and captures the output of a command. it should be used in the
  25. // same way as testify.suite.Suite
  26. type CliSuite struct {
  27. suite.Suite
  28. ctx context.Context
  29. writer *os.File
  30. reader *os.File
  31. OriginalStdout *os.File
  32. storeRoot string
  33. }
  34. // BeforeTest is called by testify.suite
  35. func (sut *CliSuite) BeforeTest(suiteName, testName string) {
  36. ctx := context.Background()
  37. ctx = apicontext.WithCurrentContext(ctx, "example")
  38. dir, err := ioutil.TempDir("", "store")
  39. require.Nil(sut.T(), err)
  40. s, err := store.New(
  41. store.WithRoot(dir),
  42. )
  43. require.Nil(sut.T(), err)
  44. err = s.Create("example", "example", "", store.ContextMetadata{})
  45. require.Nil(sut.T(), err)
  46. sut.storeRoot = dir
  47. ctx = store.WithContextStore(ctx, s)
  48. sut.ctx = ctx
  49. sut.OriginalStdout = os.Stdout
  50. r, w, err := os.Pipe()
  51. require.Nil(sut.T(), err)
  52. os.Stdout = w
  53. sut.writer = w
  54. sut.reader = r
  55. }
  56. // Context returns a configured context
  57. func (sut *CliSuite) Context() context.Context {
  58. return sut.ctx
  59. }
  60. // GetStdOut returns the output of the command
  61. func (sut *CliSuite) GetStdOut() string {
  62. err := sut.writer.Close()
  63. require.Nil(sut.T(), err)
  64. out, _ := ioutil.ReadAll(sut.reader)
  65. return string(out)
  66. }
  67. // AfterTest is called by testify.suite
  68. func (sut *CliSuite) AfterTest(suiteName, testName string) {
  69. os.Stdout = sut.OriginalStdout
  70. err := os.RemoveAll(sut.storeRoot)
  71. require.Nil(sut.T(), err)
  72. }