github.com/klaytn/klaytn@v1.10.2/console/console_test.go (about)

     1  // Modifications Copyright 2018 The klaytn Authors
     2  // Copyright 2015 The go-ethereum Authors
     3  // This file is part of the go-ethereum library.
     4  //
     5  // The go-ethereum library is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU Lesser General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // The go-ethereum library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  // GNU Lesser General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Lesser General Public License
    16  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    17  //
    18  // This file is derived from console/console_test.go (2018/06/04).
    19  // Modified and improved for the klaytn development.
    20  
    21  package console
    22  
    23  import (
    24  	"bytes"
    25  	"errors"
    26  	"fmt"
    27  	"io/ioutil"
    28  	"os"
    29  	"strings"
    30  	"testing"
    31  	"time"
    32  
    33  	"github.com/klaytn/klaytn/blockchain"
    34  	"github.com/klaytn/klaytn/common"
    35  	"github.com/klaytn/klaytn/console/jsre"
    36  	"github.com/klaytn/klaytn/node"
    37  	"github.com/klaytn/klaytn/node/cn"
    38  )
    39  
    40  const (
    41  	testInstance = "console-tester"
    42  	testAddress  = "0x8605cdbbdb6d264aa742e77020dcbc58fcdce182"
    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  
    70  func (p *hookedPrompter) PromptConfirm(prompt string) (bool, error) {
    71  	return false, errors.New("not implemented")
    72  }
    73  func (p *hookedPrompter) SetHistory(history []string)              {}
    74  func (p *hookedPrompter) AppendHistory(command string)             {}
    75  func (p *hookedPrompter) ClearHistory()                            {}
    76  func (p *hookedPrompter) SetWordCompleter(completer WordCompleter) {}
    77  
    78  // tester is a console test environment for the console tests to operate on.
    79  type tester struct {
    80  	workspace string
    81  	stack     *node.Node
    82  	cn        *cn.CN
    83  	console   *Console
    84  	input     *hookedPrompter
    85  	output    *bytes.Buffer
    86  }
    87  
    88  // newTester creates a test environment based on which the console can operate.
    89  // Please ensure you call Close() on the returned tester to avoid leaks.
    90  func newTester(t *testing.T, confOverride func(*cn.Config)) *tester {
    91  	// Create a temporary storage for the node keys and initialize it
    92  	workspace, err := ioutil.TempDir("", "console-tester-")
    93  	if err != nil {
    94  		t.Fatalf("failed to create temporary keystore: %v", err)
    95  	}
    96  
    97  	// Create a networkless protocol stack and start a Klaytn service within
    98  	stack, err := node.New(&node.Config{DataDir: workspace, UseLightweightKDF: true, Name: testInstance})
    99  	if err != nil {
   100  		t.Fatalf("failed to create node: %v", err)
   101  	}
   102  	cnConf := &cn.Config{
   103  		Genesis:            blockchain.DefaultGenesisBlock(),
   104  		ServiceChainSigner: common.HexToAddress(testAddress),
   105  	}
   106  	if confOverride != nil {
   107  		confOverride(cnConf)
   108  	}
   109  	if err = stack.Register(func(ctx *node.ServiceContext) (node.Service, error) { return cn.New(ctx, cnConf) }); err != nil {
   110  		t.Fatalf("failed to register Klaytn 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 cn *cn.CN
   136  	stack.Service(&cn)
   137  
   138  	return &tester{
   139  		workspace: workspace,
   140  		stack:     stack,
   141  		cn:        cn,
   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, 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("datadir: %s", tester.workspace); !strings.Contains(output, want) {
   176  		t.Fatalf("console output missing datadir: have\n%s\nwant also %s", output, want)
   177  	}
   178  }
   179  
   180  // Tests that JavaScript statement evaluation works as intended.
   181  func TestEvaluate(t *testing.T) {
   182  	tester := newTester(t, nil)
   183  	defer tester.Close(t)
   184  
   185  	tester.console.Evaluate("2 + 2")
   186  	if output := tester.output.String(); !strings.Contains(output, "4") {
   187  		t.Fatalf("statement evaluation failed: have %s, want %s", output, "4")
   188  	}
   189  }
   190  
   191  // Tests that the console can be used in interactive mode.
   192  func TestInteractive(t *testing.T) {
   193  	// Create a tester and run an interactive console in the background
   194  	tester := newTester(t, nil)
   195  	defer tester.Close(t)
   196  
   197  	go tester.console.Interactive()
   198  
   199  	// Wait for a prompt and send a statement back
   200  	select {
   201  	case <-tester.input.scheduler:
   202  	case <-time.After(time.Second):
   203  		t.Fatalf("initial prompt timeout")
   204  	}
   205  	select {
   206  	case tester.input.scheduler <- "2+2":
   207  	case <-time.After(time.Second):
   208  		t.Fatalf("input feedback timeout")
   209  	}
   210  	// Wait for the second prompt and ensure first statement was evaluated
   211  	select {
   212  	case <-tester.input.scheduler:
   213  	case <-time.After(time.Second):
   214  		t.Fatalf("secondary prompt timeout")
   215  	}
   216  	if output := tester.output.String(); !strings.Contains(output, "4") {
   217  		t.Fatalf("statement evaluation failed: have %s, want %s", output, "4")
   218  	}
   219  }
   220  
   221  // Tests that preloaded JavaScript files have been executed before user is given
   222  // input.
   223  func TestPreload(t *testing.T) {
   224  	tester := newTester(t, nil)
   225  	defer tester.Close(t)
   226  
   227  	tester.console.Evaluate("preloaded")
   228  	if output := tester.output.String(); !strings.Contains(output, "some-preloaded-string") {
   229  		t.Fatalf("preloaded variable missing: have %s, want %s", output, "some-preloaded-string")
   230  	}
   231  }
   232  
   233  // Tests that JavaScript scripts can be executes from the configured asset path.
   234  func TestExecute(t *testing.T) {
   235  	tester := newTester(t, nil)
   236  	defer tester.Close(t)
   237  
   238  	tester.console.Execute("exec.js")
   239  
   240  	tester.console.Evaluate("execed")
   241  	if output := tester.output.String(); !strings.Contains(output, "some-executed-string") {
   242  		t.Fatalf("execed variable missing: have %s, want %s", output, "some-executed-string")
   243  	}
   244  }
   245  
   246  // Tests that the JavaScript objects returned by statement executions are properly
   247  // pretty printed instead of just displaying "[object]".
   248  func TestPrettyPrint(t *testing.T) {
   249  	tester := newTester(t, nil)
   250  	defer tester.Close(t)
   251  
   252  	tester.console.Evaluate("obj = {int: 1, string: 'two', list: [3, 3, 3], obj: {null: null, func: function(){}}}")
   253  
   254  	// Define some specially formatted fields
   255  	var (
   256  		one   = jsre.NumberColor("1")
   257  		two   = jsre.StringColor("\"two\"")
   258  		three = jsre.NumberColor("3")
   259  		null  = jsre.SpecialColor("null")
   260  		fun   = jsre.FunctionColor("function()")
   261  	)
   262  	// Assemble the actual output we're after and verify
   263  	want := `{
   264    int: ` + one + `,
   265    list: [` + three + `, ` + three + `, ` + three + `],
   266    obj: {
   267      null: ` + null + `,
   268      func: ` + fun + `
   269    },
   270    string: ` + two + `
   271  }
   272  `
   273  	if output := tester.output.String(); output != want {
   274  		t.Fatalf("pretty print mismatch: have %s, want %s", output, want)
   275  	}
   276  }
   277  
   278  // Tests that the JavaScript exceptions are properly formatted and colored.
   279  func TestPrettyError(t *testing.T) {
   280  	tester := newTester(t, nil)
   281  	defer tester.Close(t)
   282  	tester.console.Evaluate("throw 'hello'")
   283  
   284  	want := jsre.ErrorColor("hello") + "\n"
   285  	if output := tester.output.String(); output != want {
   286  		t.Fatalf("pretty error mismatch: have %s, want %s", output, want)
   287  	}
   288  }
   289  
   290  // Tests that tests if the number of indents for JS input is calculated correct.
   291  func TestIndenting(t *testing.T) {
   292  	testCases := []struct {
   293  		input               string
   294  		expectedIndentCount int
   295  	}{
   296  		{`var a = 1;`, 0},
   297  		{`"some string"`, 0},
   298  		{`"some string with (parenthesis`, 0},
   299  		{`"some string with newline
   300  		("`, 0},
   301  		{`function v(a,b) {}`, 0},
   302  		{`function f(a,b) { var str = "asd("; };`, 0},
   303  		{`function f(a) {`, 1},
   304  		{`function f(a, function(b) {`, 2},
   305  		{`function f(a, function(b) {
   306  		     var str = "a)}";
   307  		  });`, 0},
   308  		{`function f(a,b) {
   309  		   var str = "a{b(" + a, ", " + b;
   310  		   }`, 0},
   311  		{`var str = "\"{"`, 0},
   312  		{`var str = "'("`, 0},
   313  		{`var str = "\\{"`, 0},
   314  		{`var str = "\\\\{"`, 0},
   315  		{`var str = 'a"{`, 0},
   316  		{`var obj = {`, 1},
   317  		{`var obj = { {a:1`, 2},
   318  		{`var obj = { {a:1}`, 1},
   319  		{`var obj = { {a:1}, b:2}`, 0},
   320  		{`var obj = {}`, 0},
   321  		{`var obj = {
   322  			a: 1, b: 2
   323  		}`, 0},
   324  		{`var test = }`, -1},
   325  		{`var str = "a\""; var obj = {`, 1},
   326  	}
   327  
   328  	for i, tt := range testCases {
   329  		counted := countIndents(tt.input)
   330  		if counted != tt.expectedIndentCount {
   331  			t.Errorf("test %d: invalid indenting: have %d, want %d", i, counted, tt.expectedIndentCount)
   332  		}
   333  	}
   334  }