console_test.go 10 KB

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