github.com/MetalBlockchain/subnet-evm@v0.4.9/rpc/server_test.go (about)

     1  // (c) 2019-2020, Ava Labs, Inc.
     2  //
     3  // This file is a derived work, based on the go-ethereum library whose original
     4  // notices appear below.
     5  //
     6  // It is distributed under a license compatible with the licensing terms of the
     7  // original code from which it is derived.
     8  //
     9  // Much love to the original authors for their work.
    10  // **********
    11  // Copyright 2015 The go-ethereum Authors
    12  // This file is part of the go-ethereum library.
    13  //
    14  // The go-ethereum library is free software: you can redistribute it and/or modify
    15  // it under the terms of the GNU Lesser General Public License as published by
    16  // the Free Software Foundation, either version 3 of the License, or
    17  // (at your option) any later version.
    18  //
    19  // The go-ethereum library is distributed in the hope that it will be useful,
    20  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    21  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    22  // GNU Lesser General Public License for more details.
    23  //
    24  // You should have received a copy of the GNU Lesser General Public License
    25  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    26  
    27  package rpc
    28  
    29  import (
    30  	"bufio"
    31  	"io"
    32  	"net"
    33  	"os"
    34  	"path/filepath"
    35  	"strings"
    36  	"testing"
    37  	"time"
    38  )
    39  
    40  func TestServerRegisterName(t *testing.T) {
    41  	server := NewServer(0)
    42  	service := new(testService)
    43  
    44  	if err := server.RegisterName("test", service); err != nil {
    45  		t.Fatalf("%v", err)
    46  	}
    47  
    48  	if len(server.services.services) != 2 {
    49  		t.Fatalf("Expected 2 service entries, got %d", len(server.services.services))
    50  	}
    51  
    52  	svc, ok := server.services.services["test"]
    53  	if !ok {
    54  		t.Fatalf("Expected service calc to be registered")
    55  	}
    56  
    57  	wantCallbacks := 10
    58  	if len(svc.callbacks) != wantCallbacks {
    59  		t.Errorf("Expected %d callbacks for service 'service', got %d", wantCallbacks, len(svc.callbacks))
    60  	}
    61  }
    62  
    63  func TestServer(t *testing.T) {
    64  	files, err := os.ReadDir("testdata")
    65  	if err != nil {
    66  		t.Fatal("where'd my testdata go?")
    67  	}
    68  	for _, f := range files {
    69  		if f.IsDir() || strings.HasPrefix(f.Name(), ".") {
    70  			continue
    71  		}
    72  		path := filepath.Join("testdata", f.Name())
    73  		name := strings.TrimSuffix(f.Name(), filepath.Ext(f.Name()))
    74  		t.Run(name, func(t *testing.T) {
    75  			runTestScript(t, path)
    76  		})
    77  	}
    78  }
    79  
    80  func runTestScript(t *testing.T, file string) {
    81  	server := newTestServer()
    82  	content, err := os.ReadFile(file)
    83  	if err != nil {
    84  		t.Fatal(err)
    85  	}
    86  
    87  	clientConn, serverConn := net.Pipe()
    88  	defer clientConn.Close()
    89  	go server.ServeCodec(NewCodec(serverConn), 0, 0, 0, 0)
    90  	readbuf := bufio.NewReader(clientConn)
    91  	for _, line := range strings.Split(string(content), "\n") {
    92  		line = strings.TrimSpace(line)
    93  		switch {
    94  		case len(line) == 0 || strings.HasPrefix(line, "//"):
    95  			// skip comments, blank lines
    96  			continue
    97  		case strings.HasPrefix(line, "--> "):
    98  			t.Log(line)
    99  			// write to connection
   100  			clientConn.SetWriteDeadline(time.Now().Add(5 * time.Second))
   101  			if _, err := io.WriteString(clientConn, line[4:]+"\n"); err != nil {
   102  				t.Fatalf("write error: %v", err)
   103  			}
   104  		case strings.HasPrefix(line, "<-- "):
   105  			t.Log(line)
   106  			want := line[4:]
   107  			// read line from connection and compare text
   108  			clientConn.SetReadDeadline(time.Now().Add(5 * time.Second))
   109  			sent, err := readbuf.ReadString('\n')
   110  			if err != nil {
   111  				t.Fatalf("read error: %v", err)
   112  			}
   113  			sent = strings.TrimRight(sent, "\r\n")
   114  			if sent != want {
   115  				t.Errorf("wrong line from server\ngot:  %s\nwant: %s", sent, want)
   116  			}
   117  		default:
   118  			panic("invalid line in test script: " + line)
   119  		}
   120  	}
   121  }
   122  
   123  // // This test checks that responses are delivered for very short-lived connections that
   124  // // only carry a single request.
   125  // func TestServerShortLivedConn(t *testing.T) {
   126  // 	server := newTestServer()
   127  // 	defer server.Stop()
   128  
   129  // 	listener, err := net.Listen("tcp", "127.0.0.1:0")
   130  // 	if err != nil {
   131  // 		t.Fatal("can't listen:", err)
   132  // 	}
   133  // 	defer listener.Close()
   134  // 	go server.ServeListener(listener)
   135  
   136  // 	var (
   137  // 		request  = `{"jsonrpc":"2.0","id":1,"method":"rpc_modules"}` + "\n"
   138  // 		wantResp = `{"jsonrpc":"2.0","id":1,"result":{"nftest":"1.0","rpc":"1.0","test":"1.0"}}` + "\n"
   139  // 		deadline = time.Now().Add(10 * time.Second)
   140  // 	)
   141  // 	for i := 0; i < 20; i++ {
   142  // 		conn, err := net.Dial("tcp", listener.Addr().String())
   143  // 		if err != nil {
   144  // 			t.Fatal("can't dial:", err)
   145  // 		}
   146  // 		conn.SetDeadline(deadline)
   147  // 		// Write the request, then half-close the connection so the server stops reading.
   148  // 		conn.Write([]byte(request))
   149  // 		conn.(*net.TCPConn).CloseWrite()
   150  // 		// Now try to get the response.
   151  // 		buf := make([]byte, 2000)
   152  // 		n, err := conn.Read(buf)
   153  // 		conn.Close()
   154  //
   155  // 		if err != nil {
   156  // 			t.Fatal("read error:", err)
   157  // 		}
   158  // 		if !bytes.Equal(buf[:n], []byte(wantResp)) {
   159  // 			t.Fatalf("wrong response: %s", buf[:n])
   160  // 		}
   161  // 	}
   162  // }