github.com/klaytn/klaytn@v1.12.1/console/console_test.go (about) 1 // Modifications Copyright 2018 The klaytn Authors 2 // Copyright 2015 The go-ethereum Authors 3 // This file is part of the go-ethereum library. 4 // 5 // The go-ethereum library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The go-ethereum library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 17 // 18 // This file is derived from console/console_test.go (2018/06/04). 19 // Modified and improved for the klaytn development. 20 21 package console 22 23 import ( 24 "bytes" 25 "errors" 26 "fmt" 27 "os" 28 "strings" 29 "testing" 30 "time" 31 32 "github.com/klaytn/klaytn/blockchain" 33 "github.com/klaytn/klaytn/common" 34 "github.com/klaytn/klaytn/console/jsre" 35 "github.com/klaytn/klaytn/node" 36 "github.com/klaytn/klaytn/node/cn" 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 69 func (p *hookedPrompter) PromptConfirm(prompt string) (bool, error) { 70 return false, errors.New("not implemented") 71 } 72 func (p *hookedPrompter) SetHistory(history []string) {} 73 func (p *hookedPrompter) AppendHistory(command string) {} 74 func (p *hookedPrompter) ClearHistory() {} 75 func (p *hookedPrompter) SetWordCompleter(completer WordCompleter) {} 76 77 // tester is a console test environment for the console tests to operate on. 78 type tester struct { 79 workspace string 80 stack *node.Node 81 cn *cn.CN 82 console *Console 83 input *hookedPrompter 84 output *bytes.Buffer 85 } 86 87 // newTester creates a test environment based on which the console can operate. 88 // Please ensure you call Close() on the returned tester to avoid leaks. 89 func newTester(t *testing.T, confOverride func(*cn.Config)) *tester { 90 // Create a temporary storage for the node keys and initialize it 91 workspace, err := os.MkdirTemp("", "console-tester-") 92 if err != nil { 93 t.Fatalf("failed to create temporary keystore: %v", err) 94 } 95 96 // Create a networkless protocol stack and start a Klaytn service within 97 stack, err := node.New(&node.Config{DataDir: workspace, UseLightweightKDF: true, Name: testInstance}) 98 if err != nil { 99 t.Fatalf("failed to create node: %v", err) 100 } 101 cnConf := &cn.Config{ 102 Genesis: blockchain.DefaultGenesisBlock(), 103 ServiceChainSigner: common.HexToAddress(testAddress), 104 } 105 if confOverride != nil { 106 confOverride(cnConf) 107 } 108 if err = stack.Register(func(ctx *node.ServiceContext) (node.Service, error) { return cn.New(ctx, cnConf) }); err != nil { 109 t.Fatalf("failed to register Klaytn protocol: %v", err) 110 } 111 // Start the node and assemble the JavaScript console around it 112 if err = stack.Start(); err != nil { 113 t.Fatalf("failed to start test stack: %v", err) 114 } 115 client, err := stack.Attach() 116 if err != nil { 117 t.Fatalf("failed to attach to node: %v", err) 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 var cn *cn.CN 135 stack.Service(&cn) 136 137 return &tester{ 138 workspace: workspace, 139 stack: stack, 140 cn: cn, 141 console: console, 142 input: prompter, 143 output: printer, 144 } 145 } 146 147 // Close cleans up any temporary data folders and held resources. 148 func (env *tester) Close(t *testing.T) { 149 if err := env.console.Stop(false); err != nil { 150 t.Errorf("failed to stop embedded console: %v", err) 151 } 152 if err := env.stack.Stop(); err != nil { 153 t.Errorf("failed to stop embedded node: %v", err) 154 } 155 os.RemoveAll(env.workspace) 156 } 157 158 // Tests that the node lists the correct welcome message, notably that it contains 159 // the instance name, block number, data directory and supported 160 // console modules. 161 func TestWelcome(t *testing.T) { 162 tester := newTester(t, nil) 163 defer tester.Close(t) 164 165 tester.console.Welcome() 166 167 output := tester.output.String() 168 if want := "Welcome"; !strings.Contains(output, want) { 169 t.Fatalf("console output missing welcome message: have\n%s\nwant also %s", output, want) 170 } 171 if want := fmt.Sprintf("instance: %s", testInstance); !strings.Contains(output, want) { 172 t.Fatalf("console output missing instance: 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 JavaScript scripts can be executes from the configured asset path. 233 func TestExecute(t *testing.T) { 234 tester := newTester(t, nil) 235 defer tester.Close(t) 236 237 tester.console.Execute("exec.js") 238 239 tester.console.Evaluate("execed") 240 if output := tester.output.String(); !strings.Contains(output, "some-executed-string") { 241 t.Fatalf("execed variable missing: have %s, want %s", output, "some-executed-string") 242 } 243 } 244 245 // Tests that the JavaScript objects returned by statement executions are properly 246 // pretty printed instead of just displaying "[object]". 247 func TestPrettyPrint(t *testing.T) { 248 tester := newTester(t, nil) 249 defer tester.Close(t) 250 251 tester.console.Evaluate("obj = {int: 1, string: 'two', list: [3, 3, 3], obj: {null: null, func: function(){}}}") 252 253 // Define some specially formatted fields 254 var ( 255 one = jsre.NumberColor("1") 256 two = jsre.StringColor("\"two\"") 257 three = jsre.NumberColor("3") 258 null = jsre.SpecialColor("null") 259 fun = jsre.FunctionColor("function()") 260 ) 261 // Assemble the actual output we're after and verify 262 want := `{ 263 int: ` + one + `, 264 list: [` + three + `, ` + three + `, ` + three + `], 265 obj: { 266 null: ` + null + `, 267 func: ` + fun + ` 268 }, 269 string: ` + two + ` 270 } 271 ` 272 if output := tester.output.String(); output != want { 273 t.Fatalf("pretty print mismatch: have %s, want %s", output, want) 274 } 275 } 276 277 // Tests that the JavaScript exceptions are properly formatted and colored. 278 func TestPrettyError(t *testing.T) { 279 tester := newTester(t, nil) 280 defer tester.Close(t) 281 tester.console.Evaluate("throw 'hello'") 282 283 want := jsre.ErrorColor("hello\n\tat <eval>:1:1(1)\n") + "\n" 284 if output := tester.output.String(); output != want { 285 t.Fatalf("pretty error mismatch: have %s, want %s", output, want) 286 } 287 } 288 289 // Tests that tests if the number of indents for JS input is calculated correct. 290 func TestIndenting(t *testing.T) { 291 testCases := []struct { 292 input string 293 expectedIndentCount int 294 }{ 295 {`var a = 1;`, 0}, 296 {`"some string"`, 0}, 297 {`"some string with (parenthesis`, 0}, 298 {`"some string with newline 299 ("`, 0}, 300 {`function v(a,b) {}`, 0}, 301 {`function f(a,b) { var str = "asd("; };`, 0}, 302 {`function f(a) {`, 1}, 303 {`function f(a, function(b) {`, 2}, 304 {`function f(a, function(b) { 305 var str = "a)}"; 306 });`, 0}, 307 {`function f(a,b) { 308 var str = "a{b(" + a, ", " + b; 309 }`, 0}, 310 {`var str = "\"{"`, 0}, 311 {`var str = "'("`, 0}, 312 {`var str = "\\{"`, 0}, 313 {`var str = "\\\\{"`, 0}, 314 {`var str = 'a"{`, 0}, 315 {`var obj = {`, 1}, 316 {`var obj = { {a:1`, 2}, 317 {`var obj = { {a:1}`, 1}, 318 {`var obj = { {a:1}, b:2}`, 0}, 319 {`var obj = {}`, 0}, 320 {`var obj = { 321 a: 1, b: 2 322 }`, 0}, 323 {`var test = }`, -1}, 324 {`var str = "a\""; var obj = {`, 1}, 325 } 326 327 for i, tt := range testCases { 328 counted := countIndents(tt.input) 329 if counted != tt.expectedIndentCount { 330 t.Errorf("test %d: invalid indenting: have %d, want %d", i, counted, tt.expectedIndentCount) 331 } 332 } 333 }