server_test.go 5.26 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Copyright 2015 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package rpc
18 19

import (
20 21 22
	"bufio"
	"bytes"
	"io"
23
	"net"
24
	"os"
25 26
	"path/filepath"
	"strings"
27
	"testing"
28
	"time"
29 30 31 32
)

func TestServerRegisterName(t *testing.T) {
	server := NewServer()
33
	service := new(testService)
34

35
	if err := server.RegisterName("test", service); err != nil {
36 37 38
		t.Fatalf("%v", err)
	}

39 40
	if len(server.services.services) != 2 {
		t.Fatalf("Expected 2 service entries, got %d", len(server.services.services))
41 42
	}

43
	svc, ok := server.services.services["test"]
44 45 46 47
	if !ok {
		t.Fatalf("Expected service calc to be registered")
	}

48
	wantCallbacks := 13
49 50
	if len(svc.callbacks) != wantCallbacks {
		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 57
	if err != nil {
		t.Fatal("where'd my testdata go?")
58
	}
59 60 61 62 63 64 65 66 67 68 69
	for _, f := range files {
		if f.IsDir() || strings.HasPrefix(f.Name(), ".") {
			continue
		}
		path := filepath.Join("testdata", f.Name())
		name := strings.TrimSuffix(f.Name(), filepath.Ext(f.Name()))
		t.Run(name, func(t *testing.T) {
			runTestScript(t, path)
		})
	}
}
70

71 72
func runTestScript(t *testing.T, file string) {
	server := newTestServer()
73
	server.SetBatchLimits(4, 100000)
74
	content, err := os.ReadFile(file)
75 76
	if err != nil {
		t.Fatal(err)
77
	}
78

79 80
	clientConn, serverConn := net.Pipe()
	defer clientConn.Close()
81
	go server.ServeCodec(NewCodec(serverConn), 0)
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
	readbuf := bufio.NewReader(clientConn)
	for _, line := range strings.Split(string(content), "\n") {
		line = strings.TrimSpace(line)
		switch {
		case len(line) == 0 || strings.HasPrefix(line, "//"):
			// skip comments, blank lines
			continue
		case strings.HasPrefix(line, "--> "):
			t.Log(line)
			// write to connection
			clientConn.SetWriteDeadline(time.Now().Add(5 * time.Second))
			if _, err := io.WriteString(clientConn, line[4:]+"\n"); err != nil {
				t.Fatalf("write error: %v", err)
			}
		case strings.HasPrefix(line, "<-- "):
			t.Log(line)
			want := line[4:]
			// read line from connection and compare text
			clientConn.SetReadDeadline(time.Now().Add(5 * time.Second))
			sent, err := readbuf.ReadString('\n')
			if err != nil {
				t.Fatalf("read error: %v", err)
			}
			sent = strings.TrimRight(sent, "\r\n")
			if sent != want {
				t.Errorf("wrong line from server\ngot:  %s\nwant: %s", sent, want)
			}
		default:
			panic("invalid line in test script: " + line)
		}
112
	}
113
}
114

115 116 117 118 119
// This test checks that responses are delivered for very short-lived connections that
// only carry a single request.
func TestServerShortLivedConn(t *testing.T) {
	server := newTestServer()
	defer server.Stop()
120

121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
	listener, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatal("can't listen:", err)
	}
	defer listener.Close()
	go server.ServeListener(listener)

	var (
		request  = `{"jsonrpc":"2.0","id":1,"method":"rpc_modules"}` + "\n"
		wantResp = `{"jsonrpc":"2.0","id":1,"result":{"nftest":"1.0","rpc":"1.0","test":"1.0"}}` + "\n"
		deadline = time.Now().Add(10 * time.Second)
	)
	for i := 0; i < 20; i++ {
		conn, err := net.Dial("tcp", listener.Addr().String())
		if err != nil {
			t.Fatal("can't dial:", err)
137
		}
138

139 140 141 142 143 144 145
		conn.SetDeadline(deadline)
		// Write the request, then half-close the connection so the server stops reading.
		conn.Write([]byte(request))
		conn.(*net.TCPConn).CloseWrite()
		// Now try to get the response.
		buf := make([]byte, 2000)
		n, err := conn.Read(buf)
146 147
		conn.Close()

148 149
		if err != nil {
			t.Fatal("read error:", err)
150
		}
151 152
		if !bytes.Equal(buf[:n], []byte(wantResp)) {
			t.Fatalf("wrong response: %s", buf[:n])
153 154 155
		}
	}
}
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193

func TestServerBatchResponseSizeLimit(t *testing.T) {
	server := newTestServer()
	defer server.Stop()
	server.SetBatchLimits(100, 60)
	var (
		batch  []BatchElem
		client = DialInProc(server)
	)
	for i := 0; i < 5; i++ {
		batch = append(batch, BatchElem{
			Method: "test_echo",
			Args:   []any{"x", 1},
			Result: new(echoResult),
		})
	}
	if err := client.BatchCall(batch); err != nil {
		t.Fatal("error sending batch:", err)
	}
	for i := range batch {
		// We expect the first two queries to be ok, but after that the size limit takes effect.
		if i < 2 {
			if batch[i].Error != nil {
				t.Fatalf("batch elem %d has unexpected error: %v", i, batch[i].Error)
			}
			continue
		}
		// After two, we expect an error.
		re, ok := batch[i].Error.(Error)
		if !ok {
			t.Fatalf("batch elem %d has wrong error: %v", i, batch[i].Error)
		}
		wantedCode := errcodeResponseTooLarge
		if re.ErrorCode() != wantedCode {
			t.Errorf("batch elem %d wrong error code, have %d want %d", i, re.ErrorCode(), wantedCode)
		}
	}
}