github.com/theQRL/go-zond@v0.1.1/rpc/server_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 rpc
    18  
    19  import (
    20  	"bufio"
    21  	"bytes"
    22  	"io"
    23  	"net"
    24  	"os"
    25  	"path/filepath"
    26  	"strings"
    27  	"testing"
    28  	"time"
    29  )
    30  
    31  func TestServerRegisterName(t *testing.T) {
    32  	server := NewServer()
    33  	service := new(testService)
    34  
    35  	if err := server.RegisterName("test", service); err != nil {
    36  		t.Fatalf("%v", err)
    37  	}
    38  
    39  	if len(server.services.services) != 2 {
    40  		t.Fatalf("Expected 2 service entries, got %d", len(server.services.services))
    41  	}
    42  
    43  	svc, ok := server.services.services["test"]
    44  	if !ok {
    45  		t.Fatalf("Expected service calc to be registered")
    46  	}
    47  
    48  	wantCallbacks := 13
    49  	if len(svc.callbacks) != wantCallbacks {
    50  		t.Errorf("Expected %d callbacks for service 'service', got %d", wantCallbacks, len(svc.callbacks))
    51  	}
    52  }
    53  
    54  func TestServer(t *testing.T) {
    55  	files, err := os.ReadDir("testdata")
    56  	if err != nil {
    57  		t.Fatal("where'd my testdata go?")
    58  	}
    59  	for _, f := range files {
    60  		if f.IsDir() || strings.HasPrefix(f.Name(), ".") {
    61  			continue
    62  		}
    63  		path := filepath.Join("testdata", f.Name())
    64  		name := strings.TrimSuffix(f.Name(), filepath.Ext(f.Name()))
    65  		t.Run(name, func(t *testing.T) {
    66  			runTestScript(t, path)
    67  		})
    68  	}
    69  }
    70  
    71  func runTestScript(t *testing.T, file string) {
    72  	server := newTestServer()
    73  	server.SetBatchLimits(4, 100000)
    74  	content, err := os.ReadFile(file)
    75  	if err != nil {
    76  		t.Fatal(err)
    77  	}
    78  
    79  	clientConn, serverConn := net.Pipe()
    80  	defer clientConn.Close()
    81  	go server.ServeCodec(NewCodec(serverConn), 0)
    82  	readbuf := bufio.NewReader(clientConn)
    83  	for _, line := range strings.Split(string(content), "\n") {
    84  		line = strings.TrimSpace(line)
    85  		switch {
    86  		case len(line) == 0 || strings.HasPrefix(line, "//"):
    87  			// skip comments, blank lines
    88  			continue
    89  		case strings.HasPrefix(line, "--> "):
    90  			t.Log(line)
    91  			// write to connection
    92  			clientConn.SetWriteDeadline(time.Now().Add(5 * time.Second))
    93  			if _, err := io.WriteString(clientConn, line[4:]+"\n"); err != nil {
    94  				t.Fatalf("write error: %v", err)
    95  			}
    96  		case strings.HasPrefix(line, "<-- "):
    97  			t.Log(line)
    98  			want := line[4:]
    99  			// read line from connection and compare text
   100  			clientConn.SetReadDeadline(time.Now().Add(5 * time.Second))
   101  			sent, err := readbuf.ReadString('\n')
   102  			if err != nil {
   103  				t.Fatalf("read error: %v", err)
   104  			}
   105  			sent = strings.TrimRight(sent, "\r\n")
   106  			if sent != want {
   107  				t.Errorf("wrong line from server\ngot:  %s\nwant: %s", sent, want)
   108  			}
   109  		default:
   110  			panic("invalid line in test script: " + line)
   111  		}
   112  	}
   113  }
   114  
   115  // This test checks that responses are delivered for very short-lived connections that
   116  // only carry a single request.
   117  func TestServerShortLivedConn(t *testing.T) {
   118  	server := newTestServer()
   119  	defer server.Stop()
   120  
   121  	listener, err := net.Listen("tcp", "127.0.0.1:0")
   122  	if err != nil {
   123  		t.Fatal("can't listen:", err)
   124  	}
   125  	defer listener.Close()
   126  	go server.ServeListener(listener)
   127  
   128  	var (
   129  		request  = `{"jsonrpc":"2.0","id":1,"method":"rpc_modules"}` + "\n"
   130  		wantResp = `{"jsonrpc":"2.0","id":1,"result":{"nftest":"1.0","rpc":"1.0","test":"1.0"}}` + "\n"
   131  		deadline = time.Now().Add(10 * time.Second)
   132  	)
   133  	for i := 0; i < 20; i++ {
   134  		conn, err := net.Dial("tcp", listener.Addr().String())
   135  		if err != nil {
   136  			t.Fatal("can't dial:", err)
   137  		}
   138  
   139  		conn.SetDeadline(deadline)
   140  		// Write the request, then half-close the connection so the server stops reading.
   141  		conn.Write([]byte(request))
   142  		conn.(*net.TCPConn).CloseWrite()
   143  		// Now try to get the response.
   144  		buf := make([]byte, 2000)
   145  		n, err := conn.Read(buf)
   146  		conn.Close()
   147  
   148  		if err != nil {
   149  			t.Fatal("read error:", err)
   150  		}
   151  		if !bytes.Equal(buf[:n], []byte(wantResp)) {
   152  			t.Fatalf("wrong response: %s", buf[:n])
   153  		}
   154  	}
   155  }
   156  
   157  func TestServerBatchResponseSizeLimit(t *testing.T) {
   158  	server := newTestServer()
   159  	defer server.Stop()
   160  	server.SetBatchLimits(100, 60)
   161  	var (
   162  		batch  []BatchElem
   163  		client = DialInProc(server)
   164  	)
   165  	for i := 0; i < 5; i++ {
   166  		batch = append(batch, BatchElem{
   167  			Method: "test_echo",
   168  			Args:   []any{"x", 1},
   169  			Result: new(echoResult),
   170  		})
   171  	}
   172  	if err := client.BatchCall(batch); err != nil {
   173  		t.Fatal("error sending batch:", err)
   174  	}
   175  	for i := range batch {
   176  		// We expect the first two queries to be ok, but after that the size limit takes effect.
   177  		if i < 2 {
   178  			if batch[i].Error != nil {
   179  				t.Fatalf("batch elem %d has unexpected error: %v", i, batch[i].Error)
   180  			}
   181  			continue
   182  		}
   183  		// After two, we expect an error.
   184  		re, ok := batch[i].Error.(Error)
   185  		if !ok {
   186  			t.Fatalf("batch elem %d has wrong error: %v", i, batch[i].Error)
   187  		}
   188  		wantedCode := errcodeResponseTooLarge
   189  		if re.ErrorCode() != wantedCode {
   190  			t.Errorf("batch elem %d wrong error code, have %d want %d", i, re.ErrorCode(), wantedCode)
   191  		}
   192  	}
   193  }