-
Notifications
You must be signed in to change notification settings - Fork 0
/
steps.go
257 lines (204 loc) · 7.85 KB
/
steps.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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package servicetest
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"github.com/antchfx/jsonquery"
"github.com/cucumber/godog"
. "github.com/onsi/gomega"
"github.com/rs/zerolog/log"
"os"
"strings"
"time"
)
type Step struct {
Expression string
Handler interface{}
}
func (s *ServerTestFeature) InitializeScenario(ctx *godog.ScenarioContext) {
ctx.Before(func(ctx context.Context, sc *godog.Scenario) (context.Context, error) {
s.Reset(sc)
return ctx, nil
})
ctx.Step(`^I send "(GET|POST|DELETE)" request to "([^"]*)"$`, s.SendRequest)
ctx.Step(`^I send "(PATCH|POST|PUT|DELETE)" request to "([^"]*)" with data$`, s.SendRequestWithData)
ctx.Step(`^I send "([^"]*)" gql request to the "([^"]*)" endpoint "([^"]*)" with the variables$`, s.SendGQLRequestWithVariables)
ctx.Step(`^the response code should be "([^"]*)"$`, s.TheResponseCodeShouldBe)
ctx.Step(`^the response code should be (\d+)$`, s.TheResponseCodeShouldBe)
ctx.Step(`^the response should match json$`, s.TheResponseShouldMatchJSON)
ctx.Step(`^the response should contain$`, s.TheResponseShouldContain)
ctx.Step(`^the response should contain a "([^"]*)" header with value "([^"]*)"$`, s.TheResponseHeadersShouldContain)
ctx.Step(`^the response should contain a "([^"]*)"$`, s.TheResponseShouldContainA)
ctx.Step(`^the response should not contain a "([^"]*)"$`, s.TheResponseShouldNotContainA)
ctx.Step(`^I extract the "([^"]*)" from the response$`, s.ExtractValueFromResponse)
ctx.Step(`^I have a file named "([^"]*)" in the "([^"]*)" directory$`, s.SetFilePath)
ctx.Step(`^I have a file named "([^"]*)" in the "([^"]*)" directory that should be sent in the request with key "([^"]*)"$`, s.FileToSendInRequest)
ctx.Step(`^I wait for "([^"]*)" seconds$`, s.WaitForSeconds)
ctx.Step(`^the response should contain "([^"]*)" set to "([^"]*)"$`, s.TheResponseShouldContainSetTo)
ctx.Step(`^it should not contain "([^"]*)" for the path "([^"]*)"$`, s.ShouldNotContainForJsonQueryPath)
ctx.Step(`^the response should contain a "([^"]*)" that is not null$`, s.TheResponseShouldContainAThatIsNotNull)
}
func (s *ServerTestFeature) SendRequestWithData(method string, endpoint string, body *godog.DocString) {
s.MakeRequest(method, endpoint, body)
}
func (s *ServerTestFeature) SendGQLRequestWithVariables(gqlMethodName string, serviceName string, endpoint string, variableBody *godog.DocString) error {
s.GraphQLOperation = gqlMethodName
if s.DirectoryFilePath == "" {
return errors.New("cannot read graphql operation from file")
}
fileContent, err := os.ReadFile(s.DirectoryFilePath)
if err != nil {
return err
}
getVariables := func(variableBody *godog.DocString) (map[string]interface{}, error) {
if variableBody == nil {
return nil, nil
}
variables := map[string]interface{}{}
if s.GraphQLResponse == nil {
s.GraphQLResponse = make(map[string]interface{})
}
// loop through graph response and replace all the string that matches $key
for k, v := range s.GraphQLResponse {
variableBody.Content = strings.ReplaceAll(variableBody.Content, fmt.Sprintf("$%s", k), fmt.Sprintf("%v", v))
}
variableBody.Content = string(s.performSubstitutions([]byte(variableBody.Content)))
log.Debug().Msgf("GraphQL variables body: %s", variableBody.Content)
if err = json.Unmarshal([]byte(variableBody.Content), &variables); err != nil {
return nil, err
}
return variables, nil
}
variables, err := getVariables(variableBody)
if err != nil {
return err
}
graphqlRequest := struct {
OperationName string `json:"operationName"`
Query string `json:"query"`
Variables map[string]any `json:"variables,omitempty"`
}{
OperationName: gqlMethodName,
Query: string(fileContent),
Variables: variables,
}
var buf bytes.Buffer
if err = json.NewEncoder(&buf).Encode(graphqlRequest); err != nil {
return err
}
return s.makeGraphQLRequest(endpoint, serviceName, buf.String())
}
func (s *ServerTestFeature) ExtractValueFromResponse(keyName string) error {
doc, err := jsonquery.Parse(strings.NewReader(s.ResponseString))
if err != nil {
return err
}
extractedValue := jsonquery.FindOne(doc, fmt.Sprintf("//%s/%s", s.GraphQLOperation, keyName))
if extractedValue == nil {
return fmt.Errorf("key %s not found in response", keyName)
}
s.GraphQLResponse[keyName] = extractedValue.FirstChild.Data
return nil
}
func (s *ServerTestFeature) ShouldNotContainForJsonQueryPath(value, jsonQueryPath string) error {
doc, err := jsonquery.Parse(strings.NewReader(s.ResponseString))
if err != nil {
return err
}
jsonQueryPath = strings.ReplaceAll(jsonQueryPath, ".", "/")
extractedValue := jsonquery.FindOne(doc, fmt.Sprintf("//%s", jsonQueryPath))
if extractedValue == nil {
return fmt.Errorf("json query '%s' not found in response", jsonQueryPath)
}
dataFound := false
for _, child := range extractedValue.ChildNodes() {
if child.Value() == value {
dataFound = true
break
}
}
if dataFound {
return fmt.Errorf("value %s found in json query path %s", value, jsonQueryPath)
}
return nil
}
func (s *ServerTestFeature) TheResponseShouldContainAThatIsNotNull(jsonQueryPath string) error {
doc, err := jsonquery.Parse(strings.NewReader(s.ResponseString))
if err != nil {
return err
}
jsonQueryPath = strings.ReplaceAll(jsonQueryPath, ".", "/")
extractedValue := jsonquery.FindOne(doc, fmt.Sprintf("//%s", jsonQueryPath))
if extractedValue == nil {
return fmt.Errorf("json query '%s' not found in response", jsonQueryPath)
}
dataFound := false
for _, child := range extractedValue.ChildNodes() {
if child.Value() != nil {
dataFound = true
break
}
}
if dataFound {
return fmt.Errorf("the json query path %s contains s null value", jsonQueryPath)
}
return nil
}
func (s *ServerTestFeature) SendRequest(method, endpoint string) {
s.MakeRequest(method, endpoint, nil)
}
func (s *ServerTestFeature) TheResponseCodeShouldBe(statusCode int) error {
if s.StatusCode != statusCode {
return fmt.Errorf("expected response code %d, but got %d", statusCode, s.StatusCode)
}
return nil
}
func (s *ServerTestFeature) TheResponseShouldContain(body *godog.DocString) {
actual := TrimString(s.ResponseString)
expected := TrimString(body.Content)
Expect(actual).To(ContainSubstring(expected))
}
func (s *ServerTestFeature) TheResponseHeadersShouldContain(key, value string) {
headerValue := s.Response.Header.Get(key)
Expect(headerValue).To(ContainSubstring(value))
}
func (s *ServerTestFeature) TheResponseShouldContainA(key string) {
key = string(s.performSubstitutions([]byte(key)))
actual := TrimString(s.ResponseString)
Expect(actual).To(ContainSubstring(key))
}
func (s *ServerTestFeature) TheResponseShouldNotContainA(key string) {
actual := TrimString(s.ResponseString)
Expect(actual).NotTo(ContainSubstring(key))
}
func (s *ServerTestFeature) TheResponseShouldMatchJSON(body *godog.DocString) {
actual := s.ResponseString
expected := body.Content
Expect(actual).To(MatchJSON(expected))
}
func (s *ServerTestFeature) WaitForSeconds(seconds int) {
time.Sleep(time.Duration(seconds) * time.Second)
}
func (s *ServerTestFeature) TheResponseShouldContainSetTo(property, value string) {
Expect(s.ResponseString).To(ContainSubstring(fmt.Sprintf("\"%s\":\"%s\"", property, value)))
}
func (s *ServerTestFeature) SetFilePath(filename string, directory string) error {
if directory == "" && filename == "" {
return fmt.Errorf("directory and filename cannot be empty")
}
s.DirectoryFilePath = fmt.Sprintf("./%s/%s", directory, filename)
return nil
}
func (s *ServerTestFeature) FileToSendInRequest(filename, directory, key string) error {
if directory == "" && filename == "" {
return fmt.Errorf("directory and filename cannot be empty")
}
s.SendFileKey = key
s.SendFile = fmt.Sprintf("./%s/%s", directory, filename)
if _, err := os.Stat(s.SendFile); os.IsNotExist(err) {
return fmt.Errorf("file %s does not exist", s.SendFile)
}
return nil
}