server_test.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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. package rpc
  17. import (
  18. "bufio"
  19. "bytes"
  20. "io"
  21. "net"
  22. "os"
  23. "path/filepath"
  24. "strings"
  25. "testing"
  26. "time"
  27. )
  28. func TestServerRegisterName(t *testing.T) {
  29. server := NewServer()
  30. service := new(testService)
  31. if err := server.RegisterName("test", service); err != nil {
  32. t.Fatalf("%v", err)
  33. }
  34. if len(server.services.services) != 2 {
  35. t.Fatalf("Expected 2 service entries, got %d", len(server.services.services))
  36. }
  37. svc, ok := server.services.services["test"]
  38. if !ok {
  39. t.Fatalf("Expected service calc to be registered")
  40. }
  41. wantCallbacks := 10
  42. if len(svc.callbacks) != wantCallbacks {
  43. t.Errorf("Expected %d callbacks for service 'service', got %d", wantCallbacks, len(svc.callbacks))
  44. }
  45. }
  46. func TestServer(t *testing.T) {
  47. files, err := os.ReadDir("testdata")
  48. if err != nil {
  49. t.Fatal("where'd my testdata go?")
  50. }
  51. for _, f := range files {
  52. if f.IsDir() || strings.HasPrefix(f.Name(), ".") {
  53. continue
  54. }
  55. path := filepath.Join("testdata", f.Name())
  56. name := strings.TrimSuffix(f.Name(), filepath.Ext(f.Name()))
  57. t.Run(name, func(t *testing.T) {
  58. runTestScript(t, path)
  59. })
  60. }
  61. }
  62. func runTestScript(t *testing.T, file string) {
  63. server := newTestServer()
  64. content, err := os.ReadFile(file)
  65. if err != nil {
  66. t.Fatal(err)
  67. }
  68. clientConn, serverConn := net.Pipe()
  69. defer clientConn.Close()
  70. go server.ServeCodec(NewCodec(serverConn), 0)
  71. readbuf := bufio.NewReader(clientConn)
  72. for _, line := range strings.Split(string(content), "\n") {
  73. line = strings.TrimSpace(line)
  74. switch {
  75. case len(line) == 0 || strings.HasPrefix(line, "//"):
  76. // skip comments, blank lines
  77. continue
  78. case strings.HasPrefix(line, "--> "):
  79. t.Log(line)
  80. // write to connection
  81. clientConn.SetWriteDeadline(time.Now().Add(5 * time.Second))
  82. if _, err := io.WriteString(clientConn, line[4:]+"\n"); err != nil {
  83. t.Fatalf("write error: %v", err)
  84. }
  85. case strings.HasPrefix(line, "<-- "):
  86. t.Log(line)
  87. want := line[4:]
  88. // read line from connection and compare text
  89. clientConn.SetReadDeadline(time.Now().Add(5 * time.Second))
  90. sent, err := readbuf.ReadString('\n')
  91. if err != nil {
  92. t.Fatalf("read error: %v", err)
  93. }
  94. sent = strings.TrimRight(sent, "\r\n")
  95. if sent != want {
  96. t.Errorf("wrong line from server\ngot: %s\nwant: %s", sent, want)
  97. }
  98. default:
  99. panic("invalid line in test script: " + line)
  100. }
  101. }
  102. }
  103. // This test checks that responses are delivered for very short-lived connections that
  104. // only carry a single request.
  105. func TestServerShortLivedConn(t *testing.T) {
  106. server := newTestServer()
  107. defer server.Stop()
  108. listener, err := net.Listen("tcp", "127.0.0.1:0")
  109. if err != nil {
  110. t.Fatal("can't listen:", err)
  111. }
  112. defer listener.Close()
  113. go server.ServeListener(listener)
  114. var (
  115. request = `{"jsonrpc":"2.0","id":1,"method":"rpc_modules"}` + "\n"
  116. wantResp = `{"jsonrpc":"2.0","id":1,"result":{"nftest":"1.0","rpc":"1.0","test":"1.0"}}` + "\n"
  117. deadline = time.Now().Add(10 * time.Second)
  118. )
  119. for i := 0; i < 20; i++ {
  120. conn, err := net.Dial("tcp", listener.Addr().String())
  121. if err != nil {
  122. t.Fatal("can't dial:", err)
  123. }
  124. conn.SetDeadline(deadline)
  125. // Write the request, then half-close the connection so the server stops reading.
  126. conn.Write([]byte(request))
  127. conn.(*net.TCPConn).CloseWrite()
  128. // Now try to get the response.
  129. buf := make([]byte, 2000)
  130. n, err := conn.Read(buf)
  131. conn.Close()
  132. if err != nil {
  133. t.Fatal("read error:", err)
  134. }
  135. if !bytes.Equal(buf[:n], []byte(wantResp)) {
  136. t.Fatalf("wrong response: %s", buf[:n])
  137. }
  138. }
  139. }