forked from k8snetworkplumbingwg/linuxptp-daemon
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhardwareconfig_test.go
More file actions
1371 lines (1194 loc) · 48.4 KB
/
hardwareconfig_test.go
File metadata and controls
1371 lines (1194 loc) · 48.4 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
package hardwareconfig
import (
"fmt"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"testing"
"github.com/stretchr/testify/assert"
dpll "github.com/k8snetworkplumbingwg/linuxptp-daemon/pkg/dpll-netlink"
ptpv1 "github.com/k8snetworkplumbingwg/ptp-operator/api/v1"
ptpv2alpha1 "github.com/k8snetworkplumbingwg/ptp-operator/api/v2alpha1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/client-go/kubernetes/scheme"
)
func TestApplyHardwareConfigsForProfile(t *testing.T) {
// Set up mock PTP device resolver for testing
SetupMockPtpDeviceResolver()
defer TeardownMockPtpDeviceResolver()
// Set up mock DPLL pins from test file for testing
mockErr := SetupMockDpllPinsForTests()
if mockErr != nil {
t.Logf("Warning: Failed to setup mock DPLL pins: %v", mockErr)
// Continue with test as DPLL pins are optional
}
defer TeardownMockDpllPinsForTests()
tests := []struct {
name string
testDataFile string
profileName string
}{
{
name: "successful hardware config application",
testDataFile: "testdata/wpc-hwconfig.yaml",
profileName: "01-tbc-tr",
},
{
name: "no matching profile",
testDataFile: "testdata/wpc-hwconfig.yaml",
profileName: "non-existent-profile",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
SetupMockPtpDeviceResolver()
defer TeardownMockPtpDeviceResolver()
if err := SetupMockDpllPinsForTests(); err != nil {
t.Fatalf("failed to set up mock DPLL pins: %v", err)
}
defer TeardownMockDpllPinsForTests()
// Set up mock command executor for GetClockIDFromInterface
mockCmd := NewMockCommandExecutor()
mockCmd.SetResponse("ethtool", []string{"-i", "ens4f0"}, "driver: ice\nbus-info: 0000:17:00.0")
mockCmd.SetResponse("devlink", []string{"dev", "info", "pci/0000:17:00.0"}, "serial_number 50-7c-6f-ff-ff-5c-4a-e8")
mockCmd.SetResponse("ethtool", []string{"-i", "ens8f0"}, "driver: ice\nbus-info: 0000:51:00.0")
mockCmd.SetResponse("devlink", []string{"dev", "info", "pci/0000:51:00.0"}, "serial_number 50-7c-6f-ff-ff-1f-b1-b8")
SetCommandExecutor(mockCmd)
defer ResetCommandExecutor()
// Load test data
hwConfig, err := loadHardwareConfigFromFile(tt.testDataFile)
assert.NoError(t, err)
assert.NotNil(t, hwConfig)
// Create hardware config manager and add test data
hcm := NewHardwareConfigManager()
defer hcm.resetExecutors()
hcm.overrideExecutors(nil, func(_, _ string) error { return nil })
var appliedPins []dpll.PinParentDeviceCtl
hcm.overrideExecutors(func(cmds []dpll.PinParentDeviceCtl) error {
snapshot := make([]dpll.PinParentDeviceCtl, len(cmds))
copy(snapshot, cmds)
appliedPins = append(appliedPins, snapshot...)
return nil
}, func(_, _ string) error {
return nil
})
err = hcm.UpdateHardwareConfig([]ptpv2alpha1.HardwareConfig{*hwConfig})
assert.NoError(t, err)
// Create a mock PTP profile
profile := &ptpv1.PtpProfile{
Name: &tt.profileName,
}
// Test the function
err = hcm.ApplyHardwareConfigsForProfile(profile)
assert.NoError(t, err)
})
}
}
func TestHardwareConfigManagerOperations(t *testing.T) {
// Set up mock PTP device resolver for testing
SetupMockPtpDeviceResolver()
defer TeardownMockPtpDeviceResolver()
// Set up mock DPLL pins for testing
mockErr := SetupMockDpllPinsForTests()
if mockErr != nil {
t.Logf("Warning: Failed to setup mock DPLL pins: %v", mockErr)
// Continue with test as DPLL pins are optional
}
defer TeardownMockDpllPinsForTests()
// Set up mock command executor for GetClockIDFromInterface
mockCmd := NewMockCommandExecutor()
mockCmd.SetResponse("ethtool", []string{"-i", "ens4f0"}, "driver: ice\nbus-info: 0000:17:00.0")
mockCmd.SetResponse("devlink", []string{"dev", "info", "pci/0000:17:00.0"}, "serial_number 50-7c-6f-ff-ff-5c-4a-e8")
mockCmd.SetResponse("ethtool", []string{"-i", "ens8f0"}, "driver: ice\nbus-info: 0000:51:00.0")
mockCmd.SetResponse("devlink", []string{"dev", "info", "pci/0000:51:00.0"}, "serial_number 50-7c-6f-ff-ff-1f-b1-b8")
SetCommandExecutor(mockCmd)
defer ResetCommandExecutor()
hcm := NewHardwareConfigManager()
// Test initial state
assert.Equal(t, 0, hcm.GetHardwareConfigCount())
// Load test data
hwConfig, err := loadHardwareConfigFromFile("testdata/wpc-hwconfig.yaml")
assert.NoError(t, err)
assert.NotNil(t, hwConfig)
// Test UpdateHardwareConfig
err = hcm.UpdateHardwareConfig([]ptpv2alpha1.HardwareConfig{*hwConfig})
assert.NoError(t, err)
assert.Equal(t, 1, hcm.GetHardwareConfigCount())
// Test HasHardwareConfigForProfile
profile := &ptpv1.PtpProfile{
Name: stringPtr("01-tbc-tr"),
}
assert.True(t, hcm.HasHardwareConfigForProfile(profile))
// Test with non-existent profile
profile.Name = stringPtr("non-existent")
assert.False(t, hcm.HasHardwareConfigForProfile(profile))
// Test GetHardwareConfigsForProfile
profile.Name = stringPtr("01-tbc-tr")
configs := hcm.GetHardwareConfigsForProfile(profile)
assert.Len(t, configs, 1)
assert.Equal(t, "tbc", *configs[0].Name)
// Test ClearHardwareConfigs
hcm.ClearHardwareConfigs()
assert.Equal(t, 0, hcm.GetHardwareConfigCount())
assert.False(t, hcm.HasHardwareConfigForProfile(profile))
}
func TestHardwareConfigManagerEmptyConfigs(t *testing.T) {
// Set up mock DPLL pins from test file for testing
mockErr := SetupMockDpllPinsForTests()
if mockErr != nil {
t.Logf("Warning: Failed to setup mock DPLL pins: %v", mockErr)
// Continue with test as DPLL pins are optional
}
defer TeardownMockDpllPinsForTests()
hcm := NewHardwareConfigManager()
// Test with empty configs
err := hcm.UpdateHardwareConfig([]ptpv2alpha1.HardwareConfig{})
assert.NoError(t, err)
assert.Equal(t, 0, hcm.GetHardwareConfigCount())
// Test with nil profile name
profile := &ptpv1.PtpProfile{}
assert.False(t, hcm.HasHardwareConfigForProfile(profile))
configs := hcm.GetHardwareConfigsForProfile(profile)
assert.Len(t, configs, 0)
}
// loadHardwareConfigFromFile loads a HardwareConfig from a YAML file
func loadHardwareConfigFromFile(filename string) (*ptpv2alpha1.HardwareConfig, error) {
data, err := os.ReadFile(filename)
if err != nil {
return nil, fmt.Errorf("failed to read file %s: %v", filename, err)
}
// Register the HardwareConfig types with the scheme
_ = ptpv2alpha1.AddToScheme(scheme.Scheme)
// Create a decoder
decode := serializer.NewCodecFactory(scheme.Scheme).UniversalDeserializer().Decode
// Decode the YAML
obj, _, err := decode(data, nil, nil)
if err != nil {
return nil, fmt.Errorf("failed to decode YAML: %v", err)
}
hwConfig, ok := obj.(*ptpv2alpha1.HardwareConfig)
if !ok {
return nil, fmt.Errorf("decoded object is not a HardwareConfig")
}
return hwConfig, nil
}
// stringPtr returns a pointer to a string
func stringPtr(s string) *string {
return &s
}
func TestLoadHardwareConfigFromFile(t *testing.T) {
// Test successful loading
hwConfig, err := loadHardwareConfigFromFile("testdata/wpc-hwconfig.yaml")
assert.NoError(t, err)
assert.NotNil(t, hwConfig)
assert.Equal(t, "test", hwConfig.Name)
assert.Equal(t, "01-tbc-tr", hwConfig.Spec.RelatedPtpProfileName)
assert.Equal(t, "tbc", *hwConfig.Spec.Profile.Name)
// Test with non-existent file
_, err = loadHardwareConfigFromFile("testdata/non-existent.yaml")
assert.Error(t, err)
assert.Contains(t, err.Error(), "failed to read file")
}
func TestNewHardwareConfigManager(t *testing.T) {
hcm := NewHardwareConfigManager()
assert.NotNil(t, hcm)
assert.Equal(t, 0, hcm.GetHardwareConfigCount())
}
func TestPTPStateDetector(t *testing.T) {
// Set up mock PTP device resolver for testing
SetupMockPtpDeviceResolver()
defer TeardownMockPtpDeviceResolver()
// Set up mock DPLL pins for testing
mockErr := SetupMockDpllPinsForTests()
if mockErr != nil {
t.Logf("Warning: Failed to setup mock DPLL pins: %v", mockErr)
// Continue with test as DPLL pins are optional
}
defer TeardownMockDpllPinsForTests()
// Set up mock command executor for GetClockIDFromInterface
mockCmd := NewMockCommandExecutor()
mockCmd.SetResponse("ethtool", []string{"-i", "ens4f0"}, "driver: ice\nbus-info: 0000:17:00.0")
mockCmd.SetResponse("devlink", []string{"dev", "info", "pci/0000:17:00.0"}, "serial_number 50-7c-6f-ff-ff-5c-4a-e8")
mockCmd.SetResponse("ethtool", []string{"-i", "ens8f0"}, "driver: ice\nbus-info: 0000:51:00.0")
mockCmd.SetResponse("devlink", []string{"dev", "info", "pci/0000:51:00.0"}, "serial_number 50-7c-6f-ff-ff-1f-b1-b8")
SetCommandExecutor(mockCmd)
defer ResetCommandExecutor()
// Load test data
hwConfig, err := loadHardwareConfigFromFile("testdata/wpc-hwconfig.yaml")
assert.NoError(t, err)
assert.NotNil(t, hwConfig)
// Create hardware config manager and add test data
hcm := NewHardwareConfigManager()
err = hcm.UpdateHardwareConfig([]ptpv2alpha1.HardwareConfig{*hwConfig})
assert.NoError(t, err)
// Create PTP state detector
psd := NewPTPStateDetector(hcm)
// Test GetMonitoredPorts
monitoredPorts := psd.GetMonitoredPorts()
assert.Contains(t, monitoredPorts, "ens4f1")
// Test GetBehaviorRules
conditions := psd.GetBehaviorRules()
assert.NotEmpty(t, conditions)
}
func TestDetectStateChange(t *testing.T) {
// Set up mock PTP device resolver for testing
SetupMockPtpDeviceResolver()
defer TeardownMockPtpDeviceResolver()
// Set up mock DPLL pins for testing
mockErr := SetupMockDpllPinsForTests()
if mockErr != nil {
t.Logf("Warning: Failed to setup mock DPLL pins: %v", mockErr)
// Continue with test as DPLL pins are optional
}
defer TeardownMockDpllPinsForTests()
// Set up mock command executor for GetClockIDFromInterface
mockCmd := NewMockCommandExecutor()
mockCmd.SetResponse("ethtool", []string{"-i", "ens4f0"}, "driver: ice\nbus-info: 0000:17:00.0")
mockCmd.SetResponse("devlink", []string{"dev", "info", "pci/0000:17:00.0"}, "serial_number 50-7c-6f-ff-ff-5c-4a-e8")
mockCmd.SetResponse("ethtool", []string{"-i", "ens8f0"}, "driver: ice\nbus-info: 0000:51:00.0")
mockCmd.SetResponse("devlink", []string{"dev", "info", "pci/0000:51:00.0"}, "serial_number 50-7c-6f-ff-ff-1f-b1-b8")
SetCommandExecutor(mockCmd)
defer ResetCommandExecutor()
// Load test data
hwConfig, err := loadHardwareConfigFromFile("testdata/wpc-hwconfig.yaml")
assert.NoError(t, err)
// Create hardware config manager and add test data
hcm := NewHardwareConfigManager()
err = hcm.UpdateHardwareConfig([]ptpv2alpha1.HardwareConfig{*hwConfig})
assert.NoError(t, err)
// Create PTP state detector
psd := NewPTPStateDetector(hcm)
t.Run("individual_test_cases", func(t *testing.T) {
testCases := []struct {
name string
logLine string
expected string
}{
{
name: "locked condition",
logLine: "ptp4l[1716691.337]: [ptp4l.1.config:5] port 1 (ens4f1): UNCALIBRATED to SLAVE on MASTER_CLOCK_SELECTED",
expected: "locked",
},
{
name: "lost condition",
logLine: "ptp4l[1031716.424]: [ptp4l.0.config:5] port 1 (ens4f1): SLAVE to FAULT_DETECTED on FAULT_DETECTED",
expected: "lost",
},
{
name: "non-monitored port - should return empty",
logLine: "ptp4l[1031716.424]: [ptp4l.0.config:5] port 2 (ens8f0): UNCALIBRATED to SLAVE on MASTER_CLOCK_SELECTED",
expected: "", // ens8f0 is not in PTPTimeReceivers for the test data
},
{
name: "non-ptp4l log - should return empty",
logLine: "some other log message",
expected: "",
},
{
name: "irrelevant ptp4l transition - should return empty",
logLine: "[ptp4l.0.config:5] port 1 (ens4f1): LISTENING to MASTER on INITIALIZATION",
expected: "",
},
{
name: "user reported failing case - should work now",
logLine: "ptp4l[1720295.764]: [ptp4l.1.config:5] port 1 (ens4f1): UNCALIBRATED to SLAVE on MASTER_CLOCK_SELECTED",
expected: "locked",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
result := psd.DetectStateChange(tc.logLine)
assert.Equal(t, tc.expected, result, "State change detection should match expected result")
if result != "" {
t.Logf("✅ Detected %s condition from log line", result)
}
})
}
})
t.Run("real_log_file_processing", func(t *testing.T) {
// Read the real log file
logData, readErr := os.ReadFile("testdata/log2.txt")
assert.NoError(t, readErr, "Should be able to read log2.txt")
// Split log into lines
lines := strings.Split(string(logData), "\n")
// Track detected state changes
var detectedChanges []struct {
lineNum int
condition string
logLine string
}
// Process each line
for i, line := range lines {
if strings.TrimSpace(line) == "" {
continue
}
result := psd.DetectStateChange(line)
if result != "" {
detectedChanges = append(detectedChanges, struct {
lineNum int
condition string
logLine string
}{
lineNum: i + 1, // 1-based line numbers
condition: result,
logLine: line,
})
}
}
// Log the results
t.Logf("=== REAL LOG FILE PROCESSING RESULTS ===")
t.Logf("Total lines processed: %d", len(lines))
t.Logf("State changes detected: %d", len(detectedChanges))
for _, change := range detectedChanges {
t.Logf("Line %d: %s condition", change.lineNum, change.condition)
t.Logf(" Log line: %s", change.logLine)
}
// Verify we detected some state changes (real logs should have transitions)
if len(detectedChanges) > 0 {
t.Logf("✅ Successfully detected %d state changes in real log file", len(detectedChanges))
// Count locked vs lost conditions
lockedCount := 0
lostCount := 0
for _, change := range detectedChanges {
switch change.condition {
case "locked":
lockedCount++
case "lost":
lostCount++
}
}
t.Logf(" Locked conditions: %d", lockedCount)
t.Logf(" Lost conditions: %d", lostCount)
} else {
t.Logf("ℹ️ No state changes detected in log file (this may be expected if log contains no relevant transitions)")
}
})
}
func TestNewPTPStateDetector(t *testing.T) {
hcm := NewHardwareConfigManager()
psd := NewPTPStateDetector(hcm)
assert.NotNil(t, psd)
assert.NotNil(t, psd.hcm)
}
// TestApplyConditionDesiredStatesWithRealData tests applyConditionDesiredStatesByType using actual hardware config YAML data
//
//nolint:gocyclo // test complexity is acceptable
func TestApplyConditionDesiredStatesWithRealData(t *testing.T) {
// Set up mock command executor for GetClockIDFromInterface
mockCmd := NewMockCommandExecutor()
mockCmd.SetResponse("ethtool", []string{"-i", "ens4f0"}, "driver: ice\nbus-info: 0000:17:00.0")
mockCmd.SetResponse("devlink", []string{"dev", "info", "pci/0000:17:00.0"}, "serial_number 50-7c-6f-ff-ff-5c-4a-e8")
mockCmd.SetResponse("ethtool", []string{"-i", "ens8f0"}, "driver: ice\nbus-info: 0000:51:00.0")
mockCmd.SetResponse("devlink", []string{"dev", "info", "pci/0000:51:00.0"}, "serial_number 50-7c-6f-ff-ff-1f-b1-b8")
SetCommandExecutor(mockCmd)
defer ResetCommandExecutor()
// Load the real hardware configuration from YAML
hwConfig, err := loadHardwareConfigFromFile("testdata/wpc-hwconfig.yaml")
if err != nil {
t.Fatalf("Failed to load hardware config: %v", err)
}
// Create a HardwareConfigManager
hcm := &HardwareConfigManager{
hardwareConfigs: []enrichedHardwareConfig{
{HardwareConfig: *hwConfig},
},
}
// Extract the clock chain from the loaded config
clockChain := hwConfig.Spec.Profile.ClockChain
profileName := *hwConfig.Spec.Profile.Name
t.Logf("Testing with real hardware config: %s", hwConfig.Name)
t.Logf("Profile: %s", profileName)
t.Logf("Clock chain has %d conditions", len(clockChain.Behavior.Conditions))
// Validate that source configurations reference subsystems
if clockChain.Behavior != nil && len(clockChain.Behavior.Sources) > 0 {
t.Logf("Validating %d behavior sources:", len(clockChain.Behavior.Sources))
for i, source := range clockChain.Behavior.Sources {
t.Logf(" Source %d: %s (Subsystem: %s)", i+1, source.Name, source.Subsystem)
}
}
// Test each condition from the real hardware config
for i, condition := range clockChain.Behavior.Conditions {
t.Run(fmt.Sprintf("condition_%d_%s", i, condition.Name), func(t *testing.T) {
t.Logf("Testing condition: %s", condition.Name)
t.Logf(" Triggers: %d", len(condition.Triggers))
t.Logf(" Desired states: %d", len(condition.DesiredStates))
// Log details about the condition
for j, trigger := range condition.Triggers {
t.Logf(" Trigger %d: %s (%s)", j+1, trigger.SourceName, trigger.ConditionType)
}
for j, desiredState := range condition.DesiredStates {
if desiredState.DPLL != nil {
t.Logf(" Desired state %d: DPLL - Subsystem: %s, Board: %s",
j+1, desiredState.DPLL.Subsystem, desiredState.DPLL.BoardLabel)
if desiredState.DPLL.EEC != nil {
if desiredState.DPLL.EEC.Priority != nil {
t.Logf(" EEC Priority: %d", *desiredState.DPLL.EEC.Priority)
}
if desiredState.DPLL.EEC.State != "" {
t.Logf(" EEC State: %s", desiredState.DPLL.EEC.State)
}
}
if desiredState.DPLL.PPS != nil {
if desiredState.DPLL.PPS.Priority != nil {
t.Logf(" PPS Priority: %d", *desiredState.DPLL.PPS.Priority)
}
if desiredState.DPLL.PPS.State != "" {
t.Logf(" PPS State: %s", desiredState.DPLL.PPS.State)
}
}
}
if desiredState.SysFS != nil {
t.Logf(" Desired state %d: SysFS - Path: %s, Value: %s",
j+1, desiredState.SysFS.Path, desiredState.SysFS.Value)
if desiredState.SysFS.SourceName != "" {
t.Logf(" Source: %s", desiredState.SysFS.SourceName)
}
}
}
// Create a mock enriched hardware config for testing
mockEnrichedConfig := &enrichedHardwareConfig{
HardwareConfig: *hwConfig,
sysFSCommands: make(map[string][]SysFSCommand),
dpllPinCommands: make(map[string][]dpll.PinParentDeviceCtl),
}
// Determine the condition type for this condition
var conditionType string
if len(condition.Triggers) == 0 {
conditionType = ConditionTypeInit
} else {
conditionType = condition.Triggers[0].ConditionType
}
// Apply the condition's desired states
applyErr := hcm.applyConditionDesiredStatesByType(condition, conditionType, profileName, mockEnrichedConfig)
// All conditions should apply successfully since the YAML is well-formed
if applyErr != nil {
t.Errorf("Failed to apply condition '%s' (type: %s): %v", condition.Name, conditionType, applyErr)
} else {
t.Logf("✅ Successfully applied condition '%s' (type: %s) with %d desired states",
condition.Name, conditionType, len(condition.DesiredStates))
}
})
}
// Test specific conditions by name
testCases := []struct {
conditionName string
expectedStates int
description string
}{
{
conditionName: "Initialize T-BC",
expectedStates: 5,
description: "Should have initialization states for GNSS and CVL pins plus sysFS config",
},
{
conditionName: "PTP Source Active",
expectedStates: 2,
description: "Should have active configuration for CVL pins",
},
{
conditionName: "PTP Source Lost - Leader Holdover",
expectedStates: 2,
description: "Should have holdover configuration for CVL pins",
},
}
for _, tc := range testCases {
t.Run(fmt.Sprintf("validate_%s", strings.ReplaceAll(tc.conditionName, " ", "_")), func(t *testing.T) {
// Find the condition by name
var targetCondition *ptpv2alpha1.Condition
for _, condition := range clockChain.Behavior.Conditions {
if condition.Name == tc.conditionName {
targetCondition = &condition
break
}
}
if targetCondition == nil {
t.Fatalf("Condition '%s' not found in hardware config", tc.conditionName)
return // unreachable but satisfies staticcheck
}
// Validate the expected number of desired states
// Note: The actual count may vary slightly due to hardware-specific defaults being applied
actualStates := len(targetCondition.DesiredStates)
if actualStates < tc.expectedStates {
t.Errorf("Expected at least %d desired states for '%s', got %d",
tc.expectedStates, tc.conditionName, actualStates)
}
t.Logf("✅ %s", tc.description)
t.Logf(" Found %d desired states (expected at least %d)", actualStates, tc.expectedStates)
})
}
// Validate the hardware config structure
t.Run("validate_hardware_config_structure", func(t *testing.T) {
// Check that we have the expected sources
sources := clockChain.Behavior.Sources
if len(sources) != 1 {
t.Errorf("Expected 1 source, got %d", len(sources))
} else {
source := sources[0]
if source.Name != "PTP" {
t.Errorf("Expected source name 'PTP', got '%s'", source.Name)
}
if source.SourceType != "ptpTimeReceiver" {
t.Errorf("Expected source type 'ptpTimeReceiver', got '%s'", source.SourceType)
}
if len(source.PTPTimeReceivers) != 1 || source.PTPTimeReceivers[0] != "ens4f1" {
t.Errorf("Expected PTP time receiver 'ens4f1', got %v", source.PTPTimeReceivers)
}
t.Logf("✅ Source configuration validated: %s (%s) with interface %s",
source.Name, source.SourceType, source.PTPTimeReceivers[0])
}
// Check subsystems have network interfaces defined
if len(clockChain.Structure) > 0 {
for _, subsystem := range clockChain.Structure {
if subsystem.DPLL.NetworkInterface == "" && (len(subsystem.Ethernet) == 0 || len(subsystem.Ethernet[0].Ports) == 0) {
t.Errorf("Subsystem %s must have NetworkInterface or Ethernet ports", subsystem.Name)
} else {
t.Logf("✅ Subsystem %s has network interface for clock ID resolution", subsystem.Name)
}
}
}
})
}
// TestApplyDefaultAndInitConditions tests the applyDefaultAndInitConditions function
func TestApplyDefaultAndInitConditions(t *testing.T) {
// Set up mock PTP device resolver for testing
SetupMockPtpDeviceResolver()
defer TeardownMockPtpDeviceResolver()
// Set up mock DPLL pins for testing
mockErr := SetupMockDpllPinsForTests()
if mockErr != nil {
t.Logf("Warning: Failed to setup mock DPLL pins: %v", mockErr)
// Continue with test as DPLL pins are optional
}
defer TeardownMockDpllPinsForTests()
// Set up mock command executor for GetClockIDFromInterface
mockCmd := NewMockCommandExecutor()
mockCmd.SetResponse("ethtool", []string{"-i", "ens4f0"}, "driver: ice\nbus-info: 0000:17:00.0")
mockCmd.SetResponse("devlink", []string{"dev", "info", "pci/0000:17:00.0"}, "serial_number 50-7c-6f-ff-ff-5c-4a-e8")
mockCmd.SetResponse("ethtool", []string{"-i", "ens8f0"}, "driver: ice\nbus-info: 0000:51:00.0")
mockCmd.SetResponse("devlink", []string{"dev", "info", "pci/0000:51:00.0"}, "serial_number 50-7c-6f-ff-ff-1f-b1-b8")
SetCommandExecutor(mockCmd)
defer ResetCommandExecutor()
// Load test hardware config
hwConfig, err := loadHardwareConfigFromFile("testdata/wpc-hwconfig.yaml")
if err != nil {
t.Fatalf("Failed to load hardware config: %v", err)
}
// Clock IDs are now resolved dynamically - no aliases needed
// Create hardware config manager
hcm := NewHardwareConfigManager()
err = hcm.UpdateHardwareConfig([]ptpv2alpha1.HardwareConfig{*hwConfig})
if err != nil {
t.Fatalf("Failed to update hardware config: %v", err)
}
profileName := "test-profile"
clockChain := hwConfig.Spec.Profile.ClockChain
tests := []struct {
name string
clockChain *ptpv2alpha1.ClockChain
profileName string
expectError bool
expectedDefaultCount int
expectedInitCount int
}{
{
name: "valid clock chain with conditions",
clockChain: clockChain,
profileName: profileName,
expectError: false,
expectedDefaultCount: 0, // No explicit default conditions in test data
expectedInitCount: 1, // "Initialize T-BC" condition has empty sources, treated as init
},
{
name: "nil behavior section",
clockChain: &ptpv2alpha1.ClockChain{},
profileName: profileName,
expectError: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create a mock enriched hardware config for testing
mockEnrichedConfig := &enrichedHardwareConfig{
HardwareConfig: ptpv2alpha1.HardwareConfig{},
sysFSCommands: make(map[string][]SysFSCommand),
}
// Test the function
testErr := hcm.applyDefaultAndInitConditions(tt.clockChain, tt.profileName, mockEnrichedConfig)
// Verify error expectation
if tt.expectError {
assert.Error(t, testErr)
} else {
assert.NoError(t, testErr)
}
// If we have behavior section, verify condition extraction
if tt.clockChain.Behavior != nil {
defaultConditions := hcm.extractConditionsByType(tt.clockChain.Behavior.Conditions, "default")
initConditions := hcm.extractConditionsByType(tt.clockChain.Behavior.Conditions, "init")
assert.Equal(t, tt.expectedDefaultCount, len(defaultConditions), "Default conditions count mismatch")
assert.Equal(t, tt.expectedInitCount, len(initConditions), "Init conditions count mismatch")
t.Logf("✅ Found %d default conditions and %d init conditions",
len(defaultConditions), len(initConditions))
}
})
}
}
// TestExtractConditionsByType tests the extractConditionsByType function
func TestExtractConditionsByType(t *testing.T) {
// Set up mock DPLL pins for testing
mockErr := SetupMockDpllPinsForTests()
if mockErr != nil {
t.Logf("Warning: Failed to setup mock DPLL pins: %v", mockErr)
// Continue with test as DPLL pins are optional
}
defer TeardownMockDpllPinsForTests()
hcm := NewHardwareConfigManager()
// Create test conditions
conditions := []ptpv2alpha1.Condition{
{
Name: "Default Condition",
Triggers: []ptpv2alpha1.SourceState{
{SourceName: "TestSource", ConditionType: ConditionTypeDefault},
},
},
{
Name: "Init Condition (Empty Sources)",
Triggers: []ptpv2alpha1.SourceState{}, // Empty sources should be treated as init
},
{
Name: "Locked Condition",
Triggers: []ptpv2alpha1.SourceState{
{SourceName: "TestSource", ConditionType: ConditionTypeLocked},
},
},
{
Name: "Lost Condition",
Triggers: []ptpv2alpha1.SourceState{
{SourceName: "TestSource", ConditionType: ConditionTypeLost},
},
},
}
tests := []struct {
name string
conditionType string
expectedCount int
expectedNames []string
}{
{
name: "extract default conditions",
conditionType: ConditionTypeDefault,
expectedCount: 1,
expectedNames: []string{"Default Condition"},
},
{
name: "extract init conditions",
conditionType: ConditionTypeInit,
expectedCount: 1,
expectedNames: []string{"Init Condition (Empty Sources)"},
},
{
name: "extract locked conditions",
conditionType: ConditionTypeLocked,
expectedCount: 1,
expectedNames: []string{"Locked Condition"},
},
{
name: "extract lost conditions",
conditionType: ConditionTypeLost,
expectedCount: 1,
expectedNames: []string{"Lost Condition"},
},
{
name: "extract non-existent condition type",
conditionType: "nonexistent",
expectedCount: 0,
expectedNames: []string{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := hcm.extractConditionsByType(conditions, tt.conditionType)
assert.Equal(t, tt.expectedCount, len(result), "Condition count mismatch")
// Verify condition names
resultNames := make([]string, len(result))
for i, condition := range result {
resultNames[i] = condition.Name
}
for _, expectedName := range tt.expectedNames {
assert.Contains(t, resultNames, expectedName, "Expected condition not found")
}
t.Logf("✅ Found %d conditions of type '%s': %v",
len(result), tt.conditionType, resultNames)
})
}
}
// TestResolveSysFSPtpDevice tests the resolveSysFSPtpDevice function with mock file system
func TestResolveSysFSPtpDevice(t *testing.T) {
// Create a temporary directory structure for testing
tempDir := t.TempDir()
// Create mock PTP device directories and files
ptpDeviceDir := filepath.Join(tempDir, "sys", "class", "net", "eth0", "device", "ptp")
if err := os.MkdirAll(ptpDeviceDir, 0755); err != nil {
t.Fatalf("Failed to create test directory structure: %v", err)
}
// Create mock PTP devices
ptp0Dir := filepath.Join(ptpDeviceDir, "ptp0")
ptp1Dir := filepath.Join(ptpDeviceDir, "ptp1")
ptp2Dir := filepath.Join(ptpDeviceDir, "ptp2")
if err := os.MkdirAll(ptp0Dir, 0755); err != nil {
t.Fatalf("Failed to create ptp0 directory: %v", err)
}
if err := os.MkdirAll(ptp1Dir, 0755); err != nil {
t.Fatalf("Failed to create ptp1 directory: %v", err)
}
if err := os.MkdirAll(ptp2Dir, 0755); err != nil {
t.Fatalf("Failed to create ptp2 directory: %v", err)
}
// Create test files with different permissions
writableFile := filepath.Join(ptp0Dir, "period")
readOnlyFile := filepath.Join(ptp1Dir, "period")
anotherWritableFile := filepath.Join(ptp2Dir, "period")
// Create writable files (0644 has write permission for owner)
if err := os.WriteFile(writableFile, []byte("test"), 0644); err != nil {
t.Fatalf("Failed to create writable test file: %v", err)
}
if err := os.WriteFile(anotherWritableFile, []byte("test"), 0644); err != nil {
t.Fatalf("Failed to create another writable test file: %v", err)
}
// Create read-only file (0444 has no write permission)
if err := os.WriteFile(readOnlyFile, []byte("test"), 0444); err != nil {
t.Fatalf("Failed to create read-only test file: %v", err)
}
// Create HardwareConfigManager for testing
hcm := &HardwareConfigManager{
hardwareConfigs: make([]enrichedHardwareConfig, 0),
}
testCases := []struct {
name string
interfacePath string
expectedPaths []string
expectedError bool
description string
}{
{
name: "no_ptp_placeholder",
interfacePath: "/sys/class/net/eth0/carrier",
expectedPaths: []string{"/sys/class/net/eth0/carrier"},
expectedError: false,
description: "Should return path as-is when no ptp* placeholder is present",
},
{
name: "valid_ptp_devices_found",
interfacePath: filepath.Join(tempDir, "sys/class/net/eth0/device/ptp/ptp*/period"),
expectedPaths: []string{
filepath.Join(tempDir, "sys/class/net/eth0/device/ptp/ptp0/period"),
filepath.Join(tempDir, "sys/class/net/eth0/device/ptp/ptp2/period"),
},
expectedError: false,
description: "Should return all writable PTP device paths",
},
{
name: "nonexistent_directory",
interfacePath: filepath.Join(tempDir, "nonexistent/ptp/ptp*/period"),
expectedPaths: nil,
expectedError: true,
description: "Should return error when PTP device directory doesn't exist",
},
{
name: "no_writable_files",
interfacePath: filepath.Join(tempDir, "sys/class/net/eth0/device/ptp/ptp*/nonexistent"),
expectedPaths: nil,
expectedError: true,
description: "Should return error when no writable files are found",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Logf("Testing: %s", tc.description)
result, testErr := hcm.resolveSysFSPtpDevice(tc.interfacePath)
if tc.expectedError {
if testErr == nil {
t.Errorf("Expected error but got none")
} else {
t.Logf("✅ Got expected error: %v", testErr)
}
} else {
if testErr != nil {
t.Errorf("Unexpected error: %v", testErr)
} else {
// Sort both slices for comparison since order might vary
sort.Strings(result)
sort.Strings(tc.expectedPaths)
if !reflect.DeepEqual(result, tc.expectedPaths) {
t.Errorf("Expected paths: %v, Got: %v", tc.expectedPaths, result)
} else {
t.Logf("✅ Successfully resolved %d PTP device paths", len(result))
for i, path := range result {
t.Logf(" Path %d: %s", i+1, path)
}
}
}
}
})
}
// Additional test for edge cases
t.Run("edge_cases", func(t *testing.T) {
// Test empty path
result, edgeErr := hcm.resolveSysFSPtpDevice("")
if edgeErr != nil {
t.Errorf("Empty path should not return error, got: %v", edgeErr)
}
if len(result) != 1 || result[0] != "" {
t.Errorf("Empty path should return empty string, got: %v", result)
}
// Test path with multiple ptp* placeholders (edge case)
complexPath := filepath.Join(tempDir, "sys/class/net/eth0/device/ptp/ptp*/subdir/ptp*/period")
result, edgeErr = hcm.resolveSysFSPtpDevice(complexPath)
// This should still work as it only splits on the first ptp*
if edgeErr != nil {
t.Logf("Complex path with multiple ptp* placeholders returned error (expected): %v", edgeErr)
} else {
t.Logf("Complex path resolved to: %v", result)
}
})
}
func TestSysFSCommandCaching(t *testing.T) {
// Set up mock PTP device resolver for testing
SetupMockPtpDeviceResolver()
defer TeardownMockPtpDeviceResolver()
// Set up mock DPLL pins for testing
mockErr := SetupMockDpllPinsForTests()
if mockErr != nil {
t.Logf("Warning: Failed to setup mock DPLL pins: %v", mockErr)
// Continue with test as DPLL pins are optional
}
defer TeardownMockDpllPinsForTests()
// Set up mock command executor for GetClockIDFromInterface
mockCmd := NewMockCommandExecutor()
mockCmd.SetResponse("ethtool", []string{"-i", "ens4f0"}, "driver: ice\nbus-info: 0000:17:00.0")