graphql_test.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. "math/big"
  21. "net/http"
  22. "strings"
  23. "testing"
  24. "time"
  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/node"
  29. "github.com/ethereum/go-ethereum/params"
  30. )
  31. func TestBuildSchema(t *testing.T) {
  32. ddir, err := ioutil.TempDir("", "graphql-buildschema")
  33. if err != nil {
  34. t.Fatalf("failed to create temporary datadir: %v", err)
  35. }
  36. // Copy config
  37. conf := node.DefaultConfig
  38. conf.DataDir = ddir
  39. stack, err := node.New(&conf)
  40. if err != nil {
  41. t.Fatalf("could not create new node: %v", err)
  42. }
  43. // Make sure the schema can be parsed and matched up to the object model.
  44. if err := newHandler(stack, nil, []string{}, []string{}); err != nil {
  45. t.Errorf("Could not construct GraphQL handler: %v", err)
  46. }
  47. }
  48. // Tests that a graphQL request is successfully handled when graphql is enabled on the specified endpoint
  49. func TestGraphQLBlockSerialization(t *testing.T) {
  50. stack := createNode(t, true)
  51. defer stack.Close()
  52. // start node
  53. if err := stack.Start(); err != nil {
  54. t.Fatalf("could not start node: %v", err)
  55. }
  56. for i, tt := range []struct {
  57. body string
  58. want string
  59. code int
  60. }{
  61. { // Should return latest block
  62. body: `{"query": "{block{number}}","variables": null}`,
  63. want: `{"data":{"block":{"number":10}}}`,
  64. code: 200,
  65. },
  66. { // Should return info about latest block
  67. body: `{"query": "{block{number,gasUsed,gasLimit}}","variables": null}`,
  68. want: `{"data":{"block":{"number":10,"gasUsed":0,"gasLimit":11500000}}}`,
  69. code: 200,
  70. },
  71. {
  72. body: `{"query": "{block(number:0){number,gasUsed,gasLimit}}","variables": null}`,
  73. want: `{"data":{"block":{"number":0,"gasUsed":0,"gasLimit":11500000}}}`,
  74. code: 200,
  75. },
  76. {
  77. body: `{"query": "{block(number:-1){number,gasUsed,gasLimit}}","variables": null}`,
  78. want: `{"data":{"block":null}}`,
  79. code: 200,
  80. },
  81. {
  82. body: `{"query": "{block(number:-500){number,gasUsed,gasLimit}}","variables": null}`,
  83. want: `{"data":{"block":null}}`,
  84. code: 200,
  85. },
  86. {
  87. body: `{"query": "{block(number:\"0\"){number,gasUsed,gasLimit}}","variables": null}`,
  88. want: `{"data":{"block":{"number":0,"gasUsed":0,"gasLimit":11500000}}}`,
  89. code: 200,
  90. },
  91. {
  92. body: `{"query": "{block(number:\"-33\"){number,gasUsed,gasLimit}}","variables": null}`,
  93. want: `{"data":{"block":null}}`,
  94. code: 200,
  95. },
  96. {
  97. body: `{"query": "{block(number:\"1337\"){number,gasUsed,gasLimit}}","variables": null}`,
  98. want: `{"data":{"block":null}}`,
  99. code: 200,
  100. },
  101. {
  102. body: `{"query": "{block(number:\"0xbad\"){number,gasUsed,gasLimit}}","variables": null}`,
  103. want: `{"errors":[{"message":"strconv.ParseInt: parsing \"0xbad\": invalid syntax"}],"data":{}}`,
  104. code: 400,
  105. },
  106. { // hex strings are currently not supported. If that's added to the spec, this test will need to change
  107. body: `{"query": "{block(number:\"0x0\"){number,gasUsed,gasLimit}}","variables": null}`,
  108. want: `{"errors":[{"message":"strconv.ParseInt: parsing \"0x0\": invalid syntax"}],"data":{}}`,
  109. code: 400,
  110. },
  111. {
  112. body: `{"query": "{block(number:\"a\"){number,gasUsed,gasLimit}}","variables": null}`,
  113. want: `{"errors":[{"message":"strconv.ParseInt: parsing \"a\": invalid syntax"}],"data":{}}`,
  114. code: 400,
  115. },
  116. {
  117. body: `{"query": "{bleh{number}}","variables": null}"`,
  118. want: `{"errors":[{"message":"Cannot query field \"bleh\" on type \"Query\".","locations":[{"line":1,"column":2}]}]}`,
  119. code: 400,
  120. },
  121. // should return `estimateGas` as decimal
  122. {
  123. body: `{"query": "{block{ estimateGas(data:{}) }}"}`,
  124. want: `{"data":{"block":{"estimateGas":53000}}}`,
  125. code: 200,
  126. },
  127. } {
  128. resp, err := http.Post(fmt.Sprintf("http://%s/graphql", "127.0.0.1:9393"), "application/json", strings.NewReader(tt.body))
  129. if err != nil {
  130. t.Fatalf("could not post: %v", err)
  131. }
  132. bodyBytes, err := ioutil.ReadAll(resp.Body)
  133. if err != nil {
  134. t.Fatalf("could not read from response body: %v", err)
  135. }
  136. if have := string(bodyBytes); have != tt.want {
  137. t.Errorf("testcase %d %s,\nhave:\n%v\nwant:\n%v", i, tt.body, have, tt.want)
  138. }
  139. if tt.code != resp.StatusCode {
  140. t.Errorf("testcase %d %s,\nwrong statuscode, have: %v, want: %v", i, tt.body, resp.StatusCode, tt.code)
  141. }
  142. }
  143. }
  144. // Tests that a graphQL request is not handled successfully when graphql is not enabled on the specified endpoint
  145. func TestGraphQLHTTPOnSamePort_GQLRequest_Unsuccessful(t *testing.T) {
  146. stack := createNode(t, false)
  147. defer stack.Close()
  148. if err := stack.Start(); err != nil {
  149. t.Fatalf("could not start node: %v", err)
  150. }
  151. body := strings.NewReader(`{"query": "{block{number}}","variables": null}`)
  152. resp, err := http.Post(fmt.Sprintf("http://%s/graphql", "127.0.0.1:9393"), "application/json", body)
  153. if err != nil {
  154. t.Fatalf("could not post: %v", err)
  155. }
  156. bodyBytes, err := ioutil.ReadAll(resp.Body)
  157. if err != nil {
  158. t.Fatalf("could not read from response body: %v", err)
  159. }
  160. resp.Body.Close()
  161. // make sure the request is not handled successfully
  162. if want, have := "404 page not found\n", string(bodyBytes); have != want {
  163. t.Errorf("have:\n%v\nwant:\n%v", have, want)
  164. }
  165. if want, have := 404, resp.StatusCode; want != have {
  166. t.Errorf("wrong statuscode, have:\n%v\nwant:%v", have, want)
  167. }
  168. }
  169. func createNode(t *testing.T, gqlEnabled bool) *node.Node {
  170. stack, err := node.New(&node.Config{
  171. HTTPHost: "127.0.0.1",
  172. HTTPPort: 9393,
  173. WSHost: "127.0.0.1",
  174. WSPort: 9393,
  175. })
  176. if err != nil {
  177. t.Fatalf("could not create node: %v", err)
  178. }
  179. if !gqlEnabled {
  180. return stack
  181. }
  182. createGQLService(t, stack, "127.0.0.1:9393")
  183. return stack
  184. }
  185. func createGQLService(t *testing.T, stack *node.Node, endpoint string) {
  186. // create backend
  187. ethConf := &eth.Config{
  188. Genesis: &core.Genesis{
  189. Config: params.AllEthashProtocolChanges,
  190. GasLimit: 11500000,
  191. Difficulty: big.NewInt(1048576),
  192. },
  193. Ethash: ethash.Config{
  194. PowMode: ethash.ModeFake,
  195. },
  196. NetworkId: 1337,
  197. TrieCleanCache: 5,
  198. TrieCleanCacheJournal: "triecache",
  199. TrieCleanCacheRejournal: 60 * time.Minute,
  200. TrieDirtyCache: 5,
  201. TrieTimeout: 60 * time.Minute,
  202. SnapshotCache: 5,
  203. }
  204. ethBackend, err := eth.New(stack, ethConf)
  205. if err != nil {
  206. t.Fatalf("could not create eth backend: %v", err)
  207. }
  208. // Create some blocks and import them
  209. chain, _ := core.GenerateChain(params.AllEthashProtocolChanges, ethBackend.BlockChain().Genesis(),
  210. ethash.NewFaker(), ethBackend.ChainDb(), 10, func(i int, gen *core.BlockGen) {})
  211. _, err = ethBackend.BlockChain().InsertChain(chain)
  212. if err != nil {
  213. t.Fatalf("could not create import blocks: %v", err)
  214. }
  215. // create gql service
  216. err = New(stack, ethBackend.APIBackend, []string{}, []string{})
  217. if err != nil {
  218. t.Fatalf("could not create graphql service: %v", err)
  219. }
  220. }