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