-
Notifications
You must be signed in to change notification settings - Fork 3
/
server_test.go
98 lines (78 loc) · 1.99 KB
/
server_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"testing"
"github.com/jensneuse/graphql-go-tools/pkg/graphql"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var httpClient *http.Client
func TestMainFunc(t *testing.T) {
go main()
t.Run("should get all heroes", func(t *testing.T) {
gqlReqBody := graphql.Request{
Query: "{ heroes { name ...on Human { hasLightsaber } ...on Droid { primaryFunction } } }",
}
heroResponse := executeGraphQLRequest(t, gqlReqBody)
assert.JSONEq(t, expectedHeroes, string(heroResponse.Data))
})
t.Run("should get all type names excluding interfaces", func(t *testing.T) {
gqlReqBody := graphql.Request{
Query: "{ types }",
}
typesResponse := executeGraphQLRequest(t, gqlReqBody)
assert.JSONEq(t, expectedTypes, string(typesResponse.Data))
})
}
func executeGraphQLRequest(t *testing.T, reqBody graphql.Request) GraphQLResponse {
t.Helper()
bodyBytes, err := json.Marshal(reqBody)
require.NoError(t, err)
req, err := http.NewRequest(http.MethodPost, "http://localhost:8085/query", bytes.NewBuffer(bodyBytes))
require.NoError(t, err)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
if httpClient == nil {
httpClient = &http.Client{}
}
resp, err := httpClient.Do(req)
require.NoError(t, err)
require.Equalf(t, http.StatusOK, resp.StatusCode, "response status code is not 200")
respBody, err := ioutil.ReadAll(resp.Body)
require.NoError(t, err)
gqlResponse := GraphQLResponse{}
err = json.Unmarshal(respBody, &gqlResponse)
require.NoError(t, err)
return gqlResponse
}
type GraphQLResponse struct {
Data json.RawMessage `json:"data"`
}
var expectedHeroes = `{
"heroes": [
{
"name": "Luke Skywalker",
"hasLightsaber": true
},
{
"name": "Han Solo",
"hasLightsaber": false
},
{
"name": "C-3PO",
"primaryFunction": "Translator"
}
]
}
`
var expectedTypes = `{
"types": [
"Query",
"Human",
"Droid"
]
}
`