github.com/yinchengtsinghua/golang-Eos-dpos-Ethereum@v0.0.0-20190121132951-92cc4225ed8e/console/console_test.go (about)

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