forked from aristanetworks/goeapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_test.go
633 lines (583 loc) · 17.3 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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
//
// Copyright (c) 2015, Arista Networks, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Arista Networks nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARISTA NETWORKS
// BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
// IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
package goeapi
import (
"fmt"
"os"
"os/user"
"regexp"
"sort"
"strings"
"testing"
)
func TestConfigExpandPath_UnitTest(t *testing.T) {
usr, _ := user.Current()
homedir := usr.HomeDir
tests := [...]struct {
in string
want string
}{
{"/home/usera/.eapi.conf", "/home/usera/.eapi.conf"},
{"~/.eapi.conf", homedir + "/.eapi.conf"},
{"./.eapi.conf", "./.eapi.conf"},
{"", ""},
{"a", "a"},
{"aa", "aa"},
{"~/", homedir},
{"~", homedir},
}
for _, tt := range tests {
got, _ := expandPath(tt.in)
if got != tt.want {
t.Fatalf("expandPath() got %q; want %q", got, tt.want)
}
}
}
func TestConfigNilEapiConfig_UnitTest(t *testing.T) {
config := NewEapiConfig()
config = nil
if ret := config.Connections(); ret != nil {
t.Fatalf("got %#v expected nil", config)
}
}
func TestConfigEapiConfigNilFile_UnitTest(t *testing.T) {
currEnv := os.Getenv("EAPI_CONF")
os.Setenv("EAPI_CONF", GetFixture("dontexist.conf"))
config := NewEapiConfig()
if len(config.Connections()) != 1 {
t.Fatalf("got %d expected 1", len(config.Connections()))
}
if currEnv != "" {
os.Setenv("EAPI_CONF", currEnv)
} else {
os.Unsetenv("EAPI_CONF")
}
}
func TestConfigInitInvalid_UnitTest(t *testing.T) {
config := NewEapiConfigFile(GetFixture("invalid.conf"))
if len(config.Connections()) != 1 {
t.Fatalf("got %d expected 1", len(config.Connections()))
}
}
func TestConfigReadInvalid_UnitTest(t *testing.T) {
config := NewEapiConfig()
if err := config.Read(GetFixture("invalid.conf")); err == nil {
t.Fatalf("expected failure")
}
}
func TestConfigReadValid_UnitTest(t *testing.T) {
config := NewEapiConfig()
if err := config.Read(GetFixture("eapi.conf")); err != nil {
t.Fatalf("expected failure")
}
}
func TestConfigLoadConfigFilename_UnitTest(t *testing.T) {
currEnv := os.Getenv("EAPI_CONF")
if currEnv != "" {
fmt.Printf("UNSETTING EAPI_CONF\n")
os.Unsetenv("EAPI_CONF")
}
if os.Getenv("EAPI_CONF") != "" {
t.Fatalf("Unsetenv failed")
}
LoadConfig(GetFixture("eapi.conf"))
section := ConfigFor("test1")
if section["host"] != "192.168.1.16" ||
section["username"] != "eapi" ||
section["password"] != "password" {
t.Fatalf("ConfigFor failed: %q", section)
}
if currEnv != "" {
os.Setenv("EAPI_CONF", currEnv)
} else {
os.Unsetenv("EAPI_CONF")
}
}
func TestConfigLoadConfigWithEnv_UnitTest(t *testing.T) {
currEnv := os.Getenv("EAPI_CONF")
os.Setenv("EAPI_CONF", GetFixture("eapi.conf"))
LoadConfig(RandomString(4, 9))
section := ConfigFor("test1")
if section["host"] != "192.168.1.16" ||
section["username"] != "eapi" ||
section["password"] != "password" {
t.Fatalf("ConfigFor failed: %q", section)
}
if currEnv != "" {
os.Setenv("EAPI_CONF", currEnv)
} else {
os.Unsetenv("EAPI_CONF")
}
}
func TestConfigLoadConfigCheckSections_UnitTest(t *testing.T) {
LoadConfig(GetFixture("eapi.conf"))
if len(configGlobal.File) != 3 {
t.Fatalf("Incorrect number of sections found: %d", len(configGlobal.File))
}
}
func TestConfigLoadConfigDefaultConnection_UnitTest(t *testing.T) {
LoadConfig(GetFixture("invalid.conf"))
if len(configGlobal.File) != 1 {
t.Fatalf("Incorrect number of sections found: %d", len(configGlobal.File))
}
}
func TestConfigLoadConfigProperty_UnitTest(t *testing.T) {
LoadConfig(GetFixture("eapi.conf"))
validConnections := []string{"test1", "test2", "localhost"}
sort.Strings(validConnections)
connections := Connections()
sort.Strings(connections)
if len(connections) == len(validConnections) {
for idx, val := range connections {
if validConnections[idx] != val {
t.Fatalf("Got %s expected %s", val, validConnections[idx])
}
}
return
}
t.Fatalf("Incorrect length: got %d expected: %d", len(connections), len(validConnections))
}
func TestConfigLoadConfigReplaceHostWithName_UnitTest(t *testing.T) {
LoadConfig(GetFixture("nohost.conf"))
section := ConfigFor("test")
if section["host"] != "test" {
t.Fatalf("Got %s expected: test", section["host"])
}
}
// HACK. Reload dut.conf after the above test.
// Don't account for localhost in config since we don't support yet.
func TestConfigLoadRest_UnitTest(t *testing.T) {
duts = nil
LoadConfig(GetFixture("dut.conf"))
conns := Connections()
for _, name := range conns {
if name != "localhost" {
node, _ := ConnectTo(name)
duts = append(duts, node)
}
}
}
func TestClientRunningConfig_UnitTest(t *testing.T) {
dummyNode.Refresh()
if config := dummyNode.RunningConfig(); config == "" {
t.Fatalf("No config returned")
}
if config := dummyNode.RunningConfig(); config == "" {
t.Fatalf("No config returned")
}
}
func TestClientStartupConfig_UnitTest(t *testing.T) {
dummyNode.Refresh()
if config := dummyNode.StartupConfig(); config == "" {
t.Fatalf("No config returned")
}
if config := dummyNode.StartupConfig(); config == "" {
t.Fatalf("No config returned")
}
}
func TestClientGetConfig_UnitTest(t *testing.T) {
tests := [...]struct {
config string
params string
rc bool
}{
{"running-config", "all", true},
{"startup-config", "", true},
{"bogus-config", "", false},
}
for idx, tt := range tests {
_, err := dummyNode.GetConfig(tt.config, tt.params)
if (err == nil) != tt.rc {
t.Fatalf("Test[%d] Expected %t in eval of (err == nil): err:%#v", idx, tt.rc, err)
}
}
}
func TestClientGetConfigConnectionError_UnitTest(t *testing.T) {
conn := dummyNode.GetConnection().(*DummyEapiConnection)
conn.setReturnError(true)
ret, err := dummyNode.GetConfig("running-config", "")
if ret != "" && err == nil {
t.Fatalf("Connection error didn't raise issue")
}
}
func TestClientGetSection_UnitTest(t *testing.T) {
tests := [...]struct {
reg string
config string
rc bool
}{
{`(?m)^interface Ethernet1$`, "running-config", true},
{`(?m)^interface Ethernet1$`, "", true},
{`(?m)^interface Ethernet1$`, "startup-config", true},
{`(?=>)^interface Ethernet1$`, "running-config", false},
{`(?m)^interface Ethernet1$`, "bogus-config", false},
{`(?m)^interface TokenRing1$`, "running-config", false},
}
for idx, tt := range tests {
_, err := dummyNode.GetSection(tt.reg, tt.config)
if (err == nil) != tt.rc {
t.Fatalf("Test[%d] Expected %t in eval of (err == nil): err:%#v", idx, tt.rc, err)
}
}
}
func TestClientGetSectionConnectionError_UnitTest(t *testing.T) {
conn := dummyNode.GetConnection().(*DummyEapiConnection)
conn.setReturnError(true)
ret, err := dummyNode.GetSection(`(?m)^interface Ethernet1$`, "startup-config")
if ret != "" && err == nil {
t.Fatalf("Connection error didn't raise issue")
}
}
func TestClientConfig_UnitTest(t *testing.T) {
cmds := []string{
"interface Ethernet1",
"no flowcontrol send",
"ip address 1.1.1.1/24",
"no shut",
}
dummyNode.SetAutoRefresh(true)
dummyNode.Config(cmds...)
commands := dummyConnection.GetCommands()[2:]
for idx, val := range commands {
if cmds[idx] != val {
t.Fatalf("Expected \"%q\" got \"%q\"", cmds, commands)
}
}
}
func TestClientEnable_UnitTest(t *testing.T) {
tests := [...]struct {
in []string
rc bool
}{
{[]string{"configure terminal"}, false},
{[]string{"configure terminal"}, false},
{[]string{" configure"}, false},
{[]string{"configure"}, false},
{[]string{"show running-config"}, true},
}
dummyNode.EnableAuthentication("root")
for idx, tt := range tests {
if _, got := dummyNode.Enable(tt.in); (got == nil) != tt.rc {
dummyNode.EnableAuthentication("")
t.Fatalf("Test[%d] Expected %t in eval of (err == nil)", idx, tt.rc)
}
}
dummyNode.EnableAuthentication("")
}
func TestClientEnableConnectionError_UnitTest(t *testing.T) {
conn := dummyNode.GetConnection().(*DummyEapiConnection)
conn.setReturnError(true)
cmds := []string{"show running-config"}
ret, err := dummyNode.Enable(cmds)
if ret != nil && err == nil {
t.Fatalf("Connection error didn't raise issue")
}
}
func TestClientPrependEnableSequence_UnitTest(t *testing.T) {
cmds := []string{
"show version",
"show arp",
"show interfaces",
}
dummyNode.EnableAuthentication("root")
got := dummyNode.prependEnableSequence(cmds)
if len(got) != len(cmds)+1 {
dummyNode.EnableAuthentication("")
t.Fatalf("Missing or extra entry in prepend: %#v", got)
}
cmd := got[0].(map[string]interface{})["cmd"]
passwd := got[0].(map[string]interface{})["input"]
if cmd != "enable" || passwd != "root" {
dummyNode.EnableAuthentication("")
t.Fatalf("Invalid Entry. Cmd:%s Passwd:%s Got:%#v", cmd, passwd, got[0])
}
dummyNode.EnableAuthentication("")
}
func TestClientPrependEnableSequenceInvalidParams_UnitTest(t *testing.T) {
cmds := []string{
"show version",
"show arp",
"show interfaces",
}
got := dummyNode.prependEnableSequence(cmds)
if len(got) != len(cmds)+1 {
dummyNode.EnableAuthentication("")
t.Fatalf("Missing or extra entry in prepend: %#v", got)
}
dummyNode.EnableAuthentication("")
}
func TestClientCmdsToInterface_UnitTest(t *testing.T) {
cmds := []string{
"show version",
"show arp",
"show interfaces",
}
got := cmdsToInterface(cmds)
if len(got) != len(cmds) {
t.Fatalf("Missing or extra entry in Conversion: %#v", got)
}
if got := cmdsToInterface(nil); got != nil {
t.Fatalf("Should return nil on nil being passed")
}
if got := cmdsToInterface([]string{}); got != nil {
t.Fatalf("Should return nil on empty list being passed")
}
}
func TestClientEnableSingleResult_SystemTest(t *testing.T) {
for _, dut := range duts {
cmds := []string{
"show version",
}
ret, _ := dut.runCommands(cmds, "json")
if len(ret.Result) != 1 {
t.Fatalf("sizes do not match Result[%d] != 1\n", len(ret.Result))
}
}
}
func TestClientEnableMultipleResult_SystemTest(t *testing.T) {
for _, dut := range duts {
var cmds []string
for i := 0; i < RandomInt(10, 200); i++ {
cmds = append(cmds, "show version")
}
ret, _ := dut.runCommands(cmds, "json")
if len(ret.Result) != len(cmds) {
t.Fatalf("sizes do not match Result[%d] != cmds[%d]\n", len(ret.Result), len(cmds))
}
}
}
func TestClientEnableMultiRequests_SystemTest(t *testing.T) {
for _, dut := range duts {
cmds := []string{
"show version",
}
for i := 0; i < RandomInt(10, 200); i++ {
ret, _ := dut.runCommands(cmds, "json")
if len(ret.Result) != 1 {
t.Fatalf("sizes do not match Result[%d] != 1\n", len(ret.Result))
}
}
}
}
func TestClientConfigSingle_SystemTest(t *testing.T) {
for _, dut := range duts {
cmds := []string{
"hostname " + RandomString(5, 50),
}
if ok := dut.Config(cmds...); !ok {
t.Fatalf("Config failure\n")
}
name := strings.Split(cmds[len(cmds)-1], " ")[1]
ret, _ := dut.runCommands([]string{"show hostname"}, "json")
if ret.Result[0]["hostname"] != name {
t.Fatalf("Expecting %s got %s\n", name, ret.Result[0]["hostname"])
}
}
}
func TestClientConfigMultiple_SystemTest(t *testing.T) {
for _, dut := range duts {
var cmds []string
for i := 0; i < RandomInt(10, 200); i++ {
cmds = append(cmds, "hostname "+RandomString(5, 50))
}
if ok := dut.Config(cmds...); !ok {
t.Fatal("Config failure\n")
}
// just check last
name := strings.Split(cmds[len(cmds)-1], " ")[1]
ret, _ := dut.runCommands([]string{"show hostname"}, "json")
if ret.Result[0]["hostname"] != name {
t.Fatalf("Expecting %s got %s\n", name, ret.Result[0]["hostname"])
}
}
}
func TestClientConnectInvalidTransport_UnitTest(t *testing.T) {
if _, err := Connect("invalid", "hostname", "username", "passwd", 10); err == nil {
t.Fatalf("No error seen for invalid transport type")
}
}
func TestClientNodeEnablePasswd_UnitTest(t *testing.T) {
node := &Node{}
node.EnableAuthentication("root")
if node.enablePasswd != "root" {
t.Fatal("EnableAuthentication failed to set")
}
node.EnableAuthentication("")
if node.enablePasswd != "" {
t.Fatal("EnableAuthentication failed to set")
}
}
func TestClientNodeAutoRefresh_UnitTest(t *testing.T) {
for _, dut := range duts {
dut.SetAutoRefresh(true)
if dut.autoRefresh == false {
t.Fatal("SetAutoRefresh(true) failed to set")
}
dut.SetAutoRefresh(false)
if dut.autoRefresh == true {
t.Fatal("SetAutoRefresh(false) failed to set")
}
}
}
func TestClientNodeGetRunningConfig_SystemTest(t *testing.T) {
re := regexp.MustCompile(`^!\s+Command: show running-config`)
for _, dut := range duts {
dut.Refresh()
config := dut.RunningConfig()
if found := re.MatchString(config); !found {
t.Fatal("Failed to obtain running-config")
}
config = dut.RunningConfig()
if found := re.MatchString(config); !found {
t.Fatal("Failed to obtain non-cached running-config")
}
}
}
func TestClientNodeGetStartupConfig_SystemTest(t *testing.T) {
re := regexp.MustCompile(`^!\s+Command: show startup-config`)
for _, dut := range duts {
dut.Refresh()
config := dut.StartupConfig()
if found := re.MatchString(config); !found {
t.Fatal("Failed to obtain startup-config")
}
config = dut.StartupConfig()
if found := re.MatchString(config); !found {
t.Fatal("Failed to obtain non-cached startup-config")
}
}
}
func TestClientNodeGetConfigInvalid_SystemTest(t *testing.T) {
for _, dut := range duts {
if _, err := dut.GetConfig("bogus-config", ""); err == nil {
t.Fatal("Failed to return error on bogus-config")
}
}
}
func TestClientNodeGetSection_SystemTest(t *testing.T) {
re := regexp.MustCompile(`^interface\s+Management1`)
regStr := `(?m)^interface\s+Management1$`
invalidRegexp := `(?=>)interface\s+Management1$`
for _, dut := range duts {
section, err := dut.GetSection(regStr, "bogus-config")
if err == nil {
t.Fatalf("GetSection should return error on bogus-config")
}
section, err = dut.GetSection(regStr, "")
if found := re.MatchString(section); !found {
t.Fatalf("Failed to obtain section from running-config err: %s", err)
}
section, _ = dut.GetSection(regStr, "running-config")
if found := re.MatchString(section); !found {
t.Fatalf("Failed to obtain section from running-config")
}
section, _ = dut.GetSection(regStr, "startup-config")
if found := re.MatchString(section); !found {
t.Fatalf("Failed to obtain section from startup-config")
}
section, err = dut.GetSection(invalidRegexp, "startup-config")
if err == nil {
t.Fatalf("Invalid regexp didn't fail")
}
}
}
func TestClientNodeEnableInvalidConfigCommands_SystemTest(t *testing.T) {
tests := [...]struct {
in []string
}{
{[]string{"configure terminal"}},
{[]string{"configure terminal"}},
{[]string{" configure"}},
{[]string{"configure"}},
}
for _, dut := range duts {
for _, tt := range tests {
if _, got := dut.Enable(tt.in); got == nil {
t.Fatalf("Should have failed %s", tt.in)
}
}
}
}
func TestClientNodeEnableValid_SystemTest(t *testing.T) {
re := regexp.MustCompile(`Internal build version`)
cmds := []string{"show version"}
for _, dut := range duts {
crap, _ := dut.Enable(cmds)
if found := re.MatchString(crap[0]["result"]); !found {
t.Fatal("Failed to obtain build version")
}
}
}
func TestClientHandleEncoding_UnitTest(t *testing.T) {
node := &Node{}
if _, err := node.GetHandle("json"); err != nil {
t.Fatal("GetHandle json")
}
if _, err := node.GetHandle("text"); err != nil {
t.Fatal("GetHandle text")
}
if _, err := node.GetHandle("crap"); err == nil {
t.Fatal("GetHandle crap")
}
if _, err := node.GetHandle("JsOn"); err != nil {
t.Fatal("GetHandle JsOn")
}
}
func TestClientHandleInvalid_UnitTest(t *testing.T) {
var node *Node
if _, err := node.GetHandle("json"); err == nil {
t.Fatal("GetHandle invalid failed")
}
}
func TestClientHandleClose_UnitTest(t *testing.T) {
node := &Node{}
handle, _ := node.GetHandle("json")
handle.Close()
if err := handle.Call(); err == nil {
t.Fatal("No error for Call() after Close()")
}
}
func TestClientNodeGetConnectionInvalid_UnitTest(t *testing.T) {
var node *Node
conn := node.GetConnection()
if conn != nil {
t.Fatal("Should not return valid")
}
}
func TestClientNodeGetConnection_UnitTest(t *testing.T) {
for _, dut := range duts {
conn := dut.GetConnection()
if conn == nil {
t.Fatal("Failed to obtain connection")
}
}
}