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