console_test.go 10 KB

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