input_test.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package cmdline
  2. import (
  3. "fmt"
  4. "os"
  5. "sync"
  6. "testing"
  7. "time"
  8. "github.com/stretchr/testify/assert"
  9. "github.com/tal-tech/go-zero/core/iox"
  10. "github.com/tal-tech/go-zero/core/lang"
  11. )
  12. func TestEnterToContinue(t *testing.T) {
  13. restore, err := iox.RedirectInOut()
  14. assert.Nil(t, err)
  15. defer restore()
  16. var wg sync.WaitGroup
  17. wg.Add(2)
  18. go func() {
  19. defer wg.Done()
  20. fmt.Println()
  21. }()
  22. go func() {
  23. defer wg.Done()
  24. EnterToContinue()
  25. }()
  26. wait := make(chan lang.PlaceholderType)
  27. go func() {
  28. wg.Wait()
  29. close(wait)
  30. }()
  31. select {
  32. case <-time.After(time.Second):
  33. t.Error("timeout")
  34. case <-wait:
  35. }
  36. }
  37. func TestReadLine(t *testing.T) {
  38. r, w, err := os.Pipe()
  39. assert.Nil(t, err)
  40. ow := os.Stdout
  41. os.Stdout = w
  42. or := os.Stdin
  43. os.Stdin = r
  44. defer func() {
  45. os.Stdin = or
  46. os.Stdout = ow
  47. }()
  48. const message = "hello"
  49. var wg sync.WaitGroup
  50. wg.Add(2)
  51. go func() {
  52. defer wg.Done()
  53. fmt.Println(message)
  54. }()
  55. go func() {
  56. defer wg.Done()
  57. input := ReadLine("")
  58. assert.Equal(t, message, input)
  59. }()
  60. wait := make(chan lang.PlaceholderType)
  61. go func() {
  62. wg.Wait()
  63. close(wait)
  64. }()
  65. select {
  66. case <-time.After(time.Second):
  67. t.Error("timeout")
  68. case <-wait:
  69. }
  70. }