unit.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. "testing"
  19. "gotest.tools/v3/assert"
  20. "gotest.tools/v3/assert/cmp"
  21. apicontext "github.com/docker/compose-cli/context"
  22. "github.com/docker/compose-cli/context/store"
  23. )
  24. // TestCLI is a helper struct for CLI tests.
  25. type TestCLI struct {
  26. ctx context.Context
  27. writer *os.File
  28. reader *os.File
  29. }
  30. // NewTestCLI returns a CLI testing helper.
  31. func NewTestCLI(t *testing.T) *TestCLI {
  32. dir, err := ioutil.TempDir("", "store")
  33. assert.Check(t, cmp.Nil(err))
  34. originalStdout := os.Stdout
  35. t.Cleanup(func() {
  36. os.Stdout = originalStdout
  37. _ = os.RemoveAll(dir)
  38. })
  39. s, err := store.New(dir)
  40. assert.Check(t, cmp.Nil(err))
  41. err = s.Create("example", "example", "", store.ContextMetadata{})
  42. assert.Check(t, cmp.Nil(err))
  43. ctx := context.Background()
  44. ctx = store.WithContextStore(ctx, s)
  45. ctx = apicontext.WithCurrentContext(ctx, "example")
  46. r, w, err := os.Pipe()
  47. os.Stdout = w
  48. assert.Check(t, cmp.Nil(err))
  49. return &TestCLI{ctx, w, r}
  50. }
  51. // Context returns a configured context
  52. func (c *TestCLI) Context() context.Context {
  53. return c.ctx
  54. }
  55. // GetStdOut returns the output of the command
  56. func (c *TestCLI) GetStdOut() string {
  57. _ = c.writer.Close()
  58. out, _ := ioutil.ReadAll(c.reader)
  59. return string(out)
  60. }