graphql_test.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. // Copyright 2019 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 graphql
  17. import (
  18. "fmt"
  19. "io/ioutil"
  20. "net/http"
  21. "strings"
  22. "testing"
  23. "time"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/consensus/ethash"
  26. "github.com/ethereum/go-ethereum/core"
  27. "github.com/ethereum/go-ethereum/eth"
  28. "github.com/ethereum/go-ethereum/miner"
  29. "github.com/ethereum/go-ethereum/node"
  30. "github.com/stretchr/testify/assert"
  31. )
  32. func TestBuildSchema(t *testing.T) {
  33. stack, err := node.New(&node.DefaultConfig)
  34. if err != nil {
  35. t.Fatalf("could not create new node: %v", err)
  36. }
  37. // Make sure the schema can be parsed and matched up to the object model.
  38. if err := newHandler(stack, nil, []string{}, []string{}); err != nil {
  39. t.Errorf("Could not construct GraphQL handler: %v", err)
  40. }
  41. }
  42. // Tests that a graphQL request is successfully handled when graphql is enabled on the specified endpoint
  43. func TestGraphQLHTTPOnSamePort_GQLRequest_Successful(t *testing.T) {
  44. stack := createNode(t, true)
  45. defer stack.Close()
  46. // start node
  47. if err := stack.Start(); err != nil {
  48. t.Fatalf("could not start node: %v", err)
  49. }
  50. // create http request
  51. body := strings.NewReader("{\"query\": \"{block{number}}\",\"variables\": null}")
  52. gqlReq, err := http.NewRequest(http.MethodGet, fmt.Sprintf("http://%s/graphql", "127.0.0.1:9393"), body)
  53. if err != nil {
  54. t.Error("could not issue new http request ", err)
  55. }
  56. gqlReq.Header.Set("Content-Type", "application/json")
  57. // read from response
  58. resp := doHTTPRequest(t, gqlReq)
  59. bodyBytes, err := ioutil.ReadAll(resp.Body)
  60. if err != nil {
  61. t.Fatalf("could not read from response body: %v", err)
  62. }
  63. expected := "{\"data\":{\"block\":{\"number\":\"0x0\"}}}"
  64. assert.Equal(t, 200, resp.StatusCode)
  65. assert.Equal(t, expected, string(bodyBytes))
  66. }
  67. // Tests that a graphQL request is not handled successfully when graphql is not enabled on the specified endpoint
  68. func TestGraphQLHTTPOnSamePort_GQLRequest_Unsuccessful(t *testing.T) {
  69. stack := createNode(t, false)
  70. defer stack.Close()
  71. if err := stack.Start(); err != nil {
  72. t.Fatalf("could not start node: %v", err)
  73. }
  74. // create http request
  75. body := strings.NewReader("{\"query\": \"{block{number}}\",\"variables\": null}")
  76. gqlReq, err := http.NewRequest(http.MethodPost, fmt.Sprintf("http://%s/graphql", "127.0.0.1:9393"), body)
  77. if err != nil {
  78. t.Error("could not issue new http request ", err)
  79. }
  80. gqlReq.Header.Set("Content-Type", "application/json")
  81. // read from response
  82. resp := doHTTPRequest(t, gqlReq)
  83. bodyBytes, err := ioutil.ReadAll(resp.Body)
  84. if err != nil {
  85. t.Fatalf("could not read from response body: %v", err)
  86. }
  87. // make sure the request is not handled successfully
  88. assert.Equal(t, 404, resp.StatusCode)
  89. assert.Equal(t, "404 page not found\n", string(bodyBytes))
  90. }
  91. // Tests that 400 is returned when an invalid RPC request is made.
  92. func TestGraphQL_BadRequest(t *testing.T) {
  93. stack := createNode(t, true)
  94. defer stack.Close()
  95. // start node
  96. if err := stack.Start(); err != nil {
  97. t.Fatalf("could not start node: %v", err)
  98. }
  99. // create http request
  100. body := strings.NewReader("{\"query\": \"{bleh{number}}\",\"variables\": null}")
  101. gqlReq, err := http.NewRequest(http.MethodGet, fmt.Sprintf("http://%s/graphql", "127.0.0.1:9393"), body)
  102. if err != nil {
  103. t.Error("could not issue new http request ", err)
  104. }
  105. gqlReq.Header.Set("Content-Type", "application/json")
  106. // read from response
  107. resp := doHTTPRequest(t, gqlReq)
  108. bodyBytes, err := ioutil.ReadAll(resp.Body)
  109. if err != nil {
  110. t.Fatalf("could not read from response body: %v", err)
  111. }
  112. expected := "{\"errors\":[{\"message\":\"Cannot query field \\\"bleh\\\" on type \\\"Query\\\".\",\"locations\":[{\"line\":1,\"column\":2}]}]}"
  113. assert.Equal(t, expected, string(bodyBytes))
  114. assert.Equal(t, 400, resp.StatusCode)
  115. }
  116. func createNode(t *testing.T, gqlEnabled bool) *node.Node {
  117. stack, err := node.New(&node.Config{
  118. HTTPHost: "127.0.0.1",
  119. HTTPPort: 9393,
  120. WSHost: "127.0.0.1",
  121. WSPort: 9393,
  122. })
  123. if err != nil {
  124. t.Fatalf("could not create node: %v", err)
  125. }
  126. if !gqlEnabled {
  127. return stack
  128. }
  129. createGQLService(t, stack, "127.0.0.1:9393")
  130. return stack
  131. }
  132. func createGQLService(t *testing.T, stack *node.Node, endpoint string) {
  133. // create backend (use a config which is light on mem consumption)
  134. ethConf := &eth.Config{
  135. Genesis: core.DeveloperGenesisBlock(15, common.Address{}),
  136. Miner: miner.Config{
  137. Etherbase: common.HexToAddress("0xaabb"),
  138. },
  139. Ethash: ethash.Config{
  140. PowMode: ethash.ModeTest,
  141. },
  142. NetworkId: 1337,
  143. TrieCleanCache: 5,
  144. TrieCleanCacheJournal: "triecache",
  145. TrieCleanCacheRejournal: 60 * time.Minute,
  146. TrieDirtyCache: 5,
  147. TrieTimeout: 60 * time.Minute,
  148. SnapshotCache: 5,
  149. }
  150. ethBackend, err := eth.New(stack, ethConf)
  151. if err != nil {
  152. t.Fatalf("could not create eth backend: %v", err)
  153. }
  154. // create gql service
  155. err = New(stack, ethBackend.APIBackend, []string{}, []string{})
  156. if err != nil {
  157. t.Fatalf("could not create graphql service: %v", err)
  158. }
  159. }
  160. func doHTTPRequest(t *testing.T, req *http.Request) *http.Response {
  161. client := &http.Client{}
  162. resp, err := client.Do(req)
  163. if err != nil {
  164. t.Fatal("could not issue a GET request to the given endpoint", err)
  165. }
  166. return resp
  167. }