graphql_test.go 7.5 KB

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