test_cmd.go 7.6 KB

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