github.com/cryptogateway/go-paymex@v0.0.0-20210204174735-96277fb1e602/graphql/graphql_test.go (about)

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