test_cmd.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. // Copyright 2017 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package cmdtest
  17. import (
  18. "bufio"
  19. "bytes"
  20. "fmt"
  21. "io"
  22. "io/ioutil"
  23. "os"
  24. "os/exec"
  25. "regexp"
  26. "strings"
  27. "sync"
  28. "syscall"
  29. "testing"
  30. "text/template"
  31. "time"
  32. "github.com/docker/docker/pkg/reexec"
  33. )
  34. func NewTestCmd(t *testing.T, data interface{}) *TestCmd {
  35. return &TestCmd{T: t, Data: data}
  36. }
  37. type TestCmd struct {
  38. // For total convenience, all testing methods are available.
  39. *testing.T
  40. Func template.FuncMap
  41. Data interface{}
  42. Cleanup func()
  43. cmd *exec.Cmd
  44. stdout *bufio.Reader
  45. stdin io.WriteCloser
  46. stderr *testlogger
  47. // Err will contain the process exit error or interrupt signal error
  48. Err error
  49. }
  50. // Run exec's the current binary using name as argv[0] which will trigger the
  51. // reexec init function for that name (e.g. "geth-test" in cmd/geth/run_test.go)
  52. func (tt *TestCmd) Run(name string, args ...string) {
  53. tt.stderr = &testlogger{t: tt.T}
  54. tt.cmd = &exec.Cmd{
  55. Path: reexec.Self(),
  56. Args: append([]string{name}, args...),
  57. Stderr: tt.stderr,
  58. }
  59. stdout, err := tt.cmd.StdoutPipe()
  60. if err != nil {
  61. tt.Fatal(err)
  62. }
  63. tt.stdout = bufio.NewReader(stdout)
  64. if tt.stdin, err = tt.cmd.StdinPipe(); err != nil {
  65. tt.Fatal(err)
  66. }
  67. if err := tt.cmd.Start(); err != nil {
  68. tt.Fatal(err)
  69. }
  70. }
  71. // InputLine writes the given text to the child's stdin.
  72. // This method can also be called from an expect template, e.g.:
  73. //
  74. // geth.expect(`Passphrase: {{.InputLine "password"}}`)
  75. func (tt *TestCmd) InputLine(s string) string {
  76. io.WriteString(tt.stdin, s+"\n")
  77. return ""
  78. }
  79. func (tt *TestCmd) SetTemplateFunc(name string, fn interface{}) {
  80. if tt.Func == nil {
  81. tt.Func = make(map[string]interface{})
  82. }
  83. tt.Func[name] = fn
  84. }
  85. // Expect runs its argument as a template, then expects the
  86. // child process to output the result of the template within 5s.
  87. //
  88. // If the template starts with a newline, the newline is removed
  89. // before matching.
  90. func (tt *TestCmd) Expect(tplsource string) {
  91. // Generate the expected output by running the template.
  92. tpl := template.Must(template.New("").Funcs(tt.Func).Parse(tplsource))
  93. wantbuf := new(bytes.Buffer)
  94. if err := tpl.Execute(wantbuf, tt.Data); err != nil {
  95. panic(err)
  96. }
  97. // Trim exactly one newline at the beginning. This makes tests look
  98. // much nicer because all expect strings are at column 0.
  99. want := bytes.TrimPrefix(wantbuf.Bytes(), []byte("\n"))
  100. if err := tt.matchExactOutput(want); err != nil {
  101. tt.Fatal(err)
  102. }
  103. tt.Logf("Matched stdout text:\n%s", want)
  104. }
  105. func (tt *TestCmd) matchExactOutput(want []byte) error {
  106. buf := make([]byte, len(want))
  107. n := 0
  108. tt.withKillTimeout(func() { n, _ = io.ReadFull(tt.stdout, buf) })
  109. buf = buf[:n]
  110. if n < len(want) || !bytes.Equal(buf, want) {
  111. // Grab any additional buffered output in case of mismatch
  112. // because it might help with debugging.
  113. buf = append(buf, make([]byte, tt.stdout.Buffered())...)
  114. tt.stdout.Read(buf[n:])
  115. // Find the mismatch position.
  116. for i := 0; i < n; i++ {
  117. if want[i] != buf[i] {
  118. return fmt.Errorf("output mismatch at ◊:\n---------------- (stdout text)\n%s◊%s\n---------------- (expected text)\n%s",
  119. buf[:i], buf[i:n], want)
  120. }
  121. }
  122. if n < len(want) {
  123. return fmt.Errorf("not enough output, got until ◊:\n---------------- (stdout text)\n%s\n---------------- (expected text)\n%s◊%s",
  124. buf, want[:n], want[n:])
  125. }
  126. }
  127. return nil
  128. }
  129. // ExpectRegexp expects the child process to output text matching the
  130. // given regular expression within 5s.
  131. //
  132. // Note that an arbitrary amount of output may be consumed by the
  133. // regular expression. This usually means that expect cannot be used
  134. // after ExpectRegexp.
  135. func (tt *TestCmd) ExpectRegexp(regex string) (*regexp.Regexp, []string) {
  136. regex = strings.TrimPrefix(regex, "\n")
  137. var (
  138. re = regexp.MustCompile(regex)
  139. rtee = &runeTee{in: tt.stdout}
  140. matches []int
  141. )
  142. tt.withKillTimeout(func() { matches = re.FindReaderSubmatchIndex(rtee) })
  143. output := rtee.buf.Bytes()
  144. if matches == nil {
  145. tt.Fatalf("Output did not match:\n---------------- (stdout text)\n%s\n---------------- (regular expression)\n%s",
  146. output, regex)
  147. return re, nil
  148. }
  149. tt.Logf("Matched stdout text:\n%s", output)
  150. var submatches []string
  151. for i := 0; i < len(matches); i += 2 {
  152. submatch := string(output[matches[i]:matches[i+1]])
  153. submatches = append(submatches, submatch)
  154. }
  155. return re, submatches
  156. }
  157. // ExpectExit expects the child process to exit within 5s without
  158. // printing any additional text on stdout.
  159. func (tt *TestCmd) ExpectExit() {
  160. var output []byte
  161. tt.withKillTimeout(func() {
  162. output, _ = ioutil.ReadAll(tt.stdout)
  163. })
  164. tt.WaitExit()
  165. if tt.Cleanup != nil {
  166. tt.Cleanup()
  167. }
  168. if len(output) > 0 {
  169. tt.Errorf("Unmatched stdout text:\n%s", output)
  170. }
  171. }
  172. func (tt *TestCmd) WaitExit() {
  173. tt.Err = tt.cmd.Wait()
  174. }
  175. func (tt *TestCmd) Interrupt() {
  176. tt.Err = tt.cmd.Process.Signal(os.Interrupt)
  177. }
  178. // ExitStatus exposes the process' OS exit code
  179. // It will only return a valid value after the process has finished.
  180. func (tt *TestCmd) ExitStatus() int {
  181. if tt.Err != nil {
  182. exitErr := tt.Err.(*exec.ExitError)
  183. if exitErr != nil {
  184. if status, ok := exitErr.Sys().(syscall.WaitStatus); ok {
  185. return status.ExitStatus()
  186. }
  187. }
  188. }
  189. return 0
  190. }
  191. // StderrText returns any stderr output written so far.
  192. // The returned text holds all log lines after ExpectExit has
  193. // returned.
  194. func (tt *TestCmd) StderrText() string {
  195. tt.stderr.mu.Lock()
  196. defer tt.stderr.mu.Unlock()
  197. return tt.stderr.buf.String()
  198. }
  199. func (tt *TestCmd) CloseStdin() {
  200. tt.stdin.Close()
  201. }
  202. func (tt *TestCmd) Kill() {
  203. tt.cmd.Process.Kill()
  204. if tt.Cleanup != nil {
  205. tt.Cleanup()
  206. }
  207. }
  208. func (tt *TestCmd) withKillTimeout(fn func()) {
  209. timeout := time.AfterFunc(5*time.Second, func() {
  210. tt.Log("killing the child process (timeout)")
  211. tt.Kill()
  212. })
  213. defer timeout.Stop()
  214. fn()
  215. }
  216. // testlogger logs all written lines via t.Log and also
  217. // collects them for later inspection.
  218. type testlogger struct {
  219. t *testing.T
  220. mu sync.Mutex
  221. buf bytes.Buffer
  222. }
  223. func (tl *testlogger) Write(b []byte) (n int, err error) {
  224. lines := bytes.Split(b, []byte("\n"))
  225. for _, line := range lines {
  226. if len(line) > 0 {
  227. tl.t.Logf("(stderr) %s", line)
  228. }
  229. }
  230. tl.mu.Lock()
  231. tl.buf.Write(b)
  232. tl.mu.Unlock()
  233. return len(b), err
  234. }
  235. // runeTee collects text read through it into buf.
  236. type runeTee struct {
  237. in interface {
  238. io.Reader
  239. io.ByteReader
  240. io.RuneReader
  241. }
  242. buf bytes.Buffer
  243. }
  244. func (rtee *runeTee) Read(b []byte) (n int, err error) {
  245. n, err = rtee.in.Read(b)
  246. rtee.buf.Write(b[:n])
  247. return n, err
  248. }
  249. func (rtee *runeTee) ReadRune() (r rune, size int, err error) {
  250. r, size, err = rtee.in.ReadRune()
  251. if err == nil {
  252. rtee.buf.WriteRune(r)
  253. }
  254. return r, size, err
  255. }
  256. func (rtee *runeTee) ReadByte() (b byte, err error) {
  257. b, err = rtee.in.ReadByte()
  258. if err == nil {
  259. rtee.buf.WriteByte(b)
  260. }
  261. return b, err
  262. }