github.com/linapex/ethereum-dpos-chinese@v0.0.0-20190316121959-b78b3a4a1ece/console/console_test.go (about) 1 2 //<developer> 3 // <name>linapex 曹一峰</name> 4 // <email>linapex@163.com</email> 5 // <wx>superexc</wx> 6 // <qqgroup>128148617</qqgroup> 7 // <url>https://jsq.ink</url> 8 // <role>pku engineer</role> 9 // <date>2019-03-16 12:09:33</date> 10 //</624342612681166848> 11 12 13 package console 14 15 import ( 16 "bytes" 17 "errors" 18 "fmt" 19 "io/ioutil" 20 "os" 21 "strings" 22 "testing" 23 "time" 24 25 "github.com/ethereum/go-ethereum/common" 26 "github.com/ethereum/go-ethereum/consensus/ethash" 27 "github.com/ethereum/go-ethereum/core" 28 "github.com/ethereum/go-ethereum/eth" 29 "github.com/ethereum/go-ethereum/internal/jsre" 30 "github.com/ethereum/go-ethereum/node" 31 ) 32 33 const ( 34 testInstance = "console-tester" 35 testAddress = "0x8605cdbbdb6d264aa742e77020dcbc58fcdce182" 36 ) 37 38 //HookedPrompter实现了用户Prompter来模拟通过通道的使用输入。 39 type hookedPrompter struct { 40 scheduler chan string 41 } 42 43 func (p *hookedPrompter) PromptInput(prompt string) (string, error) { 44 // 45 select { 46 case p.scheduler <- prompt: 47 case <-time.After(time.Second): 48 return "", errors.New("prompt timeout") 49 } 50 //检索响应并反馈到控制台 51 select { 52 case input := <-p.scheduler: 53 return input, nil 54 case <-time.After(time.Second): 55 return "", errors.New("input timeout") 56 } 57 } 58 59 func (p *hookedPrompter) PromptPassword(prompt string) (string, error) { 60 return "", errors.New("not implemented") 61 } 62 func (p *hookedPrompter) PromptConfirm(prompt string) (bool, error) { 63 return false, errors.New("not implemented") 64 } 65 func (p *hookedPrompter) SetHistory(history []string) {} 66 func (p *hookedPrompter) AppendHistory(command string) {} 67 func (p *hookedPrompter) ClearHistory() {} 68 func (p *hookedPrompter) SetWordCompleter(completer WordCompleter) {} 69 70 //测试仪是控制台测试的控制台测试环境。 71 type tester struct { 72 workspace string 73 stack *node.Node 74 ethereum *eth.Ethereum 75 console *Console 76 input *hookedPrompter 77 output *bytes.Buffer 78 } 79 80 //NewTester创建了一个测试环境,控制台可以根据这个环境进行操作。 81 //请确保在返回的测试仪上调用close()以避免泄漏。 82 func newTester(t *testing.T, confOverride func(*eth.Config)) *tester { 83 //为节点键创建临时存储并初始化它 84 workspace, err := ioutil.TempDir("", "console-tester-") 85 if err != nil { 86 t.Fatalf("failed to create temporary keystore: %v", err) 87 } 88 89 //创建无网络协议栈并在 90 stack, err := node.New(&node.Config{DataDir: workspace, UseLightweightKDF: true, Name: testInstance}) 91 if err != nil { 92 t.Fatalf("failed to create node: %v", err) 93 } 94 ethConf := ð.Config{ 95 Genesis: core.DeveloperGenesisBlock(15, common.Address{}), 96 Etherbase: common.HexToAddress(testAddress), 97 Ethash: ethash.Config{ 98 PowMode: ethash.ModeTest, 99 }, 100 } 101 if confOverride != nil { 102 confOverride(ethConf) 103 } 104 if err = stack.Register(func(ctx *node.ServiceContext) (node.Service, error) { return eth.New(ctx, ethConf) }); err != nil { 105 t.Fatalf("failed to register Ethereum protocol: %v", err) 106 } 107 //启动节点并围绕它组装JavaScript控制台 108 if err = stack.Start(); err != nil { 109 t.Fatalf("failed to start test stack: %v", err) 110 } 111 client, err := stack.Attach() 112 if err != nil { 113 t.Fatalf("failed to attach to node: %v", err) 114 } 115 prompter := &hookedPrompter{scheduler: make(chan string)} 116 printer := new(bytes.Buffer) 117 118 console, err := New(Config{ 119 DataDir: stack.DataDir(), 120 DocRoot: "testdata", 121 Client: client, 122 Prompter: prompter, 123 Printer: printer, 124 Preload: []string{"preload.js"}, 125 }) 126 if err != nil { 127 t.Fatalf("failed to create JavaScript console: %v", err) 128 } 129 //创建最终测试仪并返回 130 var ethereum *eth.Ethereum 131 stack.Service(ðereum) 132 133 return &tester{ 134 workspace: workspace, 135 stack: stack, 136 ethereum: ethereum, 137 console: console, 138 input: prompter, 139 output: printer, 140 } 141 } 142 143 //关闭清除所有临时数据文件夹和保留的资源。 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.Stop(); err != nil { 149 t.Errorf("failed to stop embedded node: %v", err) 150 } 151 os.RemoveAll(env.workspace) 152 } 153 154 //测试节点是否列出了正确的欢迎消息,特别是它包含 155 //实例名、coinbase账号、块号、数据目录,支持 156 //控制台模块。 157 func TestWelcome(t *testing.T) { 158 tester := newTester(t, nil) 159 defer tester.Close(t) 160 161 tester.console.Welcome() 162 163 output := tester.output.String() 164 if want := "Welcome"; !strings.Contains(output, want) { 165 t.Fatalf("console output missing welcome message: have\n%s\nwant also %s", output, want) 166 } 167 if want := fmt.Sprintf("instance: %s", testInstance); !strings.Contains(output, want) { 168 t.Fatalf("console output missing instance: have\n%s\nwant also %s", output, want) 169 } 170 if want := fmt.Sprintf("coinbase: %s", testAddress); !strings.Contains(output, want) { 171 t.Fatalf("console output missing coinbase: have\n%s\nwant also %s", output, want) 172 } 173 if want := "at block: 0"; !strings.Contains(output, want) { 174 t.Fatalf("console output missing sync status: have\n%s\nwant also %s", output, want) 175 } 176 if want := fmt.Sprintf("datadir: %s", tester.workspace); !strings.Contains(output, want) { 177 t.Fatalf("console output missing coinbase: have\n%s\nwant also %s", output, want) 178 } 179 } 180 181 //测试javascript语句评估是否按预期工作。 182 func TestEvaluate(t *testing.T) { 183 tester := newTester(t, nil) 184 defer tester.Close(t) 185 186 tester.console.Evaluate("2 + 2") 187 if output := tester.output.String(); !strings.Contains(output, "4") { 188 t.Fatalf("statement evaluation failed: have %s, want %s", output, "4") 189 } 190 } 191 192 //测试控制台是否可以在交互模式下使用。 193 func TestInteractive(t *testing.T) { 194 //创建一个测试人员并在后台运行一个交互式控制台 195 tester := newTester(t, nil) 196 defer tester.Close(t) 197 198 go tester.console.Interactive() 199 200 //等待提示并返回语句 201 select { 202 case <-tester.input.scheduler: 203 case <-time.After(time.Second): 204 t.Fatalf("initial prompt timeout") 205 } 206 select { 207 case tester.input.scheduler <- "2+2": 208 case <-time.After(time.Second): 209 t.Fatalf("input feedback timeout") 210 } 211 //等待第二个提示并确保对第一个语句进行了计算 212 select { 213 case <-tester.input.scheduler: 214 case <-time.After(time.Second): 215 t.Fatalf("secondary prompt timeout") 216 } 217 if output := tester.output.String(); !strings.Contains(output, "4") { 218 t.Fatalf("statement evaluation failed: have %s, want %s", output, "4") 219 } 220 } 221 222 //在给定用户之前已执行预加载的javascript文件的测试 223 //输入。 224 func TestPreload(t *testing.T) { 225 tester := newTester(t, nil) 226 defer tester.Close(t) 227 228 tester.console.Evaluate("preloaded") 229 if output := tester.output.String(); !strings.Contains(output, "some-preloaded-string") { 230 t.Fatalf("preloaded variable missing: have %s, want %s", output, "some-preloaded-string") 231 } 232 } 233 234 //测试可以从配置的资产路径执行javascript脚本。 235 func TestExecute(t *testing.T) { 236 tester := newTester(t, nil) 237 defer tester.Close(t) 238 239 tester.console.Execute("exec.js") 240 241 tester.console.Evaluate("execed") 242 if output := tester.output.String(); !strings.Contains(output, "some-executed-string") { 243 t.Fatalf("execed variable missing: have %s, want %s", output, "some-executed-string") 244 } 245 } 246 247 //测试语句执行返回的javascript对象是否正确 248 //漂亮的打印,而不是仅仅显示“[对象]”。 249 func TestPrettyPrint(t *testing.T) { 250 tester := newTester(t, nil) 251 defer tester.Close(t) 252 253 tester.console.Evaluate("obj = {int: 1, string: 'two', list: [3, 3, 3], obj: {null: null, func: function(){}}}") 254 255 //定义一些特殊格式的字段 256 var ( 257 one = jsre.NumberColor("1") 258 two = jsre.StringColor("\"two\"") 259 three = jsre.NumberColor("3") 260 null = jsre.SpecialColor("null") 261 fun = jsre.FunctionColor("function()") 262 ) 263 //把我们需要的实际输出集合起来并验证 264 want := `{ 265 int: ` + one + `, 266 list: [` + three + `, ` + three + `, ` + three + `], 267 obj: { 268 null: ` + null + `, 269 func: ` + fun + ` 270 }, 271 string: ` + two + ` 272 } 273 ` 274 if output := tester.output.String(); output != want { 275 t.Fatalf("pretty print mismatch: have %s, want %s", output, want) 276 } 277 } 278 279 //测试javascript异常的格式和颜色是否正确。 280 func TestPrettyError(t *testing.T) { 281 tester := newTester(t, nil) 282 defer tester.Close(t) 283 tester.console.Evaluate("throw 'hello'") 284 285 want := jsre.ErrorColor("hello") + "\n" 286 if output := tester.output.String(); output != want { 287 t.Fatalf("pretty error mismatch: have %s, want %s", output, want) 288 } 289 } 290 291 //测试JS输入的缩进数是否计算正确。 292 func TestIndenting(t *testing.T) { 293 testCases := []struct { 294 input string 295 expectedIndentCount int 296 }{ 297 {`var a = 1;`, 0}, 298 {`"some string"`, 0}, 299 {`"some string with (parenthesis`, 0}, 300 {`"some string with newline 301 ("`, 0}, 302 {`function v(a,b) {}`, 0}, 303 {`function f(a,b) { var str = "asd("; };`, 0}, 304 {`function f(a) {`, 1}, 305 {`function f(a, function(b) {`, 2}, 306 {`function f(a, function(b) { 307 var str = "a)}"; 308 });`, 0}, 309 {`function f(a,b) { 310 var str = "a{b(" + a, ", " + b; 311 }`, 0}, 312 {`var str = "\"{"`, 0}, 313 {`var str = "'("`, 0}, 314 {`var str = "\\{"`, 0}, 315 {`var str = "\\\\{"`, 0}, 316 {`var str = 'a"{`, 0}, 317 {`var obj = {`, 1}, 318 {`var obj = { {a:1`, 2}, 319 {`var obj = { {a:1}`, 1}, 320 {`var obj = { {a:1}, b:2}`, 0}, 321 {`var obj = {}`, 0}, 322 {`var obj = { 323 a: 1, b: 2 324 }`, 0}, 325 {`var test = }`, -1}, 326 {`var str = "a\""; var obj = {`, 1}, 327 } 328 329 for i, tt := range testCases { 330 counted := countIndents(tt.input) 331 if counted != tt.expectedIndentCount { 332 t.Errorf("test %d: invalid indenting: have %d, want %d", i, counted, tt.expectedIndentCount) 333 } 334 } 335 } 336