run_test.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. // Copyright 2016 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU 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. // go-ethereum 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 General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. package main
  17. import (
  18. "bufio"
  19. "bytes"
  20. "fmt"
  21. "io"
  22. "io/ioutil"
  23. "os"
  24. "os/exec"
  25. "regexp"
  26. "sync"
  27. "testing"
  28. "text/template"
  29. "time"
  30. )
  31. func tmpdir(t *testing.T) string {
  32. dir, err := ioutil.TempDir("", "geth-test")
  33. if err != nil {
  34. t.Fatal(err)
  35. }
  36. return dir
  37. }
  38. type testgeth struct {
  39. // For total convenience, all testing methods are available.
  40. *testing.T
  41. // template variables for expect
  42. Datadir string
  43. Executable string
  44. Etherbase string
  45. Func template.FuncMap
  46. removeDatadir bool
  47. cmd *exec.Cmd
  48. stdout *bufio.Reader
  49. stdin io.WriteCloser
  50. stderr *testlogger
  51. }
  52. func init() {
  53. // Run the app if we're the child process for runGeth.
  54. if os.Getenv("GETH_TEST_CHILD") != "" {
  55. if err := app.Run(os.Args); err != nil {
  56. fmt.Fprintln(os.Stderr, err)
  57. os.Exit(1)
  58. }
  59. os.Exit(0)
  60. }
  61. }
  62. // spawns geth with the given command line args. If the args don't set --datadir, the
  63. // child g gets a temporary data directory.
  64. func runGeth(t *testing.T, args ...string) *testgeth {
  65. tt := &testgeth{T: t, Executable: os.Args[0]}
  66. for i, arg := range args {
  67. switch {
  68. case arg == "-datadir" || arg == "--datadir":
  69. if i < len(args)-1 {
  70. tt.Datadir = args[i+1]
  71. }
  72. case arg == "-etherbase" || arg == "--etherbase":
  73. if i < len(args)-1 {
  74. tt.Etherbase = args[i+1]
  75. }
  76. }
  77. }
  78. if tt.Datadir == "" {
  79. tt.Datadir = tmpdir(t)
  80. tt.removeDatadir = true
  81. args = append([]string{"-datadir", tt.Datadir}, args...)
  82. // Remove the temporary datadir if something fails below.
  83. defer func() {
  84. if t.Failed() {
  85. os.RemoveAll(tt.Datadir)
  86. }
  87. }()
  88. }
  89. // Boot "geth". This actually runs the test binary but the init function
  90. // will prevent any tests from running.
  91. tt.stderr = &testlogger{t: t}
  92. tt.cmd = exec.Command(os.Args[0], args...)
  93. tt.cmd.Env = append(os.Environ(), "GETH_TEST_CHILD=1")
  94. tt.cmd.Stderr = tt.stderr
  95. stdout, err := tt.cmd.StdoutPipe()
  96. if err != nil {
  97. t.Fatal(err)
  98. }
  99. tt.stdout = bufio.NewReader(stdout)
  100. if tt.stdin, err = tt.cmd.StdinPipe(); err != nil {
  101. t.Fatal(err)
  102. }
  103. if err := tt.cmd.Start(); err != nil {
  104. t.Fatal(err)
  105. }
  106. return tt
  107. }
  108. // InputLine writes the given text to the childs stdin.
  109. // This method can also be called from an expect template, e.g.:
  110. //
  111. // geth.expect(`Passphrase: {{.InputLine "password"}}`)
  112. func (tt *testgeth) InputLine(s string) string {
  113. io.WriteString(tt.stdin, s+"\n")
  114. return ""
  115. }
  116. func (tt *testgeth) setTemplateFunc(name string, fn interface{}) {
  117. if tt.Func == nil {
  118. tt.Func = make(map[string]interface{})
  119. }
  120. tt.Func[name] = fn
  121. }
  122. // expect runs its argument as a template, then expects the
  123. // child process to output the result of the template within 5s.
  124. //
  125. // If the template starts with a newline, the newline is removed
  126. // before matching.
  127. func (tt *testgeth) expect(tplsource string) {
  128. // Generate the expected output by running the template.
  129. tpl := template.Must(template.New("").Funcs(tt.Func).Parse(tplsource))
  130. wantbuf := new(bytes.Buffer)
  131. if err := tpl.Execute(wantbuf, tt); err != nil {
  132. panic(err)
  133. }
  134. // Trim exactly one newline at the beginning. This makes tests look
  135. // much nicer because all expect strings are at column 0.
  136. want := bytes.TrimPrefix(wantbuf.Bytes(), []byte("\n"))
  137. if err := tt.matchExactOutput(want); err != nil {
  138. tt.Fatal(err)
  139. }
  140. tt.Logf("Matched stdout text:\n%s", want)
  141. }
  142. func (tt *testgeth) matchExactOutput(want []byte) error {
  143. buf := make([]byte, len(want))
  144. n := 0
  145. tt.withKillTimeout(func() { n, _ = io.ReadFull(tt.stdout, buf) })
  146. buf = buf[:n]
  147. if n < len(want) || !bytes.Equal(buf, want) {
  148. // Grab any additional buffered output in case of mismatch
  149. // because it might help with debugging.
  150. buf = append(buf, make([]byte, tt.stdout.Buffered())...)
  151. tt.stdout.Read(buf[n:])
  152. // Find the mismatch position.
  153. for i := 0; i < n; i++ {
  154. if want[i] != buf[i] {
  155. return fmt.Errorf("Output mismatch at ◊:\n---------------- (stdout text)\n%s◊%s\n---------------- (expected text)\n%s",
  156. buf[:i], buf[i:n], want)
  157. }
  158. }
  159. if n < len(want) {
  160. return fmt.Errorf("Not enough output, got until ◊:\n---------------- (stdout text)\n%s\n---------------- (expected text)\n%s◊%s",
  161. buf, want[:n], want[n:])
  162. }
  163. }
  164. return nil
  165. }
  166. // expectRegexp expects the child process to output text matching the
  167. // given regular expression within 5s.
  168. //
  169. // Note that an arbitrary amount of output may be consumed by the
  170. // regular expression. This usually means that expect cannot be used
  171. // after expectRegexp.
  172. func (tt *testgeth) expectRegexp(resource string) (*regexp.Regexp, []string) {
  173. var (
  174. re = regexp.MustCompile(resource)
  175. rtee = &runeTee{in: tt.stdout}
  176. matches []int
  177. )
  178. tt.withKillTimeout(func() { matches = re.FindReaderSubmatchIndex(rtee) })
  179. output := rtee.buf.Bytes()
  180. if matches == nil {
  181. tt.Fatalf("Output did not match:\n---------------- (stdout text)\n%s\n---------------- (regular expression)\n%s",
  182. output, resource)
  183. return re, nil
  184. }
  185. tt.Logf("Matched stdout text:\n%s", output)
  186. var submatch []string
  187. for i := 0; i < len(matches); i += 2 {
  188. submatch = append(submatch, string(output[i:i+1]))
  189. }
  190. return re, submatch
  191. }
  192. // expectExit expects the child process to exit within 5s without
  193. // printing any additional text on stdout.
  194. func (tt *testgeth) expectExit() {
  195. var output []byte
  196. tt.withKillTimeout(func() {
  197. output, _ = ioutil.ReadAll(tt.stdout)
  198. })
  199. tt.cmd.Wait()
  200. if tt.removeDatadir {
  201. os.RemoveAll(tt.Datadir)
  202. }
  203. if len(output) > 0 {
  204. tt.Errorf("Unmatched stdout text:\n%s", output)
  205. }
  206. }
  207. func (tt *testgeth) interrupt() {
  208. tt.cmd.Process.Signal(os.Interrupt)
  209. }
  210. // stderrText returns any stderr output written so far.
  211. // The returned text holds all log lines after expectExit has
  212. // returned.
  213. func (tt *testgeth) stderrText() string {
  214. tt.stderr.mu.Lock()
  215. defer tt.stderr.mu.Unlock()
  216. return tt.stderr.buf.String()
  217. }
  218. func (tt *testgeth) withKillTimeout(fn func()) {
  219. timeout := time.AfterFunc(5*time.Second, func() {
  220. tt.Log("killing the child process (timeout)")
  221. tt.cmd.Process.Kill()
  222. if tt.removeDatadir {
  223. os.RemoveAll(tt.Datadir)
  224. }
  225. })
  226. defer timeout.Stop()
  227. fn()
  228. }
  229. // testlogger logs all written lines via t.Log and also
  230. // collects them for later inspection.
  231. type testlogger struct {
  232. t *testing.T
  233. mu sync.Mutex
  234. buf bytes.Buffer
  235. }
  236. func (tl *testlogger) Write(b []byte) (n int, err error) {
  237. lines := bytes.Split(b, []byte("\n"))
  238. for _, line := range lines {
  239. if len(line) > 0 {
  240. tl.t.Logf("(stderr) %s", line)
  241. }
  242. }
  243. tl.mu.Lock()
  244. tl.buf.Write(b)
  245. tl.mu.Unlock()
  246. return len(b), err
  247. }
  248. // runeTee collects text read through it into buf.
  249. type runeTee struct {
  250. in interface {
  251. io.Reader
  252. io.ByteReader
  253. io.RuneReader
  254. }
  255. buf bytes.Buffer
  256. }
  257. func (rtee *runeTee) Read(b []byte) (n int, err error) {
  258. n, err = rtee.in.Read(b)
  259. rtee.buf.Write(b[:n])
  260. return n, err
  261. }
  262. func (rtee *runeTee) ReadRune() (r rune, size int, err error) {
  263. r, size, err = rtee.in.ReadRune()
  264. if err == nil {
  265. rtee.buf.WriteRune(r)
  266. }
  267. return r, size, err
  268. }
  269. func (rtee *runeTee) ReadByte() (b byte, err error) {
  270. b, err = rtee.in.ReadByte()
  271. if err == nil {
  272. rtee.buf.WriteByte(b)
  273. }
  274. return b, err
  275. }