test_cmd.go 7.0 KB

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