ps_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package cmd
  2. import (
  3. "context"
  4. "io/ioutil"
  5. "os"
  6. "testing"
  7. "github.com/stretchr/testify/assert"
  8. "github.com/stretchr/testify/require"
  9. "github.com/stretchr/testify/suite"
  10. "gotest.tools/v3/golden"
  11. apicontext "github.com/docker/api/context"
  12. "github.com/docker/api/context/store"
  13. _ "github.com/docker/api/example"
  14. )
  15. type PsSuite struct {
  16. suite.Suite
  17. ctx context.Context
  18. writer *os.File
  19. reader *os.File
  20. originalStdout *os.File
  21. storeRoot string
  22. }
  23. func (sut *PsSuite) 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. func (sut *PsSuite) getStdOut() string {
  47. err := sut.writer.Close()
  48. require.Nil(sut.T(), err)
  49. out, _ := ioutil.ReadAll(sut.reader)
  50. return string(out)
  51. }
  52. func (sut *PsSuite) AfterTest(suiteName, testName string) {
  53. os.Stdout = sut.originalStdout
  54. err := os.RemoveAll(sut.storeRoot)
  55. require.Nil(sut.T(), err)
  56. }
  57. func (sut *PsSuite) TestPs() {
  58. opts := psOpts{
  59. quiet: false,
  60. }
  61. err := runPs(sut.ctx, opts)
  62. assert.NilError(sut.T(), err)
  63. golden.Assert(sut.T(), sut.getStdOut(), "ps-out.golden")
  64. }
  65. func (sut *PsSuite) TestPsQuiet() {
  66. opts := psOpts{
  67. quiet: true,
  68. }
  69. err := runPs(sut.ctx, opts)
  70. assert.NilError(sut.T(), err)
  71. golden.Assert(sut.T(), sut.getStdOut(), "ps-out-quiet.golden")
  72. }
  73. func TestPs(t *testing.T) {
  74. suite.Run(t, new(PsSuite))
  75. }