forked from OpsLevel/opslevel-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclientGQL_test.go
233 lines (208 loc) · 7.07 KB
/
clientGQL_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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
package opslevel_test
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"text/template"
"github.com/Masterminds/sprig/v3"
ol "github.com/opslevel/opslevel-go/v2023"
"github.com/rocktavious/autopilot/v2023"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
var (
dataTemplater = NewTestDataTemplater()
id1 = ol.ID(dataTemplater.ParseValue("id1_string"))
id2 = ol.ID(dataTemplater.ParseValue("id2_string"))
id3 = ol.ID(dataTemplater.ParseValue("id3_string"))
id4 = ol.ID(dataTemplater.ParseValue("id4_string"))
)
func TestMain(m *testing.M) {
output := zerolog.ConsoleWriter{Out: os.Stderr}
log.Logger = log.Output(output)
flag.Parse()
teardown := autopilot.Setup()
defer teardown()
os.Exit(m.Run())
}
func Templated(input string) string {
response, err := autopilot.Templater.Use(input)
if err != nil {
panic(err)
}
return response
}
func TemplatedResponse(response string) autopilot.ResponseWriter {
return func(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, Templated(response))
}
}
func GraphQLQueryTemplate(request string) autopilot.GraphqlQuery {
exp := autopilot.GraphqlQuery{
Variables: nil,
}
json.Unmarshal([]byte(Templated(request)), &exp)
return exp
}
func GraphQLQueryTemplatedValidation(t *testing.T, request string) autopilot.RequestValidation {
return func(r *http.Request) {
autopilot.Equals(t, autopilot.ToJson(GraphQLQueryTemplate(request)), autopilot.ToJson(autopilot.Parse(r)))
}
}
func ABetterTestClient(t *testing.T, endpoint string, request string, response string) *ol.Client {
return ol.NewGQLClient(ol.SetAPIToken("x"), ol.SetMaxRetries(0), ol.SetURL(autopilot.RegisterEndpoint(fmt.Sprintf("/LOCAL_TESTING/%s", endpoint),
TemplatedResponse(response),
GraphQLQueryTemplatedValidation(t, request))))
}
func ATestClient(t *testing.T, endpoint string) *ol.Client {
return ol.NewGQLClient(ol.SetAPIToken("x"), ol.SetMaxRetries(0), ol.SetURL(autopilot.RegisterEndpoint(fmt.Sprintf("/LOCAL_TESTING/%s", endpoint),
autopilot.FixtureResponse(fmt.Sprintf("%s_response.json", endpoint)),
autopilot.GraphQLQueryFixtureValidation(t, fmt.Sprintf("%s_request.json", endpoint)))))
}
func NewTestRequest(request string, variables string, response string) TestRequest {
templater := NewTestDataTemplater()
testRequest := TestRequest{
Request: templater.ParseTemplatedString(request),
Variables: templater.ParseTemplatedString(variables),
Response: templater.ParseTemplatedString(response),
}
if !strings.HasPrefix(testRequest.Request, "\"") || !strings.HasSuffix(testRequest.Request, "\"") {
panic(fmt.Errorf("testRequest Request should be wrapped in quotes: '%s'", testRequest.Request))
}
if !IsValidJson(testRequest.Variables) {
panic(fmt.Errorf("testRequest Variables is not valid json: '%s'", testRequest.Variables))
}
if !IsValidJson(testRequest.Response) {
panic(fmt.Errorf("testRequest Response is not json: '%s'", testRequest.Response))
}
return testRequest
}
func NewTestDataTemplater(templateDirs ...string) *TestDataTemplater {
var templateFiles []string
for _, dir := range []string{"./testdata/templates"} {
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
templateFiles = append(templateFiles, path)
}
return nil
})
if err != nil {
panic(fmt.Errorf("error during loading template files: %s", err))
}
}
output := TestDataTemplater{}
tmpl := template.New("")
tmpl.Funcs(template.FuncMap{
"WrapWithCurlyBrackets": func(value string) string { return "{ " + value + " }" },
})
tmpl.Funcs(sprig.TxtFuncMap())
tmpl, err := tmpl.ParseFiles(templateFiles...)
if err != nil {
panic(fmt.Errorf("error during template initialization: %s", err))
}
output.rootTemplate = tmpl
return &output
}
type TestDataTemplater struct {
rootTemplate *template.Template
}
func (t *TestDataTemplater) ParseValue(value string) string {
return t.ParseTemplatedString(`{{ template "` + value + `" }}`)
}
func (t *TestDataTemplater) ParseTemplatedString(contents string) string {
target, err := t.rootTemplate.Parse(contents)
if err != nil {
panic(fmt.Errorf("error parsing template: %s", err))
}
data := bytes.NewBuffer([]byte{})
if err = target.Execute(data, nil); err != nil {
panic(err)
}
return strings.TrimSpace(data.String())
}
type TestRequest struct {
Request string
Variables string
Response string
}
func (t *TestRequest) RequestWithVariables() string {
jsonRequestWithVariables := fmt.Sprintf(`{"query": %s, "variables": %s}`, t.Request, t.Variables)
if !IsValidJson(jsonRequestWithVariables) {
panic(fmt.Errorf("test request with variables could not be JSON formatted: %s", jsonRequestWithVariables))
}
return jsonRequestWithVariables
}
func IsValidJson(data string) bool {
return json.Valid([]byte(data))
}
func RegisterPaginatedEndpoint(t *testing.T, endpoint string, requests ...TestRequest) string {
url := fmt.Sprintf("/LOCAL_TESTING/%s", endpoint)
requestCount := 0
autopilot.Mux.HandleFunc(url, func(w http.ResponseWriter, r *http.Request) {
GraphQLQueryTemplatedValidation(t, requests[requestCount].RequestWithVariables())(r)
TemplatedResponse(requests[requestCount].Response)(w)
requestCount += 1
})
return autopilot.Server.URL + url
}
func BestTestClient(t *testing.T, endpoint string, requests ...TestRequest) *ol.Client {
url := RegisterPaginatedEndpoint(t, endpoint, requests...)
return ol.NewGQLClient(ol.SetAPIToken("x"), ol.SetMaxRetries(0), ol.SetURL(url))
}
func ATestClientAlt(t *testing.T, response string, request string) *ol.Client {
return ol.NewGQLClient(ol.SetAPIToken("x"), ol.SetMaxRetries(0), ol.SetURL(autopilot.RegisterEndpoint(fmt.Sprintf("/LOCAL_TESTING/%s__%s", response, request),
autopilot.FixtureResponse(fmt.Sprintf("%s_response.json", response)),
autopilot.GraphQLQueryFixtureValidation(t, fmt.Sprintf("%s_request.json", request)))))
}
func ATestClientSkipRequest(t *testing.T, endpoint string) *ol.Client {
return ol.NewGQLClient(ol.SetAPIToken("x"), ol.SetMaxRetries(0), ol.SetURL(autopilot.RegisterEndpoint(fmt.Sprintf("/LOCAL_TESTING/%s", endpoint),
autopilot.FixtureResponse(fmt.Sprintf("%s_response.json", endpoint)),
autopilot.SkipRequestValidation())))
}
func TestClientQuery(t *testing.T) {
// Arrange
headers := map[string]string{"x": "x"}
request := `{
"query": "{account{id}}",
"variables":{}
}`
response := `{"data": {
"account": {
"id": "1234"
}
}}`
url := autopilot.RegisterEndpoint("/LOCAL_TESTING/account",
TemplatedResponse(response),
GraphQLQueryTemplatedValidation(t, request))
client := ol.NewGQLClient(
ol.SetAPIToken("x"),
ol.SetMaxRetries(0),
ol.SetURL(url),
ol.SetHeaders(headers),
ol.SetUserAgentExtra("x"),
ol.SetTimeout(0),
ol.SetAPIVisibility("internal"),
ol.SetPageSize(100))
var q struct {
Account struct {
Id ol.ID
}
}
var v map[string]interface{}
// Act
err := client.Query(&q, v)
// Assert
autopilot.Ok(t, err)
autopilot.Equals(t, "1234", string(q.Account.Id))
}