-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient_test.go
More file actions
1733 lines (1561 loc) · 51.9 KB
/
Copy pathclient_test.go
File metadata and controls
1733 lines (1561 loc) · 51.9 KB
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
1000
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) 2025 Daniel Schmidt
package netconf
import (
"fmt"
"io"
"regexp"
"strings"
"testing"
"time"
"github.com/scrapli/scrapligo/response"
"github.com/scrapli/scrapligo/util"
)
// Test constants (GOCONST)
const (
testOperationFailed = "operation-failed"
)
func TestClientDefaultConfiguration(t *testing.T) {
t.Run("client with default options", func(t *testing.T) {
// We can't actually connect without a real NETCONF server,
// but we can test that option functions work
opts := []func(*Client){
Username("admin"),
Password("secret"),
Port(8830),
MaxRetries(5),
ConnectTimeout(10 * time.Second),
}
// Create a client structure (without connecting)
client := &Client{
Host: "192.168.1.1",
Port: 830,
MaxRetries: 10,
BackoffMinDelay: 1 * time.Second,
BackoffMaxDelay: 60 * time.Second,
BackoffDelayFactor: 1.2,
LockReleaseTimeout: 120 * time.Second,
ConnectTimeout: 30 * time.Second,
AttemptTimeout: 30 * time.Second,
TotalTimeout: 2 * time.Minute,
}
// Apply options
for _, opt := range opts {
opt(client)
}
// Verify options were applied
// NOTE: Username() and Password() removed for security (FIX 7)
// Use HasCredentials() instead
if !client.HasCredentials() {
t.Error("expected client to have credentials configured")
}
if client.Port != 8830 {
t.Errorf("expected port 8830, got %d", client.Port)
}
if client.MaxRetries != 5 {
t.Errorf("expected MaxRetries 5, got %d", client.MaxRetries)
}
if client.ConnectTimeout != 10*time.Second {
t.Errorf("expected ConnectTimeout 10s, got %v", client.ConnectTimeout)
}
// Verify credentials are set correctly (access private fields for testing)
if client.username != "admin" {
t.Errorf("expected username 'admin', got %s", client.username)
}
if client.password != "secret" {
t.Errorf("expected password 'secret', got %s", client.password)
}
})
t.Run("client with SSH key", func(t *testing.T) {
client := &Client{
Host: "192.168.1.1",
}
SSHKey("/path/to/key")(client)
if client.SSHKeyPath != "/path/to/key" {
t.Errorf("expected SSHKeyPath '/path/to/key', got %s", client.SSHKeyPath)
}
})
}
func TestClientCapabilities(t *testing.T) {
t.Run("ServerHasCapability with no capabilities", func(t *testing.T) {
client := &Client{
Capabilities: []string{},
}
if client.ServerHasCapability("urn:ietf:params:netconf:base:1.0") {
t.Error("expected false for empty capabilities")
}
})
t.Run("ServerHasCapability with capabilities", func(t *testing.T) {
client := &Client{
Capabilities: []string{
"urn:ietf:params:netconf:base:1.0",
"urn:ietf:params:netconf:capability:candidate:1.0",
},
}
if !client.ServerHasCapability("urn:ietf:params:netconf:base:1.0") {
t.Error("expected true for base capability")
}
if !client.ServerHasCapability("urn:ietf:params:netconf:capability:candidate:1.0") {
t.Error("expected true for candidate capability")
}
if client.ServerHasCapability("urn:ietf:params:netconf:capability:xpath:1.0") {
t.Error("expected false for missing capability")
}
})
t.Run("ServerCapabilities returns copy", func(t *testing.T) {
client := &Client{
Capabilities: []string{"cap1", "cap2"},
}
caps := client.ServerCapabilities()
if len(caps) != 2 {
t.Errorf("expected 2 capabilities, got %d", len(caps))
}
})
}
func TestClientClose(t *testing.T) {
t.Run("close on nil driver should not panic", func(t *testing.T) {
client := &Client{
driver: nil,
}
err := client.Close()
if err != nil {
t.Errorf("Close() on nil driver should not error, got %v", err)
}
})
}
func TestClientOpen(t *testing.T) {
t.Run("open without valid connection should fail", func(t *testing.T) {
// Create client with invalid host to ensure connection fails
client := &Client{
Host: "invalid-host-that-does-not-exist.local",
Port: 830,
username: "test",
password: "test",
ConnectTimeout: 1 * time.Second,
AttemptTimeout: 1 * time.Second,
TotalTimeout: 5 * time.Second,
logger: &NoOpLogger{},
prettyPrintLogs: false,
redactionPatterns: defaultRedactionPatterns,
}
// Attempt to open (should fail because host doesn't exist)
err := client.Open()
if err == nil {
t.Error("Open() should fail with invalid host")
}
})
t.Run("open preserves client configuration", func(t *testing.T) {
// Create client with specific configuration
client := &Client{
Host: "test-host",
Port: 2222,
username: "testuser",
password: "testpass",
SSHKeyPath: "/path/to/key",
InsecureSkipVerify: true,
MaxRetries: 5,
BackoffMinDelay: 2 * time.Second,
BackoffMaxDelay: 120 * time.Second,
BackoffDelayFactor: 3.0,
LockReleaseTimeout: 240 * time.Second,
ConnectTimeout: 45 * time.Second,
AttemptTimeout: 60 * time.Second,
TotalTimeout: 5 * time.Minute,
logger: &NoOpLogger{},
prettyPrintLogs: true,
redactionPatterns: defaultRedactionPatterns,
}
// Note: This test verifies configuration is preserved during connect attempt
// The connection will fail (no server), but we verify the client state remains intact
originalHost := client.Host
originalPort := client.Port
originalUser := client.username
originalPass := client.password
originalSSHKey := client.SSHKeyPath
originalInsecure := client.InsecureSkipVerify
originalMaxRetries := client.MaxRetries
originalConnectTimeout := client.ConnectTimeout
// Attempt open (will fail, but shouldn't corrupt state)
_ = client.Open() //nolint:errcheck // Test expects failure, checking state preservation only
// Verify configuration preserved
if client.Host != originalHost {
t.Errorf("Host changed after Open: got %s, want %s", client.Host, originalHost)
}
if client.Port != originalPort {
t.Errorf("Port changed after Open: got %d, want %d", client.Port, originalPort)
}
if client.username != originalUser {
t.Errorf("Username changed after Open: got %s, want %s", client.username, originalUser)
}
if client.password != originalPass {
t.Errorf("Password changed after Open: got %s, want %s", client.password, originalPass)
}
if client.SSHKeyPath != originalSSHKey {
t.Errorf("SSHKeyPath changed after Open: got %s, want %s", client.SSHKeyPath, originalSSHKey)
}
if client.InsecureSkipVerify != originalInsecure {
t.Errorf("InsecureSkipVerify changed after Open: got %v, want %v", client.InsecureSkipVerify, originalInsecure)
}
if client.MaxRetries != originalMaxRetries {
t.Errorf("MaxRetries changed after Open: got %d, want %d", client.MaxRetries, originalMaxRetries)
}
if client.ConnectTimeout != originalConnectTimeout {
t.Errorf("ConnectTimeout changed after Open: got %v, want %v", client.ConnectTimeout, originalConnectTimeout)
}
})
t.Run("open after close should reconnect", func(t *testing.T) {
client := &Client{
Host: "test-host",
Port: 830,
username: "test",
password: "test",
driver: nil, // Simulate closed state
ConnectTimeout: 1 * time.Second,
AttemptTimeout: 1 * time.Second,
TotalTimeout: 5 * time.Second,
logger: &NoOpLogger{},
prettyPrintLogs: false,
redactionPatterns: defaultRedactionPatterns,
}
// Driver should be nil initially
if client.driver != nil {
t.Error("Driver should be nil before Open")
}
// Attempt open (will fail but shouldn't panic)
_ = client.Open() //nolint:errcheck // Test expects failure, checking panic prevention only
// Driver remains nil after failed open
if client.driver != nil {
t.Error("Driver should remain nil after failed Open")
}
})
}
func TestClientIsClosed(t *testing.T) {
t.Run("client with nil driver is closed", func(t *testing.T) {
client := &Client{
driver: nil,
}
if !client.IsClosed() {
t.Error("IsClosed() should return true when driver is nil")
}
})
t.Run("newly created client without connection is closed", func(t *testing.T) {
// Create client structure without calling NewClient (which opens connection)
client := &Client{
Host: "test-host",
Port: 830,
username: "test",
password: "test",
driver: nil, // No connection established
}
if !client.IsClosed() {
t.Error("IsClosed() should return true for client without connection")
}
})
t.Run("closed client after Close() is detected as closed", func(t *testing.T) {
client := &Client{
driver: nil, // Simulate already closed
}
// Close should be idempotent
err := client.Close()
if err != nil {
t.Errorf("Close() should not error on already closed client: %v", err)
}
if !client.IsClosed() {
t.Error("IsClosed() should return true after Close()")
}
})
t.Run("IsClosed is thread-safe", func(t *testing.T) {
client := &Client{
driver: nil,
}
// Run concurrent IsClosed checks
done := make(chan bool)
for i := 0; i < 10; i++ {
go func() {
for j := 0; j < 100; j++ {
_ = client.IsClosed()
}
done <- true
}()
}
// Wait for all goroutines
for i := 0; i < 10; i++ {
<-done
}
// Should still be closed
if !client.IsClosed() {
t.Error("IsClosed() should remain true after concurrent access")
}
})
}
// Note: Full integration tests with actual NETCONF connections would require
// a real NETCONF server or mock. These tests focus on unit testing the
// structure and basic functionality.
func TestClientBackoff(t *testing.T) {
tests := []struct {
name string
minDelay time.Duration
maxDelay time.Duration
factor float64
attempt int
expectedMinDelay time.Duration
expectedMaxDelay time.Duration
}{
{
name: "first attempt",
minDelay: 1 * time.Second,
maxDelay: 60 * time.Second,
factor: 2.0,
attempt: 0,
expectedMinDelay: 1 * time.Second,
expectedMaxDelay: 2 * time.Second, // With 10% jitter
},
{
name: "second attempt",
minDelay: 1 * time.Second,
maxDelay: 60 * time.Second,
factor: 2.0,
attempt: 1,
expectedMinDelay: 2 * time.Second,
expectedMaxDelay: 3 * time.Second, // 2s * 2 + 10% jitter
},
{
name: "capped at max delay",
minDelay: 1 * time.Second,
maxDelay: 10 * time.Second,
factor: 2.0,
attempt: 10,
expectedMinDelay: 10 * time.Second, // Should cap at max
expectedMaxDelay: 11 * time.Second, // Max + 10% jitter
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
client := &Client{
BackoffMinDelay: tt.minDelay,
BackoffMaxDelay: tt.maxDelay,
BackoffDelayFactor: tt.factor,
}
delay := client.Backoff(tt.attempt)
if delay < tt.expectedMinDelay {
t.Errorf("delay %v is less than expected minimum %v", delay, tt.expectedMinDelay)
}
if delay > tt.expectedMaxDelay {
t.Errorf("delay %v is greater than expected maximum %v", delay, tt.expectedMaxDelay)
}
})
}
}
func TestClientCheckTransientError(t *testing.T) {
tests := []struct {
name string
errors []ErrorModel
isTransient bool
}{
{
name: "lock-denied error",
errors: []ErrorModel{
{ErrorTag: "lock-denied"},
},
isTransient: true,
},
{
name: "in-use error",
errors: []ErrorModel{
{ErrorTag: "in-use"},
},
isTransient: true,
},
{
name: "transport error",
errors: []ErrorModel{
{ErrorType: "transport"},
},
isTransient: true,
},
{
name: "non-transient error",
errors: []ErrorModel{
{ErrorTag: "invalid-value"},
},
isTransient: false,
},
{
name: "no errors",
errors: []ErrorModel{},
isTransient: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
client := &Client{}
result := client.checkTransientError(tt.errors, nil)
if result != tt.isTransient {
t.Errorf("expected isTransient %v, got %v", tt.isTransient, result)
}
})
}
// Test scrapligo Go errors
scrapligoTests := []struct {
name string
goErr error
isTransient bool
}{
{
name: "timeout error",
goErr: util.ErrTimeoutError,
isTransient: true,
},
{
name: "connection error",
goErr: util.ErrConnectionError,
isTransient: true,
},
{
name: "operation error",
goErr: util.ErrOperationError,
isTransient: true,
},
{
name: "wrapped timeout error",
goErr: fmt.Errorf("operation failed: %w", util.ErrTimeoutError),
isTransient: true,
},
{
name: "EOF error",
goErr: io.EOF,
isTransient: true,
},
{
name: "wrapped EOF error",
goErr: fmt.Errorf("operation get-config failed (target=running): %w", io.EOF),
isTransient: true,
},
{
name: "non-transient error",
goErr: util.ErrAuthError,
isTransient: false,
},
{
name: "nil error",
goErr: nil,
isTransient: false,
},
}
for _, tt := range scrapligoTests {
t.Run(tt.name, func(t *testing.T) {
client := &Client{}
result := client.checkTransientError([]ErrorModel{}, tt.goErr)
if result != tt.isTransient {
t.Errorf("expected isTransient %v, got %v", tt.isTransient, result)
}
})
}
}
func TestClientParseRPCErrors(t *testing.T) {
tests := []struct {
name string
responseXML string
expectedErrors int
checkFirst func(t *testing.T, err ErrorModel)
}{
{
name: "single error",
responseXML: `<?xml version="1.0"?>
<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="1">
<rpc-error>
<error-type>application</error-type>
<error-tag>operation-failed</error-tag>
<error-severity>error</error-severity>
<error-message>Test error message</error-message>
</rpc-error>
</rpc-reply>`,
expectedErrors: 1,
checkFirst: func(t *testing.T, err ErrorModel) {
if err.ErrorType != "application" {
t.Errorf("expected ErrorType 'application', got %q", err.ErrorType)
}
if err.ErrorTag != testOperationFailed {
t.Errorf("expected ErrorTag 'operation-failed', got %q", err.ErrorTag)
}
if err.ErrorSeverity != "error" {
t.Errorf("expected ErrorSeverity 'error', got %q", err.ErrorSeverity)
}
if err.ErrorMessage != "Test error message" {
t.Errorf("expected ErrorMessage 'Test error message', got %q", err.ErrorMessage)
}
},
},
{
name: "no errors",
responseXML: `<?xml version="1.0"?>
<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="1">
<ok/>
</rpc-reply>`,
expectedErrors: 0,
},
{
name: "error with all fields",
responseXML: `<?xml version="1.0"?>
<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="1">
<rpc-error>
<error-type>protocol</error-type>
<error-tag>invalid-value</error-tag>
<error-severity>error</error-severity>
<error-app-tag>custom-app-tag</error-app-tag>
<error-path>/config/interfaces/interface[name='eth0']</error-path>
<error-message>Invalid interface configuration</error-message>
<error-info>Additional info here</error-info>
</rpc-error>
</rpc-reply>`,
expectedErrors: 1,
checkFirst: func(t *testing.T, err ErrorModel) {
if err.ErrorType != "protocol" {
t.Errorf("expected ErrorType 'protocol', got %q", err.ErrorType)
}
if err.ErrorAppTag != "custom-app-tag" {
t.Errorf("expected ErrorAppTag 'custom-app-tag', got %q", err.ErrorAppTag)
}
if err.ErrorPath != "/config/interfaces/interface[name='eth0']" {
t.Errorf("expected ErrorPath '/config/interfaces/interface[name='eth0']', got %q", err.ErrorPath)
}
if err.ErrorInfo != "Additional info here" {
t.Errorf("expected ErrorInfo 'Additional info here', got %q", err.ErrorInfo)
}
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
client := &Client{}
errors := client.parseRPCErrors(tt.responseXML)
if len(errors) != tt.expectedErrors {
t.Errorf("expected %d errors, got %d", tt.expectedErrors, len(errors))
}
if tt.expectedErrors > 0 && tt.checkFirst != nil {
tt.checkFirst(t, errors[0])
}
})
}
}
func TestClientSessionID(t *testing.T) {
client := &Client{
sessionID: "12345",
}
if client.SessionID() != "12345" {
t.Errorf("expected SessionID '12345', got %q", client.SessionID())
}
}
func TestClientServerVersion(t *testing.T) {
client := &Client{
serverVersion: "1.1",
}
if client.ServerVersion() != "1.1" {
t.Errorf("expected ServerVersion '1.1', got %q", client.ServerVersion())
}
}
func TestClientHasCredentials(t *testing.T) {
tests := []struct {
name string
username string
password string
sshKey string
hasCreds bool
}{
{"username and password", "admin", "secret", "", true},
{"only username", "admin", "", "", true},
{"only password", "", "secret", "", true},
{"only ssh key", "", "", "/path/to/key", true},
{"no credentials", "", "", "", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
client := &Client{
username: tt.username,
password: tt.password,
SSHKeyPath: tt.sshKey,
}
if client.HasCredentials() != tt.hasCreds {
t.Errorf("expected HasCredentials %v, got %v", tt.hasCreds, client.HasCredentials())
}
})
}
}
// Benchmark tests for Client operations
func BenchmarkClientBackoff(b *testing.B) {
client := &Client{
BackoffMinDelay: 1 * time.Second,
BackoffMaxDelay: 60 * time.Second,
BackoffDelayFactor: 2.0,
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = client.Backoff(i % 10)
}
}
func BenchmarkClientCheckTransientError(b *testing.B) {
client := &Client{}
errors := []ErrorModel{
{ErrorTag: "lock-denied"},
{ErrorType: "transport"},
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = client.checkTransientError(errors, nil)
}
}
func BenchmarkClientParseRPCErrors(b *testing.B) {
client := &Client{}
responseXML := `<?xml version="1.0"?>
<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="1">
<rpc-error>
<error-type>application</error-type>
<error-tag>` + testOperationFailed + `</error-tag>
<error-severity>error</error-severity>
<error-message>Test error message</error-message>
</rpc-error>
</rpc-reply>`
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = client.parseRPCErrors(responseXML)
}
}
func BenchmarkClientServerCapabilities(b *testing.B) {
client := &Client{
Capabilities: []string{
"urn:ietf:params:netconf:base:1.0",
"urn:ietf:params:netconf:capability:candidate:1.0",
"urn:ietf:params:netconf:capability:xpath:1.0",
},
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = client.ServerCapabilities()
}
}
func BenchmarkClientServerHasCapability(b *testing.B) {
client := &Client{
Capabilities: []string{
"urn:ietf:params:netconf:base:1.0",
"urn:ietf:params:netconf:capability:candidate:1.0",
"urn:ietf:params:netconf:capability:xpath:1.0",
},
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = client.ServerHasCapability("urn:ietf:params:netconf:base:1.0")
}
}
// TestBuildEditConfigXML tests the buildEditConfigXML method
func TestBuildEditConfigXML(t *testing.T) {
client := &Client{}
tests := []struct {
name string
req *Req
expected []string // expected XML fragments
}{
{
name: "basic edit-config",
req: &Req{
Target: "candidate",
Config: "<config><hostname>router1</hostname></config>",
},
expected: []string{
"<edit-config>",
"<target><candidate/></target>",
"<config><hostname>router1</hostname></config>",
"</edit-config>",
},
},
{
name: "edit-config with default-operation",
req: &Req{
Target: "candidate",
Config: "<config><hostname>router1</hostname></config>",
DefaultOperation: "merge",
},
expected: []string{
"<edit-config>",
"<target><candidate/></target>",
"<default-operation>merge</default-operation>",
"<config><hostname>router1</hostname></config>",
"</edit-config>",
},
},
{
name: "edit-config with test-option",
req: &Req{
Target: "candidate",
Config: "<config><hostname>router1</hostname></config>",
TestOption: "test-then-set",
},
expected: []string{
"<edit-config>",
"<target><candidate/></target>",
"<test-option>test-then-set</test-option>",
"<config><hostname>router1</hostname></config>",
"</edit-config>",
},
},
{
name: "edit-config with error-option",
req: &Req{
Target: "candidate",
Config: "<config><hostname>router1</hostname></config>",
ErrorOption: "rollback-on-error",
},
expected: []string{
"<edit-config>",
"<target><candidate/></target>",
"<error-option>rollback-on-error</error-option>",
"<config><hostname>router1</hostname></config>",
"</edit-config>",
},
},
{
name: "edit-config with all options",
req: &Req{
Target: "running",
Config: "<config><interface>eth0</interface></config>",
DefaultOperation: "replace",
TestOption: "test-only",
ErrorOption: "continue-on-error",
},
expected: []string{
"<edit-config>",
"<target><running/></target>",
"<default-operation>replace</default-operation>",
"<test-option>test-only</test-option>",
"<error-option>continue-on-error</error-option>",
"<config><interface>eth0</interface></config>",
"</edit-config>",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
xml := client.buildEditConfigXML(tt.req)
// Verify all expected fragments are present
for _, expected := range tt.expected {
if !strings.Contains(xml, expected) {
t.Errorf("expected XML to contain %q, got:\n%s", expected, xml)
}
}
// Verify proper XML structure
if !strings.HasPrefix(xml, "<edit-config>") {
t.Errorf("expected XML to start with <edit-config>, got: %s", xml)
}
if !strings.HasSuffix(xml, "</edit-config>") {
t.Errorf("expected XML to end with </edit-config>, got: %s", xml)
}
})
}
}
// TestBuildEditConfigXMLOrder tests the order of elements in edit-config XML
func TestBuildEditConfigXMLOrder(t *testing.T) {
client := &Client{}
req := &Req{
Target: "candidate",
Config: "<config><test/></config>",
DefaultOperation: "merge",
TestOption: "test-then-set",
ErrorOption: "rollback-on-error",
}
xml := client.buildEditConfigXML(req)
// RFC 6241 Section 7.2 specifies the order:
// 1. target
// 2. default-operation (optional)
// 3. test-option (optional)
// 4. error-option (optional)
// 5. config
targetIdx := strings.Index(xml, "<target>")
defaultOpIdx := strings.Index(xml, "<default-operation>")
testOptIdx := strings.Index(xml, "<test-option>")
errorOptIdx := strings.Index(xml, "<error-option>")
configIdx := strings.Index(xml, "<config>")
if targetIdx == -1 || defaultOpIdx == -1 || testOptIdx == -1 || errorOptIdx == -1 || configIdx == -1 {
t.Fatalf("missing required elements in XML: %s", xml)
}
// Verify order
if targetIdx >= defaultOpIdx {
t.Error("target should come before default-operation")
}
if defaultOpIdx >= testOptIdx {
t.Error("default-operation should come before test-option")
}
if testOptIdx >= errorOptIdx {
t.Error("test-option should come before error-option")
}
if errorOptIdx >= configIdx {
t.Error("error-option should come before config")
}
}
// TestBuildEditConfigXMLEmptyValues tests handling of empty values
func TestBuildEditConfigXMLEmptyValues(t *testing.T) {
client := &Client{}
req := &Req{
Target: "candidate",
Config: "",
DefaultOperation: "",
TestOption: "",
ErrorOption: "",
}
xml := client.buildEditConfigXML(req)
// Empty optional fields should not be included
if strings.Contains(xml, "<default-operation>") {
t.Error("empty default-operation should not be included in XML")
}
if strings.Contains(xml, "<test-option>") {
t.Error("empty test-option should not be included in XML")
}
if strings.Contains(xml, "<error-option>") {
t.Error("empty error-option should not be included in XML")
}
// Empty config should still have config element
if !strings.Contains(xml, "<config></config>") {
t.Error("config element should be present even when empty")
}
}
// TestEditConfigOptionValidValues tests valid values for edit-config options
func TestEditConfigOptionValidValues(t *testing.T) {
tests := []struct {
name string
fieldName string
value string
valid bool
}{
// DefaultOperation valid values (RFC 6241 Section 7.2)
{"default-op merge", "DefaultOperation", "merge", true},
{"default-op replace", "DefaultOperation", "replace", true},
{"default-op none", "DefaultOperation", "none", true},
// TestOption valid values (RFC 6241 Section 7.2)
{"test-opt test-then-set", "TestOption", "test-then-set", true},
{"test-opt set", "TestOption", "set", true},
{"test-opt test-only", "TestOption", "test-only", true},
// ErrorOption valid values (RFC 6241 Section 7.2)
{"error-opt stop-on-error", "ErrorOption", "stop-on-error", true},
{"error-opt continue-on-error", "ErrorOption", "continue-on-error", true},
{"error-opt rollback-on-error", "ErrorOption", "rollback-on-error", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
client := &Client{}
req := &Req{
Target: "candidate",
Config: "<test/>",
}
switch tt.fieldName {
case "DefaultOperation":
req.DefaultOperation = tt.value
case "TestOption":
req.TestOption = tt.value
case "ErrorOption":
req.ErrorOption = tt.value
}
xml := client.buildEditConfigXML(req)
if tt.valid {
if !strings.Contains(xml, tt.value) {
t.Errorf("expected XML to contain valid value %q", tt.value)
}
}
})
}
}
// ExampleNewClient demonstrates creating a NETCONF client with authentication.
func ExampleNewClient() {
// This example demonstrates the pattern for creating a NETCONF client
// In production, replace with actual device credentials
fmt.Println("Creating a NETCONF client:")
fmt.Println(" - Specify host address")
fmt.Println(" - Provide authentication (username/password or SSH key)")
fmt.Println(" - Configure port (default: 830)")
fmt.Println(" - Set retry and timeout options")
fmt.Println("")
fmt.Println("Example:")
fmt.Println(" client, err := netconf.NewClient(")
fmt.Println(" \"192.168.1.1\",")
fmt.Println(" netconf.Username(\"admin\"),")
fmt.Println(" netconf.Password(\"secret\"),")
fmt.Println(" netconf.Port(830),")
fmt.Println(" )")
// Output: Creating a NETCONF client:
// - Specify host address
// - Provide authentication (username/password or SSH key)
// - Configure port (default: 830)
// - Set retry and timeout options
//
// Example:
// client, err := netconf.NewClient(
// "192.168.1.1",
// netconf.Username("admin"),
// netconf.Password("secret"),
// netconf.Port(830),
// )
}
// ExampleClient_Get demonstrates retrieving operational data with a filter.
func ExampleClient_Get() {
// This example demonstrates the Get operation pattern
// In production, replace with actual device connection
// Create filter for interfaces
filter := SubtreeFilter("<interfaces/>")
fmt.Printf("Created filter for interfaces\n")
// The Get operation would retrieve both config and state data
fmt.Println("Get retrieves operational and configuration data")