console_test.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. // Copyright 2015 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 console
  17. import (
  18. "bytes"
  19. "errors"
  20. "fmt"
  21. "io/ioutil"
  22. "math/big"
  23. "os"
  24. "path/filepath"
  25. "strings"
  26. "testing"
  27. "time"
  28. "github.com/ethereum/go-ethereum/accounts"
  29. "github.com/ethereum/go-ethereum/common"
  30. "github.com/ethereum/go-ethereum/core"
  31. "github.com/ethereum/go-ethereum/eth"
  32. "github.com/ethereum/go-ethereum/internal/jsre"
  33. "github.com/ethereum/go-ethereum/node"
  34. )
  35. const (
  36. testInstance = "console-tester"
  37. testAddress = "0x8605cdbbdb6d264aa742e77020dcbc58fcdce182"
  38. )
  39. // hookedPrompter implements UserPrompter to simulate use input via channels.
  40. type hookedPrompter struct {
  41. scheduler chan string
  42. }
  43. func (p *hookedPrompter) PromptInput(prompt string) (string, error) {
  44. // Send the prompt to the tester
  45. select {
  46. case p.scheduler <- prompt:
  47. case <-time.After(time.Second):
  48. return "", errors.New("prompt timeout")
  49. }
  50. // Retrieve the response and feed to the console
  51. select {
  52. case input := <-p.scheduler:
  53. return input, nil
  54. case <-time.After(time.Second):
  55. return "", errors.New("input timeout")
  56. }
  57. }
  58. func (p *hookedPrompter) PromptPassword(prompt string) (string, error) {
  59. return "", errors.New("not implemented")
  60. }
  61. func (p *hookedPrompter) PromptConfirm(prompt string) (bool, error) {
  62. return false, errors.New("not implemented")
  63. }
  64. func (p *hookedPrompter) SetScrollHistory(history []string) {}
  65. func (p *hookedPrompter) SetWordCompleter(completer WordCompleter) {}
  66. // tester is a console test environment for the console tests to operate on.
  67. type tester struct {
  68. workspace string
  69. stack *node.Node
  70. ethereum *eth.Ethereum
  71. console *Console
  72. input *hookedPrompter
  73. output *bytes.Buffer
  74. lastConfirm string
  75. }
  76. // newTester creates a test environment based on which the console can operate.
  77. // Please ensure you call Close() on the returned tester to avoid leaks.
  78. func newTester(t *testing.T, confOverride func(*eth.Config)) *tester {
  79. // Create a temporary storage for the node keys and initialize it
  80. workspace, err := ioutil.TempDir("", "console-tester-")
  81. if err != nil {
  82. t.Fatalf("failed to create temporary keystore: %v", err)
  83. }
  84. accman := accounts.NewPlaintextManager(filepath.Join(workspace, "keystore"))
  85. // Create a networkless protocol stack and start an Ethereum service within
  86. stack, err := node.New(&node.Config{DataDir: workspace, Name: testInstance, NoDiscovery: true})
  87. if err != nil {
  88. t.Fatalf("failed to create node: %v", err)
  89. }
  90. ethConf := &eth.Config{
  91. ChainConfig: &core.ChainConfig{HomesteadBlock: new(big.Int)},
  92. Etherbase: common.HexToAddress(testAddress),
  93. AccountManager: accman,
  94. PowTest: true,
  95. }
  96. if confOverride != nil {
  97. confOverride(ethConf)
  98. }
  99. if err = stack.Register(func(ctx *node.ServiceContext) (node.Service, error) { return eth.New(ctx, ethConf) }); err != nil {
  100. t.Fatalf("failed to register Ethereum protocol: %v", err)
  101. }
  102. // Start the node and assemble the JavaScript console around it
  103. if err = stack.Start(); err != nil {
  104. t.Fatalf("failed to start test stack: %v", err)
  105. }
  106. client, err := stack.Attach()
  107. if err != nil {
  108. t.Fatalf("failed to attach to node: %v", err)
  109. }
  110. prompter := &hookedPrompter{scheduler: make(chan string)}
  111. printer := new(bytes.Buffer)
  112. console, err := New(Config{
  113. DataDir: stack.DataDir(),
  114. DocRoot: "testdata",
  115. Client: client,
  116. Prompter: prompter,
  117. Printer: printer,
  118. Preload: []string{"preload.js"},
  119. })
  120. if err != nil {
  121. t.Fatalf("failed to create JavaScript console: %v", err)
  122. }
  123. // Create the final tester and return
  124. var ethereum *eth.Ethereum
  125. stack.Service(&ethereum)
  126. return &tester{
  127. workspace: workspace,
  128. stack: stack,
  129. ethereum: ethereum,
  130. console: console,
  131. input: prompter,
  132. output: printer,
  133. }
  134. }
  135. // Close cleans up any temporary data folders and held resources.
  136. func (env *tester) Close(t *testing.T) {
  137. if err := env.console.Stop(false); err != nil {
  138. t.Errorf("failed to stop embedded console: %v", err)
  139. }
  140. if err := env.stack.Stop(); err != nil {
  141. t.Errorf("failed to stop embedded node: %v", err)
  142. }
  143. os.RemoveAll(env.workspace)
  144. }
  145. // Tests that the node lists the correct welcome message, notably that it contains
  146. // the instance name, coinbase account, block number, data directory and supported
  147. // console modules.
  148. func TestWelcome(t *testing.T) {
  149. tester := newTester(t, nil)
  150. defer tester.Close(t)
  151. tester.console.Welcome()
  152. output := string(tester.output.Bytes())
  153. if want := "Welcome"; !strings.Contains(output, want) {
  154. t.Fatalf("console output missing welcome message: have\n%s\nwant also %s", output, want)
  155. }
  156. if want := fmt.Sprintf("instance: %s", testInstance); !strings.Contains(output, want) {
  157. t.Fatalf("console output missing instance: have\n%s\nwant also %s", output, want)
  158. }
  159. if want := fmt.Sprintf("coinbase: %s", testAddress); !strings.Contains(output, want) {
  160. t.Fatalf("console output missing coinbase: have\n%s\nwant also %s", output, want)
  161. }
  162. if want := "at block: 0"; !strings.Contains(output, want) {
  163. t.Fatalf("console output missing sync status: have\n%s\nwant also %s", output, want)
  164. }
  165. if want := fmt.Sprintf("datadir: %s", tester.workspace); !strings.Contains(output, want) {
  166. t.Fatalf("console output missing coinbase: have\n%s\nwant also %s", output, want)
  167. }
  168. }
  169. // Tests that JavaScript statement evaluation works as intended.
  170. func TestEvaluate(t *testing.T) {
  171. tester := newTester(t, nil)
  172. defer tester.Close(t)
  173. tester.console.Evaluate("2 + 2")
  174. if output := string(tester.output.Bytes()); !strings.Contains(output, "4") {
  175. t.Fatalf("statement evaluation failed: have %s, want %s", output, "4")
  176. }
  177. }
  178. // Tests that the console can be used in interactive mode.
  179. func TestInteractive(t *testing.T) {
  180. // Create a tester and run an interactive console in the background
  181. tester := newTester(t, nil)
  182. defer tester.Close(t)
  183. go tester.console.Interactive()
  184. // Wait for a promt and send a statement back
  185. select {
  186. case <-tester.input.scheduler:
  187. case <-time.After(time.Second):
  188. t.Fatalf("initial prompt timeout")
  189. }
  190. select {
  191. case tester.input.scheduler <- "2+2":
  192. case <-time.After(time.Second):
  193. t.Fatalf("input feedback timeout")
  194. }
  195. // Wait for the second promt and ensure first statement was evaluated
  196. select {
  197. case <-tester.input.scheduler:
  198. case <-time.After(time.Second):
  199. t.Fatalf("secondary prompt timeout")
  200. }
  201. if output := string(tester.output.Bytes()); !strings.Contains(output, "4") {
  202. t.Fatalf("statement evaluation failed: have %s, want %s", output, "4")
  203. }
  204. }
  205. // Tests that preloaded JavaScript files have been executed before user is given
  206. // input.
  207. func TestPreload(t *testing.T) {
  208. tester := newTester(t, nil)
  209. defer tester.Close(t)
  210. tester.console.Evaluate("preloaded")
  211. if output := string(tester.output.Bytes()); !strings.Contains(output, "some-preloaded-string") {
  212. t.Fatalf("preloaded variable missing: have %s, want %s", output, "some-preloaded-string")
  213. }
  214. }
  215. // Tests that JavaScript scripts can be executes from the configured asset path.
  216. func TestExecute(t *testing.T) {
  217. tester := newTester(t, nil)
  218. defer tester.Close(t)
  219. tester.console.Execute("exec.js")
  220. tester.console.Evaluate("execed")
  221. if output := string(tester.output.Bytes()); !strings.Contains(output, "some-executed-string") {
  222. t.Fatalf("execed variable missing: have %s, want %s", output, "some-executed-string")
  223. }
  224. }
  225. // Tests that the JavaScript objects returned by statement executions are properly
  226. // pretty printed instead of just displaing "[object]".
  227. func TestPrettyPrint(t *testing.T) {
  228. tester := newTester(t, nil)
  229. defer tester.Close(t)
  230. tester.console.Evaluate("obj = {int: 1, string: 'two', list: [3, 3, 3], obj: {null: null, func: function(){}}}")
  231. // Define some specially formatted fields
  232. var (
  233. one = jsre.NumberColor("1")
  234. two = jsre.StringColor("\"two\"")
  235. three = jsre.NumberColor("3")
  236. null = jsre.SpecialColor("null")
  237. fun = jsre.FunctionColor("function()")
  238. )
  239. // Assemble the actual output we're after and verify
  240. want := `{
  241. int: ` + one + `,
  242. list: [` + three + `, ` + three + `, ` + three + `],
  243. obj: {
  244. null: ` + null + `,
  245. func: ` + fun + `
  246. },
  247. string: ` + two + `
  248. }
  249. `
  250. if output := string(tester.output.Bytes()); output != want {
  251. t.Fatalf("pretty print mismatch: have %s, want %s", output, want)
  252. }
  253. }