graphql_test.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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. // should return `status` as decimal
  128. {
  129. body: `{"query": "{block {number call (data : {from : \"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b\", to: \"0x6295ee1b4f6dd65047762f924ecd367c17eabf8f\", data :\"0x12a7b914\"}){data status}}}"}`,
  130. want: `{"data":{"block":{"number":10,"call":{"data":"0x","status":1}}}}`,
  131. code: 200,
  132. },
  133. } {
  134. resp, err := http.Post(fmt.Sprintf("%s/graphql", stack.HTTPEndpoint()), "application/json", strings.NewReader(tt.body))
  135. if err != nil {
  136. t.Fatalf("could not post: %v", err)
  137. }
  138. bodyBytes, err := ioutil.ReadAll(resp.Body)
  139. if err != nil {
  140. t.Fatalf("could not read from response body: %v", err)
  141. }
  142. if have := string(bodyBytes); have != tt.want {
  143. t.Errorf("testcase %d %s,\nhave:\n%v\nwant:\n%v", i, tt.body, have, tt.want)
  144. }
  145. if tt.code != resp.StatusCode {
  146. t.Errorf("testcase %d %s,\nwrong statuscode, have: %v, want: %v", i, tt.body, resp.StatusCode, tt.code)
  147. }
  148. }
  149. }
  150. // Tests that a graphQL request is not handled successfully when graphql is not enabled on the specified endpoint
  151. func TestGraphQLHTTPOnSamePort_GQLRequest_Unsuccessful(t *testing.T) {
  152. stack := createNode(t, false)
  153. defer stack.Close()
  154. if err := stack.Start(); err != nil {
  155. t.Fatalf("could not start node: %v", err)
  156. }
  157. body := strings.NewReader(`{"query": "{block{number}}","variables": null}`)
  158. resp, err := http.Post(fmt.Sprintf("%s/graphql", stack.HTTPEndpoint()), "application/json", body)
  159. if err != nil {
  160. t.Fatalf("could not post: %v", err)
  161. }
  162. bodyBytes, err := ioutil.ReadAll(resp.Body)
  163. if err != nil {
  164. t.Fatalf("could not read from response body: %v", err)
  165. }
  166. resp.Body.Close()
  167. // make sure the request is not handled successfully
  168. if want, have := "404 page not found\n", string(bodyBytes); have != want {
  169. t.Errorf("have:\n%v\nwant:\n%v", have, want)
  170. }
  171. if want, have := 404, resp.StatusCode; want != have {
  172. t.Errorf("wrong statuscode, have:\n%v\nwant:%v", have, want)
  173. }
  174. }
  175. func createNode(t *testing.T, gqlEnabled bool) *node.Node {
  176. stack, err := node.New(&node.Config{
  177. HTTPHost: "127.0.0.1",
  178. HTTPPort: 0,
  179. WSHost: "127.0.0.1",
  180. WSPort: 0,
  181. })
  182. if err != nil {
  183. t.Fatalf("could not create node: %v", err)
  184. }
  185. if !gqlEnabled {
  186. return stack
  187. }
  188. createGQLService(t, stack)
  189. return stack
  190. }
  191. func createGQLService(t *testing.T, stack *node.Node) {
  192. // create backend
  193. ethConf := &eth.Config{
  194. Genesis: &core.Genesis{
  195. Config: params.AllEthashProtocolChanges,
  196. GasLimit: 11500000,
  197. Difficulty: big.NewInt(1048576),
  198. },
  199. Ethash: ethash.Config{
  200. PowMode: ethash.ModeFake,
  201. },
  202. NetworkId: 1337,
  203. TrieCleanCache: 5,
  204. TrieCleanCacheJournal: "triecache",
  205. TrieCleanCacheRejournal: 60 * time.Minute,
  206. TrieDirtyCache: 5,
  207. TrieTimeout: 60 * time.Minute,
  208. SnapshotCache: 5,
  209. }
  210. ethBackend, err := eth.New(stack, ethConf)
  211. if err != nil {
  212. t.Fatalf("could not create eth backend: %v", err)
  213. }
  214. // Create some blocks and import them
  215. chain, _ := core.GenerateChain(params.AllEthashProtocolChanges, ethBackend.BlockChain().Genesis(),
  216. ethash.NewFaker(), ethBackend.ChainDb(), 10, func(i int, gen *core.BlockGen) {})
  217. _, err = ethBackend.BlockChain().InsertChain(chain)
  218. if err != nil {
  219. t.Fatalf("could not create import blocks: %v", err)
  220. }
  221. // create gql service
  222. err = New(stack, ethBackend.APIBackend, []string{}, []string{})
  223. if err != nil {
  224. t.Fatalf("could not create graphql service: %v", err)
  225. }
  226. }