-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathservicenow_client_test.go
271 lines (215 loc) · 7.72 KB
/
servicenow_client_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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
package servicenowsdkgo
import (
"context"
"encoding/json"
"io"
"net/http"
"net/url"
"reflect"
"strings"
"testing"
"github.com/michaeldcanady/servicenow-sdk-go/core"
"github.com/michaeldcanady/servicenow-sdk-go/credentials"
"github.com/michaeldcanady/servicenow-sdk-go/internal"
"github.com/mozillazg/go-httpheader"
"github.com/stretchr/testify/assert"
)
type test[T any] struct {
Title string
// Setup to make needed modifications for a specific test
Setup func()
// Cleanup to undo changes do to reusable items
Cleanup func()
Input interface{}
Expected T
expectedErr error
}
var (
sharedUsernameAndPasswordCred = credentials.NewUsernamePasswordCredential("username", "password")
)
type MockRequestInformation struct {
Headers http.Header
}
func (rI *MockRequestInformation) AddRequestOptions(options []core.RequestOption) {
}
func (rI *MockRequestInformation) GetRequestOptions() []core.RequestOption {
return []core.RequestOption{}
}
func (rI *MockRequestInformation) SetStreamContent(content []byte) {
}
func (rI *MockRequestInformation) AddQueryParameters(source interface{}) error {
return nil
}
func (rI *MockRequestInformation) SetUri(url *url.URL) { //nolint:stylecheck
}
func (rI *MockRequestInformation) Url() (string, error) { //nolint:stylecheck
return "https://www.example.com", nil
}
func (rI *MockRequestInformation) ToRequest() (*http.Request, error) {
return http.NewRequest("GET", "https://www.example.com", nil)
}
func (rI *MockRequestInformation) ToRequestWithContext(ctx context.Context) (*http.Request, error) {
request, err := http.NewRequestWithContext(ctx, "GET", "https://www.example.com", nil)
if err != nil {
return nil, err
}
request.Header = rI.Headers
return request, nil
}
func (rI *MockRequestInformation) AddHeaders(rawHeaders interface{}) error {
var headers http.Header
var err error
val := reflect.ValueOf(rawHeaders)
if val.Kind() == reflect.Struct {
// use the httpheader.Encode function from the httpheader package
// to encode the pointer value into an http.Header map
headers, err = httpheader.Encode(rawHeaders)
if err != nil {
return err
}
} else if val.Type() == reflect.TypeOf(http.Header{}) {
// if the value is already an http.Header map, just assign it to headers
headers = rawHeaders.(http.Header)
} else {
// otherwise, return an error
return core.ErrInvalidHeaderType
}
// iterate over the headers map and add each key-value pair to rI.Headers
for key, values := range headers {
for _, value := range values {
rI.Headers.Add(key, value)
}
}
return nil
}
func TestNewClient(t *testing.T) {
cred := credentials.NewUsernamePasswordCredential("username", "password")
client := NewServiceNowClient(cred, "instance")
assert.NotNil(t, client)
}
func TestNewClient2(t *testing.T) {
authProvider, _ := internal.NewBaseAuthorizationProvider(sharedUsernameAndPasswordCred)
tests := []test[*ServiceNowClient]{
{
Title: "Valid",
Input: []interface{}{"instance", sharedUsernameAndPasswordCred},
Expected: &ServiceNowClient{
Credential: sharedUsernameAndPasswordCred,
authProvider: authProvider,
BaseUrl: "https://instance.service-now.com/api",
Session: http.Client{},
},
expectedErr: nil,
},
{
Title: "Nil Credential",
Input: []interface{}{"instance", (*credentials.UsernamePasswordCredential)(nil)},
Expected: nil,
expectedErr: internal.ErrNilCredential,
},
}
for _, test := range tests {
t.Run(test.Title, func(t *testing.T) {
values := test.Input.([]interface{})
instance := values[0].(string)
cred := values[1].(core.Credential)
client, err := NewServiceNowClient2(cred, instance)
if test.Expected != nil {
assert.Equal(t, test.Expected.authProvider, client.authProvider)
assert.Equal(t, test.Expected.Credential, client.Credential)
assert.Equal(t, test.Expected.BaseUrl, client.BaseUrl)
assert.Equal(t, test.Expected.Session, client.Session)
} else {
assert.Equal(t, test.Expected, client)
}
assert.Equal(t, test.expectedErr, err)
})
}
}
func TestClientURL(t *testing.T) {
cred := credentials.NewUsernamePasswordCredential("username", "password")
client := NewServiceNowClient(cred, "instance")
assert.Equal(t, client.BaseUrl, "https://instance.service-now.com/api")
}
func TestClientNow(t *testing.T) {
cred := credentials.NewUsernamePasswordCredential("username", "password")
client := NewServiceNowClient(cred, "instance")
nowBuilder := client.Now()
assert.IsType(t, &NowRequestBuilder{}, nowBuilder)
assert.Equal(t, client.BaseUrl+"/now", nowBuilder.PathParameters["baseurl"])
assert.Equal(t, client, nowBuilder.Client)
}
func TestClientToRequest(t *testing.T) {
requestInfo := &MockRequestInformation{
Headers: http.Header{},
}
cred := credentials.NewUsernamePasswordCredential("username", "password")
client := NewServiceNowClient(cred, "instance")
request, err := client.toRequest(requestInfo)
if err != nil {
t.Error(err)
}
expected := &url.URL{Scheme: "https", Opaque: "", User: (*url.Userinfo)(nil), Host: "www.example.com", Path: "", RawPath: "", OmitHost: false, ForceQuery: false, RawQuery: "", Fragment: "", RawFragment: ""}
expectedContentTypeHeader := "application/json"
expectedAcceptHeader := "application/json"
expectedAuthorizationHeader := "Basic dXNlcm5hbWU6cGFzc3dvcmQ="
assert.Equal(t, expected, request.URL)
assert.Equal(t, expectedContentTypeHeader, request.Header.Get("Content-Type"))
assert.Equal(t, expectedAcceptHeader, request.Header.Get("Accept"))
assert.Equal(t, expectedAuthorizationHeader, request.Header.Get("Authorization"))
_, err = client.toRequest(nil)
assert.Error(t, ErrNilRequestInfo, err)
}
func TestClientUnmarshallError(t *testing.T) {
cred := credentials.NewUsernamePasswordCredential("username", "password")
client := NewServiceNowClient(cred, "instance")
properErr := core.ServiceNowError{
Exception: core.Exception{
Detail: "Resource not found",
Message: "Resource not found",
},
Status: "404",
}
jsonBytes, err := json.Marshal(properErr)
if err != nil {
t.Error(err)
}
errorResp := &http.Response{
StatusCode: 404,
Body: io.NopCloser(strings.NewReader(string(jsonBytes))),
}
err = client.unmarshallError(errorResp)
assert.IsType(t, &core.ServiceNowError{}, err)
assert.Equal(t, &properErr, err)
errorResp = &http.Response{
StatusCode: 404,
Body: io.NopCloser(strings.NewReader("bad response")),
}
err = client.unmarshallError(errorResp)
assert.IsType(t, &json.SyntaxError{}, err)
}
func TestClientToRequestWithContext(t *testing.T) {
requestInfo := &MockRequestInformation{
Headers: http.Header{},
}
cred := credentials.NewUsernamePasswordCredential("username", "password")
ctx := context.TODO()
client := NewServiceNowClient(cred, "instance")
request, err := client.toRequestWithContext(ctx, requestInfo) //nolint:all
if err != nil {
t.Error(err)
}
expected := &url.URL{Scheme: "https", Opaque: "", User: (*url.Userinfo)(nil), Host: "www.example.com", Path: "", RawPath: "", OmitHost: false, ForceQuery: false, RawQuery: "", Fragment: "", RawFragment: ""}
expectedContentTypeHeader := "application/json"
expectedAcceptHeader := "application/json"
expectedAuthorizationHeader := "Basic dXNlcm5hbWU6cGFzc3dvcmQ="
assert.Equal(t, expected, request.URL)
assert.Equal(t, expectedContentTypeHeader, request.Header.Get("Content-Type"))
assert.Equal(t, expectedAcceptHeader, request.Header.Get("Accept"))
assert.Equal(t, expectedAuthorizationHeader, request.Header.Get("Authorization"))
assert.Equal(t, ctx, request.Context())
_, err = client.toRequestWithContext(context.TODO(), nil)
assert.Error(t, ErrNilRequestInfo, err)
_, err = client.toRequestWithContext(nil, requestInfo) //nolint:all
assert.Error(t, ErrNilContext, err)
}