This repository has been archived by the owner on Aug 28, 2023. It is now read-only.
/
client.go
123 lines (107 loc) · 2.45 KB
/
client.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package setup
import (
"net/url"
"testing"
"time"
"github.com/romshark/dgraph_graphql_go/api/graph"
"github.com/romshark/dgraph_graphql_go/api/graph/gqlmod"
trn "github.com/romshark/dgraph_graphql_go/api/transport"
thttp "github.com/romshark/dgraph_graphql_go/api/transport/http"
"github.com/romshark/dgraph_graphql_go/store/errors"
"github.com/stretchr/testify/require"
)
// Client represents an API client
type Client struct {
t *testing.T
ts *TestSetup
apiClient trn.Client
Help Helper
}
// Query performs an API query
func (tclt *Client) Query(
query string,
result interface{},
) error {
return tclt.apiClient.Query(query, result)
}
// QueryVar performs a parameterized API query
func (tclt *Client) QueryVar(
query string,
vars map[string]interface{},
result interface{},
) error {
return tclt.apiClient.QueryVar(query, vars, result)
}
// Guest creates a new unauthenticated API client
func (ts *TestSetup) Guest() *Client {
// Initialize client
apiClt, err := thttp.NewClient(
url.URL{
Scheme: "http",
Host: ts.serverTransport.(*thttp.Server).Addr().Host,
},
thttp.ClientConfig{
Timeout: time.Second * 10,
},
)
require.NoError(ts.t, err)
clt := &Client{
t: ts.t,
ts: ts,
apiClient: apiClt,
}
// Initialize helper
clt.Help = Helper{
ts: ts,
c: clt,
creationTimeTollerance: time.Second * 3,
}
clt.Help.OK = AssumeSuccess{
h: &clt.Help,
t: ts.t,
}
clt.Help.ERR = AssumeFailure{
h: &clt.Help,
t: ts.t,
}
return clt
}
// Debug creates a new authenticated API debug client
func (ts *TestSetup) Debug() *Client {
clt := ts.Guest()
// Sign in as debug user
require.NoError(ts.t, clt.apiClient.SignInDebug(
ts.debugUsername,
ts.debugPassword,
))
return clt
}
// Client creates a new authenticated API client
func (ts *TestSetup) Client(
email,
password string,
) (*Client, *gqlmod.Session) {
clt := ts.Guest()
sess, err := clt.apiClient.SignIn(email, password)
require.Nil(ts.t, err)
return clt, sess
}
// checkErr ensures the response error is as expected
func checkErr(
t *testing.T,
expectedErrorCode errors.Code,
err error,
) {
if expectedErrorCode != "" {
require.NotNil(t, err)
require.IsType(t, &graph.ResponseError{}, err)
require.Equal(
t,
string(expectedErrorCode),
err.(*graph.ResponseError).Code,
)
require.True(t, len(err.(*graph.ResponseError).Message) > 0)
} else {
require.Nil(t, err)
}
}