forked from nleiva/xrgrpc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_test.go
999 lines (953 loc) · 27.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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
// Big TODO: current coverage: 66.2% of statements
package xrgrpc_test
import (
"encoding/json"
"fmt"
"net"
"strings"
"testing"
"time"
xr "github.com/nleiva/xrgrpc"
pb "github.com/nleiva/xrgrpc/proto/ems"
"github.com/pkg/errors"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/metadata"
)
const (
defaultAddr = "localhost"
defaultPort = ":57344"
defaultUser = "test"
defaultPass = "test"
defaultCert = "test/cert.pem"
defaultKey = "test/key.pem"
defaultCmd = "show test"
defaultYang = "{\"Cisco-IOS-XR-test:tree\": [null]}"
defaultSubsID = "TEST"
wrongCmd = "show me the money"
wrongConf = "confreg 0x00"
wrongYang = "{\"Cisco-IOS-XR-fake:tree\": [null]}"
wrongCreds = "incorrect username/password"
wrongSubsID = "wrong Subscription ID"
wrongEncode = "wrong encoding"
wrongCmdErr = "wrong command"
wrongYangErr = "wrong YANG path"
defaultTimeout = 5
)
// execServer implements the GRPCExecServer interface
type execServer struct{}
func (s *execServer) ShowCmdTextOutput(a *pb.ShowCmdArgs, stream pb.GRPCExec_ShowCmdTextOutputServer) error {
if a.GetCli() != defaultCmd {
stream.Send(&pb.ShowCmdTextReply{
ResReqId: a.GetReqId(),
Errors: wrongCmdErr,
})
return errors.New(wrongCmdErr)
}
stream.Send(&pb.ShowCmdTextReply{
ResReqId: a.GetReqId(),
Output: "show test output",
})
return nil
}
func (s *execServer) ShowCmdJSONOutput(a *pb.ShowCmdArgs, stream pb.GRPCExec_ShowCmdJSONOutputServer) error {
if a.GetCli() != defaultCmd {
stream.Send(&pb.ShowCmdJSONReply{
ResReqId: a.GetReqId(),
Errors: wrongCmdErr,
})
return errors.New(wrongCmdErr)
}
m := map[string]string{"result": "show test output"}
j, err := json.Marshal(m)
if err != nil {
return errors.New("could not encode the test response")
}
stream.Send(&pb.ShowCmdJSONReply{
ResReqId: a.GetReqId(),
Jsonoutput: string(j),
})
return nil
}
// operConfigServer implements the GRPCConfigOperServer interface
type operConfigServer struct{}
func (s *operConfigServer) GetConfig(a *pb.ConfigGetArgs, stream pb.GRPCConfigOper_GetConfigServer) error {
if a.GetYangpathjson() != defaultYang {
stream.Send(&pb.ConfigGetReply{
ResReqId: a.GetReqId(),
Errors: wrongYangErr,
})
return errors.New(wrongYangErr)
}
m := map[string]string{"result": "config"}
j, err := json.Marshal(m)
if err != nil {
return errors.New("could not encode the test response")
}
stream.Send(&pb.ConfigGetReply{
ResReqId: a.GetReqId(),
Yangjson: string(j),
})
return nil
}
func (s *operConfigServer) MergeConfig(ctx context.Context, a *pb.ConfigArgs) (r *pb.ConfigReply, err error) {
if a.GetYangjson() != defaultYang {
err = errors.New(wrongYangErr)
r = &pb.ConfigReply{
ResReqId: a.GetReqId(),
Errors: wrongYangErr,
}
return
}
r = &pb.ConfigReply{
ResReqId: a.GetReqId(),
}
return
}
func (s *operConfigServer) DeleteConfig(ctx context.Context, a *pb.ConfigArgs) (r *pb.ConfigReply, err error) {
if a.GetYangjson() != defaultYang {
err = errors.New(wrongYangErr)
r = &pb.ConfigReply{
ResReqId: a.GetReqId(),
Errors: wrongYangErr,
}
return
}
r = &pb.ConfigReply{
ResReqId: a.GetReqId(),
}
return
}
func (s *operConfigServer) ReplaceConfig(ctx context.Context, a *pb.ConfigArgs) (r *pb.ConfigReply, err error) {
if a.GetYangjson() != defaultYang {
err = errors.New(wrongYangErr)
r = &pb.ConfigReply{
ResReqId: a.GetReqId(),
Errors: wrongYangErr,
}
return
}
r = &pb.ConfigReply{
ResReqId: a.GetReqId(),
}
return
}
func (s *operConfigServer) CliConfig(ctx context.Context, a *pb.CliConfigArgs) (r *pb.CliConfigReply, err error) {
if a.GetCli() != defaultCmd {
err = errors.New(wrongCmdErr)
r = &pb.CliConfigReply{
ResReqId: a.GetReqId(),
Errors: wrongCmdErr,
}
return
}
r = &pb.CliConfigReply{
ResReqId: a.GetReqId(),
}
return
}
// CommitConfig commits a config. Need to clarify its use-case.
func (s *operConfigServer) CommitReplace(ctx context.Context, a *pb.CommitReplaceArgs) (r *pb.CommitReplaceReply, err error) {
return
}
// CommitConfig commits a config. Need to clarify its use-case.
func (s *operConfigServer) CommitConfig(ctx context.Context, a *pb.CommitArgs) (r *pb.CommitReply, err error) {
Msg := pb.CommitMsg{Label: "test", Comment: "test"}
if *a.GetMsg() != Msg {
err = errors.New(wrongCmdErr)
r = &pb.CommitReply{
Result: pb.CommitResult_FAIL,
ResReqId: a.GetReqId(),
Errors: wrongCmdErr,
}
return
}
r = &pb.CommitReply{
ResReqId: a.GetReqId(),
Result: pb.CommitResult_CHANGE,
}
return
}
// CommitConfig commits a config. Need to clarify its use-case.
func (s *operConfigServer) ConfigDiscardChanges(context.Context, *pb.DiscardChangesArgs) (*pb.DiscardChangesReply, error) {
return nil, nil
}
func (s *operConfigServer) GetOper(a *pb.GetOperArgs, stream pb.GRPCConfigOper_GetOperServer) error {
if a.GetYangpathjson() != defaultYang {
stream.Send(&pb.GetOperReply{
ResReqId: a.GetReqId(),
Errors: wrongYangErr,
})
return errors.New(wrongYangErr)
}
m := map[string]string{"result": "oper"}
j, err := json.Marshal(m)
if err != nil {
return errors.New("could not encode the test response")
}
stream.Send(&pb.GetOperReply{
ResReqId: a.GetReqId(),
Yangjson: string(j),
})
return nil
}
func (s *operConfigServer) CreateSubs(a *pb.CreateSubsArgs, stream pb.GRPCConfigOper_CreateSubsServer) error {
mape := map[int64]string{
2: "gpb",
3: "gpbkv",
4: "json",
}
_, ok := mape[a.GetEncode()]
if !ok {
return fmt.Errorf("%s, '%v' not supported", wrongEncode, a.GetEncode())
}
if a.GetSubidstr() != defaultSubsID {
stream.Send(&pb.CreateSubsReply{
ResReqId: a.GetReqId(),
Errors: wrongSubsID,
})
return errors.New(wrongSubsID)
}
m := map[string]string{"result": "oper"}
j, err := json.Marshal(m)
if err != nil {
return errors.New("could not encode the test response")
}
// Telemetry fixed at 0.45 second interval for testing
ticker := time.NewTicker(450 * time.Millisecond)
// With this ('n') we can simulate server and client connection cancellation:
// n < ctx.Timeout -> Server cancels
// n > ctx.Timeout -> Client cancels
// Considering the only numerical inputs we have are the ID and Encoding, we will
// re-use the latter to timeout the stream.
n := time.Duration(a.GetEncode()) * time.Second
timeout := make(chan bool, 1)
go func() {
time.Sleep(n)
timeout <- true
}()
for {
select {
case <-ticker.C:
stream.Send(&pb.CreateSubsReply{
ResReqId: a.GetReqId(),
Data: j,
})
case <-timeout:
ticker.Stop()
return nil
}
}
}
// streamInterceptor to authenticate incoming gRPC stream connections
func streamInterceptor(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
if err := authorize(stream.Context()); err != nil {
return err
}
return handler(srv, stream)
}
// unaryInterceptor to authenticate incoming gRPC unary connections
func unaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
if err := authorize(ctx); err != nil {
return nil, err
}
return handler(ctx, req)
}
// Validates username and password
func authorize(ctx context.Context) error {
if md, ok := metadata.FromContext(ctx); ok {
if len(md["username"]) > 0 && md["username"][0] == defaultUser &&
len(md["password"]) > 0 && md["password"][0] == defaultPass {
return nil
}
return errors.New(wrongCreds)
}
return errors.New("empty metadata")
}
func Server(t *testing.T, svc string) *grpc.Server {
lis, err := net.Listen("tcp", defaultPort)
if err != nil {
t.Fatalf("failed to listen: %v", err)
}
creds, err := credentials.NewServerTLSFromFile(defaultCert, defaultKey)
if err != nil {
t.Fatalf("failed to construct TLS credentialst: %v", err)
}
// var opts []grpc.ServerOption
s := grpc.NewServer(
grpc.Creds(creds),
grpc.StreamInterceptor(streamInterceptor),
grpc.UnaryInterceptor(unaryInterceptor),
)
switch svc {
case "exec":
pb.RegisterGRPCExecServer(s, &execServer{})
case "opercon":
pb.RegisterGRPCConfigOperServer(s, &operConfigServer{})
default:
}
go func() {
err := s.Serve(lis)
// Serve always returns a non-nil error :-(
if strings.Contains(err.Error(), "use of closed network connection") {
return
}
if err != nil {
t.Fatalf("failed to serve: %v", err)
}
}()
return s
}
func TestConnect(t *testing.T) {
x := xr.CiscoGrpcClient{
// User/Password are per RPC based, won't be checked when dialing.
// Cert and Key for localhost are provided in the test folder
User: defaultUser,
Password: defaultPass,
Host: strings.Join([]string{defaultAddr, defaultPort}, ""),
Cert: defaultCert,
Domain: "localhost",
Timeout: defaultTimeout,
}
tt := []struct {
name string
target string
certf string
err string
}{
{name: "local connection"},
{name: "wrong target", target: "192.168.0.1:57344", err: "TBD"},
{name: "wrong certificate", certf: "example/input/certificate/ems5502-1.pem", err: "TBD"},
{name: "inexistent certificate", certf: "dummy", err: "TBD"},
}
s := Server(t, "none")
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
// Get a copy of 'x' and change parameters of test case so requires
xc := x
if tc.certf != "" {
xc.Cert = tc.certf
}
if tc.target != "" {
xc.Host = tc.target
}
// Won't return Error if it keeps re-trying.
conn, ctx, err := xr.Connect(xc)
if err != nil {
if tc.err != "" {
return
}
t.Fatalf("could not setup a client connection to %v", xc.Host)
}
select {
case <-ctx.Done():
t.Fatalf("could not setup a client connection to %v in under 1.5 seconds", xc.Host)
// Just wait for 2.5 seconds for this local connection to be setup.
case <-time.After(2500 * time.Millisecond):
break
}
// Connection won't fail until it timeouts. It re-attempt to connect until this happens.
// Can initially timeout because of the WithTimeout option hard-coded to two seconds
// or after an overal timeout of 'x.Timeout'
conn.Close()
})
}
s.Stop()
// To avoid tests failing in Travis CI, we sleep for 0.2 seconds, otherwise it
// reports 'bind: address already in use' when trying to run the next function test
time.Sleep(200 * time.Millisecond)
}
func TestShowCmdTextOutput(t *testing.T) {
x := xr.CiscoGrpcClient{
User: defaultUser,
Password: defaultPass,
Host: strings.Join([]string{defaultAddr, defaultPort}, ""),
Cert: defaultCert,
Domain: "localhost",
Timeout: defaultTimeout,
}
tt := []struct {
name string
cmd string
user string
pass string
err string
}{
{name: "local connection", cmd: defaultCmd},
{name: "wrong command", cmd: wrongCmd, err: wrongCmdErr},
// TODO Fix the StreamInterceptor to hadle wrong authentication.
// {name: "wrong user", cmd: defaultCmd, user: "bob", err: wrongCreds},
}
s := Server(t, "exec")
conn, ctx, err := xr.Connect(x)
if err != nil {
t.Fatalf("could not setup a client connection to %v", x.Host)
}
var id int64 = 1
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
if tc.user != "" {
conn.Close()
xc := x
xc.User = tc.user
conn, ctx, err = xr.Connect(xc)
if err != nil {
t.Fatalf("could not setup a client connection to %v", x.Host)
}
}
_, err := xr.ShowCmdTextOutput(ctx, conn, tc.cmd, id)
if err != nil {
if strings.Contains(err.Error(), wrongCmdErr) && tc.err == wrongCmdErr {
return
}
if strings.Contains(err.Error(), wrongCreds) && tc.err == wrongCreds {
return
}
t.Fatalf("failed to get show command text output from %v", x.Host)
}
})
id++
}
conn.Close()
s.Stop()
// To avoid tests failing in Travis CI, we sleep for 0.2 seconds, otherwise it
// reports 'bind: address already in use' when trying to run the next function test
time.Sleep(200 * time.Millisecond)
}
func TestShowCmdJSONOutput(t *testing.T) {
x := xr.CiscoGrpcClient{
User: defaultUser,
Password: defaultPass,
Host: strings.Join([]string{defaultAddr, defaultPort}, ""),
Cert: defaultCert,
Domain: "localhost",
Timeout: defaultTimeout,
}
tt := []struct {
name string
cmd string
err string
}{
{name: "local connection", cmd: defaultCmd},
{name: "wrong command", cmd: wrongCmd, err: wrongCmdErr},
}
s := Server(t, "exec")
conn, ctx, err := xr.Connect(x)
if err != nil {
t.Fatalf("could not setup a client connection to %v", x.Host)
}
var id int64 = 1
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
_, err := xr.ShowCmdJSONOutput(ctx, conn, tc.cmd, id)
if err != nil {
if strings.Contains(err.Error(), wrongCmdErr) && tc.err == wrongCmdErr {
return
}
t.Fatalf("failed to get show command json output from %v", x.Host)
}
})
id++
}
conn.Close()
s.Stop()
// To avoid tests failing in Travis CI, we sleep for 0.2 seconds, otherwise it
// reports 'bind: address already in use' when trying to run the next function test
time.Sleep(200 * time.Millisecond)
}
func TestGetConfig(t *testing.T) {
x := xr.CiscoGrpcClient{
User: defaultUser,
Password: defaultPass,
Host: strings.Join([]string{defaultAddr, defaultPort}, ""),
Cert: defaultCert,
Domain: "localhost",
Timeout: defaultTimeout,
}
tt := []struct {
name string
paths string
enc int64
err string
}{
{name: "local connection", paths: defaultYang},
{name: "wrong paths", paths: wrongYang, err: wrongYangErr},
}
s := Server(t, "opercon")
conn, ctx, err := xr.Connect(x)
if err != nil {
t.Fatalf("could not setup a client connection to %v", x.Host)
}
var id int64 = 1
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
_, err := xr.GetConfig(ctx, conn, tc.paths, id)
if err != nil {
if strings.Contains(err.Error(), wrongYangErr) && tc.err == wrongYangErr {
return
}
t.Fatalf("failed to get config from %v", x.Host)
}
})
id++
}
conn.Close()
s.Stop()
// To avoid tests failing in Travis CI, we sleep for 0.2 seconds, otherwise it
// reports 'bind: address already in use' when trying to run the next function test
time.Sleep(200 * time.Millisecond)
}
func TestMergeConfig(t *testing.T) {
x := xr.CiscoGrpcClient{
User: defaultUser,
Password: defaultPass,
Host: strings.Join([]string{defaultAddr, defaultPort}, ""),
Cert: defaultCert,
Domain: "localhost",
Timeout: defaultTimeout,
}
tt := []struct {
name string
conf string
user string
pass string
err string
}{
// The order of these test do matter, we change credentials
// on the last ones.
{name: "local connection", conf: defaultYang},
{name: "wrong config", conf: wrongYang, err: wrongYangErr},
{name: "wrong user", conf: defaultYang, user: "bob", err: wrongCreds},
{name: "wrong password", conf: defaultYang, pass: "password", err: wrongCreds},
}
s := Server(t, "opercon")
conn, ctx, err := xr.Connect(x)
if err != nil {
t.Fatalf("could not setup a client connection to %v", x.Host)
}
var id int64 = 1
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
if tc.user != "" {
conn.Close()
xc := x
xc.User = tc.user
conn, ctx, err = xr.Connect(xc)
if err != nil {
t.Fatalf("could not setup a client connection to %v", x.Host)
}
}
if tc.pass != "" {
conn.Close()
xc := x
xc.Password = tc.pass
conn, ctx, err = xr.Connect(xc)
if err != nil {
t.Fatalf("could not setup a client connection to %v", x.Host)
}
}
_, err := xr.MergeConfig(ctx, conn, tc.conf, id)
if err != nil {
if strings.Contains(err.Error(), wrongCreds) && tc.err == wrongCreds {
return
}
if strings.Contains(err.Error(), wrongYangErr) && tc.err == wrongYangErr {
return
}
t.Fatalf("incorrect response from %v, %v", x.Host, err)
}
})
id++
}
conn.Close()
s.Stop()
// To avoid tests failing in Travis CI, we sleep for 0.2 seconds, otherwise it
// reports 'bind: address already in use' when trying to run the next function test
time.Sleep(200 * time.Millisecond)
}
func TestDeleteConfig(t *testing.T) {
x := xr.CiscoGrpcClient{
User: defaultUser,
Password: defaultPass,
Host: strings.Join([]string{defaultAddr, defaultPort}, ""),
Cert: defaultCert,
Domain: "localhost",
Timeout: defaultTimeout,
}
tt := []struct {
name string
conf string
user string
pass string
err string
}{
// The order of these test do matter, we change credentials
// on the last ones.
{name: "local connection", conf: defaultYang},
{name: "wrong config", conf: wrongYang, err: wrongYangErr},
{name: "wrong user", conf: defaultYang, user: "bob", err: wrongCreds},
{name: "wrong password", conf: defaultYang, pass: "password", err: wrongCreds},
}
s := Server(t, "opercon")
conn, ctx, err := xr.Connect(x)
if err != nil {
t.Fatalf("could not setup a client connection to %v", x.Host)
}
var id int64 = 1
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
if tc.user != "" {
conn.Close()
xc := x
xc.User = tc.user
conn, ctx, err = xr.Connect(xc)
if err != nil {
t.Fatalf("could not setup a client connection to %v", x.Host)
}
}
if tc.pass != "" {
conn.Close()
xc := x
xc.Password = tc.pass
conn, ctx, err = xr.Connect(xc)
if err != nil {
t.Fatalf("could not setup a client connection to %v", x.Host)
}
}
_, err := xr.DeleteConfig(ctx, conn, tc.conf, id)
if err != nil {
if strings.Contains(err.Error(), wrongCreds) && tc.err == wrongCreds {
return
}
if strings.Contains(err.Error(), wrongYangErr) && tc.err == wrongYangErr {
return
}
t.Fatalf("incorrect response from %v, %v", x.Host, err)
}
})
id++
}
conn.Close()
s.Stop()
// To avoid tests failing in Travis CI, we sleep for 0.2 seconds, otherwise it
// reports 'bind: address already in use' when trying to run the next function test
time.Sleep(200 * time.Millisecond)
}
func TestReplaceConfig(t *testing.T) {
x := xr.CiscoGrpcClient{
User: defaultUser,
Password: defaultPass,
Host: strings.Join([]string{defaultAddr, defaultPort}, ""),
Cert: defaultCert,
Domain: "localhost",
Timeout: defaultTimeout,
}
tt := []struct {
name string
conf string
user string
pass string
err string
}{
// The order of these test do matter, we change credentials
// on the last ones.
{name: "local connection", conf: defaultYang},
{name: "wrong config", conf: wrongYang, err: wrongYangErr},
{name: "wrong user", conf: defaultYang, user: "bob", err: wrongCreds},
{name: "wrong password", conf: defaultYang, pass: "password", err: wrongCreds},
}
s := Server(t, "opercon")
conn, ctx, err := xr.Connect(x)
if err != nil {
t.Fatalf("could not setup a client connection to %v", x.Host)
}
var id int64 = 1
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
if tc.user != "" {
conn.Close()
xc := x
xc.User = tc.user
conn, ctx, err = xr.Connect(xc)
if err != nil {
t.Fatalf("could not setup a client connection to %v", x.Host)
}
}
if tc.pass != "" {
conn.Close()
xc := x
xc.Password = tc.pass
conn, ctx, err = xr.Connect(xc)
if err != nil {
t.Fatalf("could not setup a client connection to %v", x.Host)
}
}
_, err := xr.ReplaceConfig(ctx, conn, tc.conf, id)
if err != nil {
if strings.Contains(err.Error(), wrongCreds) && tc.err == wrongCreds {
return
}
if strings.Contains(err.Error(), wrongYangErr) && tc.err == wrongYangErr {
return
}
t.Fatalf("incorrect response from %v, %v", x.Host, err)
}
})
id++
}
conn.Close()
s.Stop()
// To avoid tests failing in Travis CI, we sleep for 0.2 seconds, otherwise it
// reports 'bind: address already in use' when trying to run the next function test
time.Sleep(200 * time.Millisecond)
}
func TestCLIConfig(t *testing.T) {
x := xr.CiscoGrpcClient{
User: defaultUser,
Password: defaultPass,
Host: strings.Join([]string{defaultAddr, defaultPort}, ""),
Cert: defaultCert,
Domain: "localhost",
Timeout: defaultTimeout,
}
tt := []struct {
name string
conf string
user string
pass string
err string
}{
// The order of these test do matter, we change credentials
// on the last ones.
{name: "local connection", conf: defaultCmd},
{name: "wrong config", conf: wrongConf, err: wrongCmdErr},
{name: "wrong user", conf: defaultCmd, user: "bob", err: wrongCreds},
{name: "wrong password", conf: defaultCmd, pass: "password", err: wrongCreds},
}
s := Server(t, "opercon")
conn, ctx, err := xr.Connect(x)
if err != nil {
t.Fatalf("could not setup a client connection to %v", x.Host)
}
var id int64 = 1
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
if tc.user != "" {
conn.Close()
xc := x
xc.User = tc.user
conn, ctx, err = xr.Connect(xc)
if err != nil {
t.Fatalf("could not setup a client connection to %v", x.Host)
}
}
if tc.pass != "" {
conn.Close()
xc := x
xc.Password = tc.pass
conn, ctx, err = xr.Connect(xc)
if err != nil {
t.Fatalf("could not setup a client connection to %v", x.Host)
}
}
err := xr.CLIConfig(ctx, conn, tc.conf, id)
if err != nil {
if strings.Contains(err.Error(), wrongCreds) && tc.err == wrongCreds {
return
}
if strings.Contains(err.Error(), wrongCmdErr) && tc.err == wrongCmdErr {
return
}
t.Fatalf("incorrect response from %v, %v", x.Host, err)
}
})
id++
}
conn.Close()
s.Stop()
// To avoid tests failing in Travis CI, we sleep for 0.2 seconds, otherwise it
// reports 'bind: address already in use' when trying to run the next function test
time.Sleep(200 * time.Millisecond)
}
func TestCommitConfig(t *testing.T) {
x := xr.CiscoGrpcClient{
User: defaultUser,
Password: defaultPass,
Host: strings.Join([]string{defaultAddr, defaultPort}, ""),
Cert: defaultCert,
Domain: "localhost",
Timeout: defaultTimeout,
}
defaultMsg := [2]string{"test", "test"}
tt := []struct {
name string
msg [2]string
user string
pass string
err string
}{
// The order of these test do matter, we change credentials
// on the last ones.
{name: "local connection", msg: defaultMsg},
{name: "wrong config", msg: [2]string{"unknown", "anything"}, err: wrongCmdErr},
{name: "wrong user", msg: defaultMsg, user: "bob", err: wrongCreds},
{name: "wrong password", msg: defaultMsg, pass: "password", err: wrongCreds},
}
s := Server(t, "opercon")
conn, ctx, err := xr.Connect(x)
if err != nil {
t.Fatalf("could not setup a client connection to %v", x.Host)
}
var id int64 = 1
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
if tc.user != "" {
conn.Close()
xc := x
xc.User = tc.user
conn, ctx, err = xr.Connect(xc)
if err != nil {
t.Fatalf("could not setup a client connection to %v", x.Host)
}
}
if tc.pass != "" {
conn.Close()
xc := x
xc.Password = tc.pass
conn, ctx, err = xr.Connect(xc)
if err != nil {
t.Fatalf("could not setup a client connection to %v", x.Host)
}
}
_, err := xr.CommitConfig(ctx, conn, tc.msg, id)
if err != nil {
if strings.Contains(err.Error(), wrongCreds) && tc.err == wrongCreds {
return
}
if strings.Contains(err.Error(), wrongCmdErr) && tc.err == wrongCmdErr {
return
}
t.Fatalf("Incorrect response from %v, %v", x.Host, err)
}
})
id++
}
conn.Close()
s.Stop()
// To avoid tests failing in Travis CI, we sleep for 0.2 seconds, otherwise it
// reports 'bind: address already in use' when trying to run the next function test
time.Sleep(200 * time.Millisecond)
}
func TestGetSubscription(t *testing.T) {
x := xr.CiscoGrpcClient{
User: defaultUser,
Password: defaultPass,
Host: strings.Join([]string{defaultAddr, defaultPort}, ""),
Cert: defaultCert,
Domain: "localhost",
// We fixed Timeout to 3, in this case, in order to test different failure scenarios
Timeout: 3,
}
tt := []struct {
name string
subs string
enc int64
err string
}{
{name: "server timeout", subs: defaultSubsID, enc: 2},
{name: "client timeout", subs: defaultSubsID, enc: 4},
{name: "wrong subscription", subs: "anything", enc: 3, err: wrongSubsID},
{name: "wrong encoding", subs: defaultSubsID, enc: 5, err: wrongEncode},
}
s := Server(t, "opercon")
var id int64 = 1
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
// start := time.Now()
conn, ctx, err := xr.Connect(x)
defer conn.Close()
if err != nil {
t.Fatalf("could not setup a client connection to %v", x.Host)
}
ctx, cancel := context.WithCancel(ctx)
defer cancel()
ch, ech, err := xr.GetSubscription(ctx, conn, tc.subs, id, tc.enc)
if err != nil {
if strings.Contains(err.Error(), wrongSubsID) && tc.err == wrongSubsID ||
strings.Contains(err.Error(), wrongEncode) && tc.err == wrongEncode {
return
}
t.Fatalf("could not setup Telemetry Subscription from %v: %v", x.Host, err)
}
// copy tc.err to avoid race condition
go func(e string) {
select {
case <-ctx.Done():
// Timeout: "context deadline exceeded"
// err = ctx.Err()
// fmt.Printf("\ngRPC session timed out after %v seconds: %v\n\n", time.Since(start), err.Error())
return
case err = <-ech:
if err.Error() == "EOF" ||
strings.Contains(err.Error(), wrongSubsID) && e == wrongSubsID ||
strings.Contains(err.Error(), wrongEncode) && e == wrongEncode {
return
}
// Session canceled: "context canceled"
t.Fatalf("\ngRPC session to %v failed: %v\n\n", x.Host, err.Error())
}
}(tc.err)
i := 1
for tele := range ch {
fmt.Printf("Telemetry Message %v-%v: %s\n", tc.enc, i, string(tele))
i++
}
id++
})
}
s.Stop()
// To avoid tests failing in Travis CI, we sleep for 0.2 seconds, otherwise it
// reports 'bind: address already in use' when trying to run the next function test
time.Sleep(200 * time.Millisecond)
}
func TestBuildRouter(t *testing.T) {
tt := []struct {
name string
user string
pass string
host string
cert string
timeout int
err string
}{
{name: "default case", user: defaultUser, pass: defaultPass, host: defaultAddr + defaultPort, cert: defaultCert, timeout: defaultTimeout},
{name: "wrong username", pass: defaultPass, host: defaultAddr + defaultPort, cert: defaultCert,
timeout: defaultTimeout, err: "invalid username"},
{name: "wrong password", user: defaultUser, host: defaultAddr + defaultPort, cert: defaultCert,
timeout: defaultTimeout, err: "invalid password"},
{name: "wrong host", user: defaultUser, pass: defaultPass, host: "300.1.1.1:57344", cert: defaultCert,
timeout: defaultTimeout, err: "not a valid host address"},
{name: "wrong cert file", user: defaultUser, pass: defaultPass, host: defaultAddr + defaultPort,
timeout: defaultTimeout, err: "not a valid file location"},
{name: "wrong timeout", user: defaultUser, pass: defaultPass, host: defaultAddr + defaultPort, cert: defaultCert,
timeout: 0, err: "timeout must be greater than zero"},
}
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
_, err := xr.BuildRouter(
xr.WithUsername(tc.user),
xr.WithPassword(tc.pass),
xr.WithHost(tc.host),
xr.WithCert(tc.cert),
xr.WithTimeout(tc.timeout),
)
if err != nil {
if strings.Contains(err.Error(), tc.err) {
return
}
t.Fatalf("Target parameters are incorrect: %s", err.Error())
}
})
}
}