-
Notifications
You must be signed in to change notification settings - Fork 4
/
client_test.go
473 lines (396 loc) · 11.8 KB
/
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
package sophos_test
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"github.com/esurdam/go-sophos"
)
var client *sophos.Client
var errOption = func(r *http.Request) error {
return fmt.Errorf("this is a fake error")
}
func setupTestCase(t *testing.T) func(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.Method == http.MethodPost {
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string]sophos.MethodMap{})
return
}
if strings.HasPrefix(r.URL.Path, "/api/definitions/") {
json.NewEncoder(w).Encode(map[string]sophos.MethodMap{})
return
}
if r.URL.Path == "/api/errorjson" {
w.WriteHeader(http.StatusNotFound)
byt, _ := json.Marshal(sophos.Errors{{
Oattrs: []string{
"class",
"type",
},
Class: "packetfilter",
Fatal: 1,
Format: "The %_O object requires %_d for the %_A attribute.",
Msgtype: "DATATYPE_OBJECT_ATTRIBUTE",
Name: "The group object requires a Perl array for the members list attribute.",
NeverHide: 0,
Type: "group",
}})
w.Write(byt)
return
}
if r.URL.Path == "/api/error" {
w.WriteHeader(http.StatusBadGateway)
return
}
json.NewEncoder(w).Encode(dnsMock{})
}))
sophos.DefaultHTTPClient = ts.Client()
clientF, err := sophos.New(ts.URL, sophos.WithAPIToken("abc"))
if err == nil {
client = clientF
}
if client == nil {
t.Error("errror setting up client, client is nil")
}
return func(t *testing.T) {
ts.Close()
}
}
func TestClient_Request(t *testing.T) {
td := setupTestCase(t)
defer td(t)
r, err := client.Request("GET", "/api/status/version", nil)
if err != nil {
t.Error(err)
}
if r.Header.Get(sophos.Authorization) == "" {
t.Error(errors.New("authorization is empty"))
}
wanted := fmt.Sprintf("%s/api/status/version", client.Endpoint())
if r.URL.String() != wanted {
t.Error(fmt.Errorf("incorrect URL: wanted %s, got %s", wanted, r.URL.String()))
}
r, err = client.Request("é", "/api/status/version", nil)
if err == nil {
t.Error(fmt.Errorf("request should have errored"))
}
}
func TestClient_Ping(t *testing.T) {
td := setupTestCase(t)
defer td(t)
if _, err := client.Ping(errOption); err == nil {
t.Error("error should not be nil with errOption")
}
if _, err := client.Ping(); err != nil {
t.Error(err)
}
}
func TestClient_Delete(t *testing.T) {
td := setupTestCase(t)
defer td(t)
r, err := client.Delete("/api", errOption)
if err == nil {
t.Error("error should not be nil with errOption")
}
if r.Request.Method != http.MethodDelete {
t.Error("method should be DELETE")
}
}
func TestClient_GetObject(t *testing.T) {
td := setupTestCase(t)
defer td(t)
var dns dnsMock
err := client.GetObject(&dns)
if err != nil {
t.Error("error should be nil", err.Error())
}
if err := client.GetObject(&dns, errOption); err == nil {
t.Error("error should not be nil with errOption")
}
var d dhcpServerMock
err = client.GetObject(&d)
if err == nil {
t.Error("type should require ref")
}
}
func TestClient_PostObject(t *testing.T) {
td := setupTestCase(t)
defer td(t)
var d = dhcpServerMock{Reference: "abc"}
err := client.PostObject(&d)
if err != nil {
t.Error("error should be nil", err.Error())
}
}
func TestClient_DeleteObject(t *testing.T) {
td := setupTestCase(t)
defer td(t)
var d = dhcpServerMock{Reference: "abc"}
err := client.DeleteObject(&d)
if err != nil {
t.Error("error should be nil", err.Error())
}
d = dhcpServerMock{Reference: ""}
err = client.DeleteObject(&d)
if err == nil {
t.Error("type should require ref")
}
}
func TestClient_PatchObject(t *testing.T) {
td := setupTestCase(t)
defer td(t)
var d = dhcpServerMock{Reference: "abc"}
err := client.PatchObject(&d)
if err != nil {
t.Error("error should be nil", err.Error())
}
d = dhcpServerMock{}
err = client.PatchObject(&d)
if err == nil {
t.Error("type should require ref")
}
}
func TestClient_PutObject(t *testing.T) {
td := setupTestCase(t)
defer td(t)
var d = dhcpServerMock{Reference: "abc"}
err := client.PutObject(&d)
if err != nil {
t.Error("error should be nil", err.Error())
}
d = dhcpServerMock{}
err = client.PutObject(&d)
if err == nil {
t.Error("type should require ref")
}
}
func TestClient_Get(t *testing.T) {
td := setupTestCase(t)
defer td(t)
r, err := client.Get("/api", errOption)
if err == nil {
t.Error("error should not be nil with errOption")
}
if r.Request.Method != http.MethodGet {
t.Error("method should be GET")
}
}
func TestClient_Put(t *testing.T) {
td := setupTestCase(t)
defer td(t)
r, err := client.Put("/api", nil, errOption)
if err == nil {
t.Error("error should not be nil with errOption")
}
if r.Request.Method != http.MethodPut {
t.Error("method should be PUT")
}
}
func TestClient_Post(t *testing.T) {
td := setupTestCase(t)
defer td(t)
r, err := client.Post("/api", nil, errOption)
if err == nil {
t.Error("error should not be nil with errOption")
}
if r.Request.Method != http.MethodPost {
t.Error("method should be DELETE")
}
}
func TestClient_Patch(t *testing.T) {
td := setupTestCase(t)
defer td(t)
r, err := client.Patch("/api", nil, errOption)
if err == nil {
t.Error("error should not be nil with errOption")
}
if r.Request.Method != http.MethodPatch {
t.Error("method should be DELETE")
}
}
func TestNew(t *testing.T) {
type args struct {
endpoint string
opts []sophos.Option
}
tests := []struct {
name string
args args
want string
wantErr bool
}{
{"testNewNoEndpoint", args{endpoint: ""}, "", true},
{"testNewEndpointNoHttp", args{endpoint: "boom.org"}, "https://boom.org", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := sophos.New(tt.args.endpoint, tt.args.opts...)
if (err != nil) != tt.wantErr {
t.Errorf("New() error = %v, wantErr %v", err, tt.wantErr)
return
}
if tt.want == "" {
return
}
if !reflect.DeepEqual(got.Endpoint(), tt.want) {
t.Errorf("New() = %v, want %v", got.Endpoint(), tt.want)
}
})
}
}
type faceClient struct{}
func (faceClient) Do(req *http.Request) (resp *http.Response, err error) {
return nil, errors.New("should error")
}
func TestClient_Do(t *testing.T) {
td := setupTestCase(t)
defer td(t)
_, err := client.Do("é", "/api", nil)
if err == nil {
t.Error("should have error since bad method")
}
_, err = client.Do("GET", "/api", nil, errOption)
if err == nil {
t.Error("should have error since bad errOption")
}
_, err = client.Do("GET", "/api/error", nil)
if err == nil {
t.Error("should have error due to bad response code")
}
sophos.DefaultHTTPClient = faceClient{}
_, err = client.Do("GET", "/api/error", nil)
if err == nil {
t.Error("should have error since bad client")
}
}
func TestClient_GetUsedBy(t *testing.T) {
td := setupTestCase(t)
defer td(t)
var dhcp dhcpServerMock
_, err := client.GetUsedBy(&dhcp)
if err == nil {
t.Error("should have error since no REF")
}
dhcp.Reference = "REF_abc"
_, err = client.GetUsedBy(&dhcp)
if err != nil {
t.Error("should not have error since has REF")
}
dhcp.Reference = "REF_abc"
_, err = client.GetUsedBy(&dhcp, errOption)
if err == nil {
t.Error("should have error since errOption")
}
}
// dnsMock is a generated struct representing the Sophos dnsMock Endpoint
// GET /api/nodes/dns
type dnsMock struct {
AllowedNetworks []string `json:"allowed_networks"`
Axfr []interface{} `json:"axfr"`
Dnssec int64 `json:"dnssec"`
Email string `json:"email"`
EmptyZones string `json:"empty_zones"`
FwdDynamic int64 `json:"fwd_dynamic"`
FwdStatic []string `json:"fwd_static"`
RecheckInterval int64 `json:"recheck_interval"`
Routes []string `json:"routes"`
}
var defsDns = map[string]sophos.RestObject{}
// RestObjects implements the sophos.Node interface and returns a map of dnsMock's Objects
func (dnsMock) RestObjects() map[string]sophos.RestObject { return defsDns }
// GetPath implements sophos.RestGetter
func (*dnsMock) GetPath() string { return "/api/nodes/dns" }
// RefRequired implements sophos.RestGetter
func (*dnsMock) RefRequired() (string, bool) { return "", false }
var defDns = &sophos.Definition{Description: "dns", Name: "dns", Link: "/api/definitions/dns"}
// Definition returns the /api/definitions struct of dnsMock
func (dnsMock) Definition() sophos.Definition { return *defDns }
// ApiRoutes returns all known dnsMock Paths
func (dnsMock) ApiRoutes() []string {
return []string{
"/api/objects/dns/axfr/",
"/api/objects/dns/axfr/{ref}",
"/api/objects/dns/axfr/{ref}/usedby",
"/api/objects/dns/group/",
"/api/objects/dns/group/{ref}",
"/api/objects/dns/group/{ref}/usedby",
"/api/objects/dns/route/",
"/api/objects/dns/route/{ref}",
"/api/objects/dns/route/{ref}/usedby",
}
}
// References returns the dnsMock's references. These strings serve no purpose other than to demonstrate which
// Reference keys are used for this Endpoint
func (dnsMock) References() []string {
return []string{
"REF_DnsAxfr",
"REF_DnsGroup",
"REF_DnsRoute",
}
}
// dhcpServerMock is a generated Sophos object
type dhcpServerMock struct {
Locked string `json:"_locked"`
Reference string `json:"_ref"`
ObjectType string `json:"_type"`
Address string `json:"address"`
Comment string `json:"comment"`
Custom string `json:"custom"`
DefaultGateway string `json:"default_gateway"`
DenyUnknown bool `json:"deny_unknown"`
DNS1 string `json:"dns1"`
DNS2 string `json:"dns2"`
Domain string `json:"domain"`
Interface string `json:"interface"`
LeaseTime int64 `json:"lease_time"`
Mappings []string `json:"mappings"`
Name string `json:"name"`
Netmask int64 `json:"netmask"`
ProxyAutoconfig bool `json:"proxy_autoconfig"`
RangeEnd string `json:"range_end"`
RangeStart string `json:"range_start"`
RelayMode bool `json:"relay_mode"`
Status bool `json:"status"`
Wins string `json:"wins"`
WinsNodeType string `json:"wins_node_type"`
}
// GetPath implements sophos.RestObject and returns the DhcpServers GET path
// Returns all available server types
func (d *dhcpServerMock) GetPath() string {
return fmt.Sprintf("/api/objects/dhcp/server/%s", d.Reference)
}
// RefRequired implements sophos.RestObject
func (d *dhcpServerMock) RefRequired() (string, bool) { return d.Reference, true }
// DeletePath implements sophos.RestObject and returns the dhcpServerMock DELETE path
// Creates or updates the complete object server
func (*dhcpServerMock) DeletePath(ref string) string {
return fmt.Sprintf("/api/objects/dhcp/server/%s", ref)
}
// PatchPath implements sophos.RestObject and returns the dhcpServerMock PATCH path
// Changes to parts of the object server types
func (*dhcpServerMock) PatchPath(ref string) string {
return fmt.Sprintf("/api/objects/dhcp/server/%s", ref)
}
// PostPath implements sophos.RestObject and returns the dhcpServerMock POST path
// Create a new dhcp/server object
func (*dhcpServerMock) PostPath() string {
return "/api/objects/dhcp/server/"
}
// PutPath implements sophos.RestObject and returns the dhcpServerMock PUT path
// Creates or updates the complete object server
func (*dhcpServerMock) PutPath(ref string) string {
return fmt.Sprintf("/api/objects/dhcp/server/%s", ref)
}
// UsedByPath implements sophos.Object
// Returns the objects and the nodes that use the object with the given ref
func (*dhcpServerMock) UsedByPath(ref string) string {
return fmt.Sprintf("/api/objects/dhcp/server/%s/usedby", ref)
}
// GetType implements sophos.Object
func (d *dhcpServerMock) GetType() string { return d.ObjectType }