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