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