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