graphql_test.go 7.5 KB

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