github.com/luckypickle/go-ethereum-vet@v1.14.2/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/luckypickle/go-ethereum-vet/common"
    30  	"github.com/luckypickle/go-ethereum-vet/consensus/ethash"
    31  	"github.com/luckypickle/go-ethereum-vet/core"
    32  	"github.com/luckypickle/go-ethereum-vet/eth"
    33  	"github.com/luckypickle/go-ethereum-vet/internal/jsre"
    34  	"github.com/luckypickle/go-ethereum-vet/node"
    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) ClearHistory()                            {}
    72  func (p *hookedPrompter) SetWordCompleter(completer WordCompleter) {}
    73  
    74  // tester is a console test environment for the console tests to operate on.
    75  type tester struct {
    76  	workspace string
    77  	stack     *node.Node
    78  	ethereum  *eth.Ethereum
    79  	console   *Console
    80  	input     *hookedPrompter
    81  	output    *bytes.Buffer
    82  }
    83  
    84  // newTester creates a test environment based on which the console can operate.
    85  // Please ensure you call Close() on the returned tester to avoid leaks.
    86  func newTester(t *testing.T, confOverride func(*eth.Config)) *tester {
    87  	// Create a temporary storage for the node keys and initialize it
    88  	workspace, err := ioutil.TempDir("", "console-tester-")
    89  	if err != nil {
    90  		t.Fatalf("failed to create temporary keystore: %v", err)
    91  	}
    92  
    93  	// Create a networkless protocol stack and start an Ethereum service within
    94  	stack, err := node.New(&node.Config{DataDir: workspace, UseLightweightKDF: true, Name: testInstance})
    95  	if err != nil {
    96  		t.Fatalf("failed to create node: %v", err)
    97  	}
    98  	ethConf := &eth.Config{
    99  		Genesis:   core.DeveloperGenesisBlock(15, common.Address{}),
   100  		Etherbase: common.HexToAddress(testAddress),
   101  		Ethash: ethash.Config{
   102  			PowMode: ethash.ModeTest,
   103  		},
   104  	}
   105  	if confOverride != nil {
   106  		confOverride(ethConf)
   107  	}
   108  	if err = stack.Register(func(ctx *node.ServiceContext) (node.Service, error) { return eth.New(ctx, ethConf) }); err != nil {
   109  		t.Fatalf("failed to register Ethereum 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 ethereum *eth.Ethereum
   135  	stack.Service(&ethereum)
   136  
   137  	return &tester{
   138  		workspace: workspace,
   139  		stack:     stack,
   140  		ethereum:  ethereum,
   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, coinbase account, 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("coinbase: %s", testAddress); !strings.Contains(output, want) {
   175  		t.Fatalf("console output missing coinbase: have\n%s\nwant also %s", output, want)
   176  	}
   177  	if want := "at block: 0"; !strings.Contains(output, want) {
   178  		t.Fatalf("console output missing sync status: have\n%s\nwant also %s", output, want)
   179  	}
   180  	if want := fmt.Sprintf("datadir: %s", tester.workspace); !strings.Contains(output, want) {
   181  		t.Fatalf("console output missing coinbase: have\n%s\nwant also %s", output, want)
   182  	}
   183  }
   184  
   185  // Tests that JavaScript statement evaluation works as intended.
   186  func TestEvaluate(t *testing.T) {
   187  	tester := newTester(t, nil)
   188  	defer tester.Close(t)
   189  
   190  	tester.console.Evaluate("2 + 2")
   191  	if output := tester.output.String(); !strings.Contains(output, "4") {
   192  		t.Fatalf("statement evaluation failed: have %s, want %s", output, "4")
   193  	}
   194  }
   195  
   196  // Tests that the console can be used in interactive mode.
   197  func TestInteractive(t *testing.T) {
   198  	// Create a tester and run an interactive console in the background
   199  	tester := newTester(t, nil)
   200  	defer tester.Close(t)
   201  
   202  	go tester.console.Interactive()
   203  
   204  	// Wait for a prompt and send a statement back
   205  	select {
   206  	case <-tester.input.scheduler:
   207  	case <-time.After(time.Second):
   208  		t.Fatalf("initial prompt timeout")
   209  	}
   210  	select {
   211  	case tester.input.scheduler <- "2+2":
   212  	case <-time.After(time.Second):
   213  		t.Fatalf("input feedback timeout")
   214  	}
   215  	// Wait for the second prompt and ensure first statement was evaluated
   216  	select {
   217  	case <-tester.input.scheduler:
   218  	case <-time.After(time.Second):
   219  		t.Fatalf("secondary prompt timeout")
   220  	}
   221  	if output := tester.output.String(); !strings.Contains(output, "4") {
   222  		t.Fatalf("statement evaluation failed: have %s, want %s", output, "4")
   223  	}
   224  }
   225  
   226  // Tests that preloaded JavaScript files have been executed before user is given
   227  // input.
   228  func TestPreload(t *testing.T) {
   229  	tester := newTester(t, nil)
   230  	defer tester.Close(t)
   231  
   232  	tester.console.Evaluate("preloaded")
   233  	if output := tester.output.String(); !strings.Contains(output, "some-preloaded-string") {
   234  		t.Fatalf("preloaded variable missing: have %s, want %s", output, "some-preloaded-string")
   235  	}
   236  }
   237  
   238  // Tests that JavaScript scripts can be executes from the configured asset path.
   239  func TestExecute(t *testing.T) {
   240  	tester := newTester(t, nil)
   241  	defer tester.Close(t)
   242  
   243  	tester.console.Execute("exec.js")
   244  
   245  	tester.console.Evaluate("execed")
   246  	if output := tester.output.String(); !strings.Contains(output, "some-executed-string") {
   247  		t.Fatalf("execed variable missing: have %s, want %s", output, "some-executed-string")
   248  	}
   249  }
   250  
   251  // Tests that the JavaScript objects returned by statement executions are properly
   252  // pretty printed instead of just displaying "[object]".
   253  func TestPrettyPrint(t *testing.T) {
   254  	tester := newTester(t, nil)
   255  	defer tester.Close(t)
   256  
   257  	tester.console.Evaluate("obj = {int: 1, string: 'two', list: [3, 3, 3], obj: {null: null, func: function(){}}}")
   258  
   259  	// Define some specially formatted fields
   260  	var (
   261  		one   = jsre.NumberColor("1")
   262  		two   = jsre.StringColor("\"two\"")
   263  		three = jsre.NumberColor("3")
   264  		null  = jsre.SpecialColor("null")
   265  		fun   = jsre.FunctionColor("function()")
   266  	)
   267  	// Assemble the actual output we're after and verify
   268  	want := `{
   269    int: ` + one + `,
   270    list: [` + three + `, ` + three + `, ` + three + `],
   271    obj: {
   272      null: ` + null + `,
   273      func: ` + fun + `
   274    },
   275    string: ` + two + `
   276  }
   277  `
   278  	if output := tester.output.String(); output != want {
   279  		t.Fatalf("pretty print mismatch: have %s, want %s", output, want)
   280  	}
   281  }
   282  
   283  // Tests that the JavaScript exceptions are properly formatted and colored.
   284  func TestPrettyError(t *testing.T) {
   285  	tester := newTester(t, nil)
   286  	defer tester.Close(t)
   287  	tester.console.Evaluate("throw 'hello'")
   288  
   289  	want := jsre.ErrorColor("hello") + "\n"
   290  	if output := tester.output.String(); output != want {
   291  		t.Fatalf("pretty error mismatch: have %s, want %s", output, want)
   292  	}
   293  }
   294  
   295  // Tests that tests if the number of indents for JS input is calculated correct.
   296  func TestIndenting(t *testing.T) {
   297  	testCases := []struct {
   298  		input               string
   299  		expectedIndentCount int
   300  	}{
   301  		{`var a = 1;`, 0},
   302  		{`"some string"`, 0},
   303  		{`"some string with (parenthesis`, 0},
   304  		{`"some string with newline
   305  		("`, 0},
   306  		{`function v(a,b) {}`, 0},
   307  		{`function f(a,b) { var str = "asd("; };`, 0},
   308  		{`function f(a) {`, 1},
   309  		{`function f(a, function(b) {`, 2},
   310  		{`function f(a, function(b) {
   311  		     var str = "a)}";
   312  		  });`, 0},
   313  		{`function f(a,b) {
   314  		   var str = "a{b(" + a, ", " + b;
   315  		   }`, 0},
   316  		{`var str = "\"{"`, 0},
   317  		{`var str = "'("`, 0},
   318  		{`var str = "\\{"`, 0},
   319  		{`var str = "\\\\{"`, 0},
   320  		{`var str = 'a"{`, 0},
   321  		{`var obj = {`, 1},
   322  		{`var obj = { {a:1`, 2},
   323  		{`var obj = { {a:1}`, 1},
   324  		{`var obj = { {a:1}, b:2}`, 0},
   325  		{`var obj = {}`, 0},
   326  		{`var obj = {
   327  			a: 1, b: 2
   328  		}`, 0},
   329  		{`var test = }`, -1},
   330  		{`var str = "a\""; var obj = {`, 1},
   331  	}
   332  
   333  	for i, tt := range testCases {
   334  		counted := countIndents(tt.input)
   335  		if counted != tt.expectedIndentCount {
   336  			t.Errorf("test %d: invalid indenting: have %d, want %d", i, counted, tt.expectedIndentCount)
   337  		}
   338  	}
   339  }