github.com/arieschain/arieschain@v0.0.0-20191023063405-37c074544356/console/console_test.go (about)

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