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