forked from machinebox/graphql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
graphql_json_test.go
107 lines (88 loc) · 2.32 KB
/
graphql_json_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
99
100
101
102
103
104
105
106
107
package graphql
import (
"context"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/matryer/is"
)
func TestDoJSON(t *testing.T) {
is := is.New(t)
var calls int
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
is.Equal(r.Method, http.MethodPost)
b, err := ioutil.ReadAll(r.Body)
is.NoErr(err)
is.Equal(string(b), `{"query":"query {}","variables":null}`+"\n")
io.WriteString(w, `{
"data": {
"something": "yes"
}
}`)
}))
defer srv.Close()
ctx := context.Background()
client := NewClient(srv.URL)
ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
defer cancel()
var responseData map[string]interface{}
err := client.Run(ctx, &Request{q: "query {}"}, &responseData)
is.NoErr(err)
is.Equal(calls, 1) // calls
is.Equal(responseData["something"], "yes")
}
func TestQueryJSON(t *testing.T) {
is := is.New(t)
var calls int
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
b, err := ioutil.ReadAll(r.Body)
is.NoErr(err)
is.Equal(string(b), `{"query":"query {}","variables":{"username":"matryer"}}`+"\n")
_, err = io.WriteString(w, `{"data":{"value":"some data"}}`)
is.NoErr(err)
}))
defer srv.Close()
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
client := NewClient(srv.URL)
req := NewRequest("query {}")
req.Var("username", "matryer")
// check variables
is.True(req != nil)
is.Equal(req.vars["username"], "matryer")
var resp struct {
Value string
}
err := client.Run(ctx, req, &resp)
is.NoErr(err)
is.Equal(calls, 1)
is.Equal(resp.Value, "some data")
}
func TestHeader(t *testing.T) {
is := is.New(t)
var calls int
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
is.Equal(r.Header.Get("X-Custom-Header"), "123")
_, err := io.WriteString(w, `{"data":{"value":"some data"}}`)
is.NoErr(err)
}))
defer srv.Close()
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
client := NewClient(srv.URL)
req := NewRequest("query {}")
req.Header.Set("X-Custom-Header", "123")
var resp struct {
Value string
}
err := client.Run(ctx, req, &resp)
is.NoErr(err)
is.Equal(calls, 1)
is.Equal(resp.Value, "some data")
}