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