github.com/core-coin/go-core/v2@v2.1.9/console/console_test.go (about)

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