test_cmd.go 7.7 KB

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