test_test.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. // Copyright 2012 Gary Burd
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  4. // not use this file except in compliance with the License. You may obtain
  5. // a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. // License for the specific language governing permissions and limitations
  13. // under the License.
  14. package redis
  15. import (
  16. "bufio"
  17. "errors"
  18. "flag"
  19. "fmt"
  20. "io"
  21. "io/ioutil"
  22. "os"
  23. "os/exec"
  24. "strconv"
  25. "strings"
  26. "sync"
  27. "testing"
  28. "time"
  29. )
  30. var (
  31. ErrNegativeInt = errNegativeInt
  32. serverPath = flag.String("redis-server", "redis-server", "Path to redis server binary")
  33. serverBasePort = flag.Int("redis-port", 16379, "Beginning of port range for test servers")
  34. serverLogName = flag.String("redis-log", "", "Write Redis server logs to `filename`")
  35. serverLog = ioutil.Discard
  36. defaultServerMu sync.Mutex
  37. defaultServer *Server
  38. defaultServerErr error
  39. )
  40. type Server struct {
  41. name string
  42. cmd *exec.Cmd
  43. done chan struct{}
  44. }
  45. func NewServer(name string, args ...string) (*Server, error) {
  46. s := &Server{
  47. name: name,
  48. cmd: exec.Command(*serverPath, args...),
  49. done: make(chan struct{}),
  50. }
  51. r, err := s.cmd.StdoutPipe()
  52. if err != nil {
  53. return nil, err
  54. }
  55. err = s.cmd.Start()
  56. if err != nil {
  57. return nil, err
  58. }
  59. ready := make(chan error, 1)
  60. go s.watch(r, ready)
  61. select {
  62. case err = <-ready:
  63. case <-time.After(time.Second * 10):
  64. err = errors.New("timeout waiting for server to start")
  65. }
  66. if err != nil {
  67. s.Stop()
  68. return nil, err
  69. }
  70. return s, nil
  71. }
  72. func (s *Server) watch(r io.Reader, ready chan error) {
  73. fmt.Fprintf(serverLog, "%d START %s \n", s.cmd.Process.Pid, s.name)
  74. var listening bool
  75. var text string
  76. scn := bufio.NewScanner(r)
  77. for scn.Scan() {
  78. text = scn.Text()
  79. fmt.Fprintf(serverLog, "%s\n", text)
  80. if !listening {
  81. if strings.Contains(text, "The server is now ready to accept connections on port") {
  82. listening = true
  83. ready <- nil
  84. }
  85. }
  86. }
  87. if !listening {
  88. ready <- fmt.Errorf("server exited: %s", text)
  89. }
  90. s.cmd.Wait()
  91. fmt.Fprintf(serverLog, "%d STOP %s \n", s.cmd.Process.Pid, s.name)
  92. close(s.done)
  93. }
  94. func (s *Server) Stop() {
  95. s.cmd.Process.Signal(os.Interrupt)
  96. <-s.done
  97. }
  98. // stopDefaultServer stops the server created by DialDefaultServer.
  99. func stopDefaultServer() {
  100. defaultServerMu.Lock()
  101. defer defaultServerMu.Unlock()
  102. if defaultServer != nil {
  103. defaultServer.Stop()
  104. defaultServer = nil
  105. }
  106. }
  107. // startDefaultServer starts the default server if not already running.
  108. func startDefaultServer() error {
  109. defaultServerMu.Lock()
  110. defer defaultServerMu.Unlock()
  111. if defaultServer != nil || defaultServerErr != nil {
  112. return defaultServerErr
  113. }
  114. defaultServer, defaultServerErr = NewServer(
  115. "default",
  116. "--port", strconv.Itoa(*serverBasePort),
  117. "--save", "",
  118. "--appendonly", "no")
  119. return defaultServerErr
  120. }
  121. // DialDefaultServer starts the test server if not already started and dials a
  122. // connection to the server.
  123. func DialDefaultServer() (Conn, error) {
  124. if err := startDefaultServer(); err != nil {
  125. return nil, err
  126. }
  127. c, err := Dial("tcp", fmt.Sprintf(":%d", *serverBasePort), DialReadTimeout(1*time.Second), DialWriteTimeout(1*time.Second))
  128. if err != nil {
  129. return nil, err
  130. }
  131. c.Do("FLUSHDB")
  132. return c, nil
  133. }
  134. func TestMain(m *testing.M) {
  135. os.Exit(func() int {
  136. flag.Parse()
  137. var f *os.File
  138. if *serverLogName != "" {
  139. var err error
  140. f, err = os.OpenFile(*serverLogName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600)
  141. if err != nil {
  142. fmt.Fprintf(os.Stderr, "Error opening redis-log: %v\n", err)
  143. return 1
  144. }
  145. defer f.Close()
  146. serverLog = f
  147. }
  148. defer stopDefaultServer()
  149. return m.Run()
  150. }())
  151. }