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