console_test.go 10 KB

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