github.com/ethereum-optimism/optimism/l2geth@v0.0.0-20230612200230-50b04ade19e3/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/ethereum-optimism/optimism/l2geth/common" 30 "github.com/ethereum-optimism/optimism/l2geth/consensus/ethash" 31 "github.com/ethereum-optimism/optimism/l2geth/core" 32 "github.com/ethereum-optimism/optimism/l2geth/eth" 33 "github.com/ethereum-optimism/optimism/l2geth/internal/jsre" 34 "github.com/ethereum-optimism/optimism/l2geth/miner" 35 "github.com/ethereum-optimism/optimism/l2geth/node" 36 "github.com/ethereum-optimism/optimism/l2geth/rollup" 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 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 Rollup: rollup.Config{}, 109 } 110 if confOverride != nil { 111 confOverride(ethConf) 112 } 113 if err = stack.Register(func(ctx *node.ServiceContext) (node.Service, error) { return eth.New(ctx, ethConf) }); err != nil { 114 t.Fatalf("failed to register Ethereum protocol: %v", err) 115 } 116 // Start the node and assemble the JavaScript console around it 117 if err = stack.Start(); err != nil { 118 t.Fatalf("failed to start test stack: %v", err) 119 } 120 client, err := stack.Attach() 121 if err != nil { 122 t.Fatalf("failed to attach to node: %v", err) 123 } 124 prompter := &hookedPrompter{scheduler: make(chan string)} 125 printer := new(bytes.Buffer) 126 127 console, err := New(Config{ 128 DataDir: stack.DataDir(), 129 DocRoot: "testdata", 130 Client: client, 131 Prompter: prompter, 132 Printer: printer, 133 Preload: []string{"preload.js"}, 134 }) 135 if err != nil { 136 t.Fatalf("failed to create JavaScript console: %v", err) 137 } 138 // Create the final tester and return 139 var ethereum *eth.Ethereum 140 stack.Service(ðereum) 141 142 return &tester{ 143 workspace: workspace, 144 stack: stack, 145 ethereum: ethereum, 146 console: console, 147 input: prompter, 148 output: printer, 149 } 150 } 151 152 // Close cleans up any temporary data folders and held resources. 153 func (env *tester) Close(t *testing.T) { 154 if err := env.console.Stop(false); err != nil { 155 t.Errorf("failed to stop embedded console: %v", err) 156 } 157 if err := env.stack.Close(); err != nil { 158 t.Errorf("failed to tear down embedded node: %v", err) 159 } 160 os.RemoveAll(env.workspace) 161 } 162 163 // Tests that the node lists the correct welcome message, notably that it contains 164 // the instance name, coinbase account, block number, data directory and supported 165 // console modules. 166 func TestWelcome(t *testing.T) { 167 tester := newTester(t, nil) 168 defer tester.Close(t) 169 170 tester.console.Welcome() 171 172 output := tester.output.String() 173 if want := "Welcome"; !strings.Contains(output, want) { 174 t.Fatalf("console output missing welcome message: have\n%s\nwant also %s", output, want) 175 } 176 if want := fmt.Sprintf("instance: %s", testInstance); !strings.Contains(output, want) { 177 t.Fatalf("console output missing instance: have\n%s\nwant also %s", output, want) 178 } 179 if want := fmt.Sprintf("coinbase: %s", testAddress); !strings.Contains(output, want) { 180 t.Fatalf("console output missing coinbase: have\n%s\nwant also %s", output, want) 181 } 182 if want := "at block: 0"; !strings.Contains(output, want) { 183 t.Fatalf("console output missing sync status: have\n%s\nwant also %s", output, want) 184 } 185 if want := fmt.Sprintf("datadir: %s", tester.workspace); !strings.Contains(output, want) { 186 t.Fatalf("console output missing coinbase: have\n%s\nwant also %s", output, want) 187 } 188 } 189 190 // Tests that JavaScript statement evaluation works as intended. 191 func TestEvaluate(t *testing.T) { 192 tester := newTester(t, nil) 193 defer tester.Close(t) 194 195 tester.console.Evaluate("2 + 2") 196 if output := tester.output.String(); !strings.Contains(output, "4") { 197 t.Fatalf("statement evaluation failed: have %s, want %s", output, "4") 198 } 199 } 200 201 // Tests that the console can be used in interactive mode. 202 func TestInteractive(t *testing.T) { 203 // Create a tester and run an interactive console in the background 204 tester := newTester(t, nil) 205 defer tester.Close(t) 206 207 go tester.console.Interactive() 208 209 // Wait for a prompt and send a statement back 210 select { 211 case <-tester.input.scheduler: 212 case <-time.After(time.Second): 213 t.Fatalf("initial prompt timeout") 214 } 215 select { 216 case tester.input.scheduler <- "2+2": 217 case <-time.After(time.Second): 218 t.Fatalf("input feedback timeout") 219 } 220 // Wait for the second prompt and ensure first statement was evaluated 221 select { 222 case <-tester.input.scheduler: 223 case <-time.After(time.Second): 224 t.Fatalf("secondary prompt timeout") 225 } 226 if output := tester.output.String(); !strings.Contains(output, "4") { 227 t.Fatalf("statement evaluation failed: have %s, want %s", output, "4") 228 } 229 } 230 231 // Tests that preloaded JavaScript files have been executed before user is given 232 // input. 233 func TestPreload(t *testing.T) { 234 tester := newTester(t, nil) 235 defer tester.Close(t) 236 237 tester.console.Evaluate("preloaded") 238 if output := tester.output.String(); !strings.Contains(output, "some-preloaded-string") { 239 t.Fatalf("preloaded variable missing: have %s, want %s", output, "some-preloaded-string") 240 } 241 } 242 243 // Tests that JavaScript scripts can be executes from the configured asset path. 244 func TestExecute(t *testing.T) { 245 tester := newTester(t, nil) 246 defer tester.Close(t) 247 248 tester.console.Execute("exec.js") 249 250 tester.console.Evaluate("execed") 251 if output := tester.output.String(); !strings.Contains(output, "some-executed-string") { 252 t.Fatalf("execed variable missing: have %s, want %s", output, "some-executed-string") 253 } 254 } 255 256 // Tests that the JavaScript objects returned by statement executions are properly 257 // pretty printed instead of just displaying "[object]". 258 func TestPrettyPrint(t *testing.T) { 259 tester := newTester(t, nil) 260 defer tester.Close(t) 261 262 tester.console.Evaluate("obj = {int: 1, string: 'two', list: [3, 3, 3], obj: {null: null, func: function(){}}}") 263 264 // Define some specially formatted fields 265 var ( 266 one = jsre.NumberColor("1") 267 two = jsre.StringColor("\"two\"") 268 three = jsre.NumberColor("3") 269 null = jsre.SpecialColor("null") 270 fun = jsre.FunctionColor("function()") 271 ) 272 // Assemble the actual output we're after and verify 273 want := `{ 274 int: ` + one + `, 275 list: [` + three + `, ` + three + `, ` + three + `], 276 obj: { 277 null: ` + null + `, 278 func: ` + fun + ` 279 }, 280 string: ` + two + ` 281 } 282 ` 283 if output := tester.output.String(); output != want { 284 t.Fatalf("pretty print mismatch: have %s, want %s", output, want) 285 } 286 } 287 288 // Tests that the JavaScript exceptions are properly formatted and colored. 289 func TestPrettyError(t *testing.T) { 290 tester := newTester(t, nil) 291 defer tester.Close(t) 292 tester.console.Evaluate("throw 'hello'") 293 294 want := jsre.ErrorColor("hello") + "\n" 295 if output := tester.output.String(); output != want { 296 t.Fatalf("pretty error mismatch: have %s, want %s", output, want) 297 } 298 } 299 300 // Tests that tests if the number of indents for JS input is calculated correct. 301 func TestIndenting(t *testing.T) { 302 testCases := []struct { 303 input string 304 expectedIndentCount int 305 }{ 306 {`var a = 1;`, 0}, 307 {`"some string"`, 0}, 308 {`"some string with (parenthesis`, 0}, 309 {`"some string with newline 310 ("`, 0}, 311 {`function v(a,b) {}`, 0}, 312 {`function f(a,b) { var str = "asd("; };`, 0}, 313 {`function f(a) {`, 1}, 314 {`function f(a, function(b) {`, 2}, 315 {`function f(a, function(b) { 316 var str = "a)}"; 317 });`, 0}, 318 {`function f(a,b) { 319 var str = "a{b(" + a, ", " + b; 320 }`, 0}, 321 {`var str = "\"{"`, 0}, 322 {`var str = "'("`, 0}, 323 {`var str = "\\{"`, 0}, 324 {`var str = "\\\\{"`, 0}, 325 {`var str = 'a"{`, 0}, 326 {`var obj = {`, 1}, 327 {`var obj = { {a:1`, 2}, 328 {`var obj = { {a:1}`, 1}, 329 {`var obj = { {a:1}, b:2}`, 0}, 330 {`var obj = {}`, 0}, 331 {`var obj = { 332 a: 1, b: 2 333 }`, 0}, 334 {`var test = }`, -1}, 335 {`var str = "a\""; var obj = {`, 1}, 336 } 337 338 for i, tt := range testCases { 339 counted := countIndents(tt.input) 340 if counted != tt.expectedIndentCount { 341 t.Errorf("test %d: invalid indenting: have %d, want %d", i, counted, tt.expectedIndentCount) 342 } 343 } 344 }