-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdarwin_test.go
More file actions
893 lines (791 loc) · 28.3 KB
/
darwin_test.go
File metadata and controls
893 lines (791 loc) · 28.3 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
//go:build darwin
package machineid
import (
"bytes"
"context"
"errors"
"fmt"
"log/slog"
"strings"
"testing"
)
// TestExtractHardwareFieldValid tests successful field extraction from JSON.
func TestExtractHardwareFieldValid(t *testing.T) {
jsonOutput := `{
"SPHardwareDataType": [{
"platform_UUID": "12345-67890",
"serial_number": "C02TEST123",
"chip_type": "Apple M1 Pro",
"machine_model": "MacBookPro18,3"
}]
}`
result, err := extractHardwareField(jsonOutput, func(e spHardwareEntry) string {
return e.PlatformUUID
})
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if result != "12345-67890" {
t.Errorf("Expected '12345-67890', got '%s'", result)
}
}
// TestExtractHardwareFieldEmpty tests extraction when field is empty.
func TestExtractHardwareFieldEmpty(t *testing.T) {
jsonOutput := `{
"SPHardwareDataType": [{
"platform_UUID": "",
"serial_number": "C02TEST123"
}]
}`
_, err := extractHardwareField(jsonOutput, func(e spHardwareEntry) string {
return e.PlatformUUID
})
if err == nil {
t.Error("Expected error when field is empty")
}
}
// TestExtractHardwareFieldNoData tests extraction when no data entries exist.
func TestExtractHardwareFieldNoData(t *testing.T) {
jsonOutput := `{"SPHardwareDataType": []}`
_, err := extractHardwareField(jsonOutput, func(e spHardwareEntry) string {
return e.PlatformUUID
})
if err == nil {
t.Error("Expected error when no data entries")
}
}
// TestExtractHardwareFieldInvalidJSON tests extraction with invalid JSON.
func TestExtractHardwareFieldInvalidJSON(t *testing.T) {
_, err := extractHardwareField("not json", func(e spHardwareEntry) string {
return e.PlatformUUID
})
if err == nil {
t.Error("Expected error for invalid JSON")
}
}
// TestMacOSHardwareUUIDViaIORegNotFound tests ioreg fallback when UUID not in output.
func TestMacOSHardwareUUIDViaIORegNotFound(t *testing.T) {
mock := newMockExecutor()
mock.setOutput("ioreg", "some output without UUID")
_, err := macOSHardwareUUIDViaIOReg(context.Background(), mock, nil)
if err == nil {
t.Error("Expected error when UUID not found in ioreg output")
}
}
// TestMacOSHardwareUUIDViaIORegError tests ioreg command error.
func TestMacOSHardwareUUIDViaIORegError(t *testing.T) {
mock := newMockExecutor()
mock.setError("ioreg", fmt.Errorf("command failed"))
_, err := macOSHardwareUUIDViaIOReg(context.Background(), mock, nil)
if err == nil {
t.Error("Expected error when ioreg command fails")
}
}
// TestMacOSHardwareUUIDViaIORegSuccess tests successful UUID extraction.
func TestMacOSHardwareUUIDViaIORegSuccess(t *testing.T) {
mock := newMockExecutor()
ioregOutput := `
+-o IOPlatformExpertDevice
| {
| "IOPlatformUUID" = "ABCD-1234-EFGH-5678"
| }
`
mock.setOutput("ioreg", ioregOutput)
result, err := macOSHardwareUUIDViaIOReg(context.Background(), mock, nil)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if result != "ABCD-1234-EFGH-5678" {
t.Errorf("Expected 'ABCD-1234-EFGH-5678', got '%s'", result)
}
}
// TestMacOSSerialNumberViaIORegError tests ioreg error.
func TestMacOSSerialNumberViaIORegError(t *testing.T) {
mock := newMockExecutor()
mock.setError("ioreg", fmt.Errorf("command failed"))
_, err := macOSSerialNumberViaIOReg(context.Background(), mock, nil)
if err == nil {
t.Error("Expected error when ioreg command fails")
}
}
// TestMacOSSerialNumberViaIORegNotFound tests when serial not in output.
func TestMacOSSerialNumberViaIORegNotFound(t *testing.T) {
mock := newMockExecutor()
mock.setOutput("ioreg", "output without serial")
_, err := macOSSerialNumberViaIOReg(context.Background(), mock, nil)
if err == nil {
t.Error("Expected error when serial not found")
}
}
// TestMacOSSerialNumberViaIORegSuccess tests successful extraction.
func TestMacOSSerialNumberViaIORegSuccess(t *testing.T) {
mock := newMockExecutor()
ioregOutput := `
"IOPlatformSerialNumber" = "C02TEST123"
`
mock.setOutput("ioreg", ioregOutput)
result, err := macOSSerialNumberViaIOReg(context.Background(), mock, nil)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if result != "C02TEST123" {
t.Errorf("Expected 'C02TEST123', got '%s'", result)
}
}
// TestMacOSSerialNumberFallback tests fallback to ioreg.
func TestMacOSSerialNumberFallback(t *testing.T) {
mock := newMockExecutor()
mock.setError("system_profiler", fmt.Errorf("system_profiler failed"))
mock.setOutput("ioreg", `"IOPlatformSerialNumber" = "C02FALLBACK"`)
result, err := macOSSerialNumber(context.Background(), mock, nil)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if result != "C02FALLBACK" {
t.Errorf("Expected 'C02FALLBACK', got '%s'", result)
}
}
// TestMacOSCPUInfoError tests CPU info error handling.
func TestMacOSCPUInfoError(t *testing.T) {
mock := newMockExecutor()
mock.setError("sysctl", fmt.Errorf("command failed"))
mock.setError("system_profiler", fmt.Errorf("command failed"))
_, err := macOSCPUInfo(context.Background(), mock, nil)
if err == nil {
t.Error("Expected error when all CPU info commands fail")
}
}
// TestMacOSCPUInfoAppleSiliconViaSysctl tests Apple Silicon CPU info using sysctl
// (primary path). On Apple Silicon, sysctl -n machdep.cpu.brand_string returns
// the chip name, and machdep.cpu.features returns empty, producing "ChipType:".
func TestMacOSCPUInfoAppleSiliconViaSysctl(t *testing.T) {
mock := newMockExecutor()
// sysctl returns "Apple M1 Pro" as brand_string, empty features (Apple Silicon behavior)
mock.setOutput("sysctl", "Apple M1 Pro")
result, err := macOSCPUInfo(context.Background(), mock, nil)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
// NOTE: On Apple Silicon, sysctl -n machdep.cpu.features succeeds with empty output.
// The mock returns the same output for both sysctl calls (brand_string and features)
// because it keys by command name only. In production, features is empty, producing
// "Apple M1 Pro:" (trailing colon). The mock produces "Apple M1 Pro:Apple M1 Pro"
// which still exercises the code path correctly.
if !strings.HasPrefix(result, "Apple M1 Pro") {
t.Errorf("Expected result to start with 'Apple M1 Pro', got '%s'", result)
}
}
// TestMacOSCPUInfoFallbackToProfiler tests CPU info falls back to system_profiler
// when sysctl is not available.
func TestMacOSCPUInfoFallbackToProfiler(t *testing.T) {
mock := newMockExecutor()
// sysctl not configured → error → falls through to system_profiler
mock.setOutput("system_profiler", `{
"SPHardwareDataType": [{
"chip_type": "Apple M1 Pro",
"machine_model": "MacBookPro18,3",
"platform_UUID": "SOME-UUID",
"serial_number": "SERIAL123"
}]
}`)
result, err := macOSCPUInfo(context.Background(), mock, nil)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if result != "Apple M1 Pro" {
t.Errorf("Expected 'Apple M1 Pro', got '%s'", result)
}
}
// TestMacOSCPUInfoAllFail tests that CPU info returns error when all methods fail.
func TestMacOSCPUInfoAllFail(t *testing.T) {
mock := newMockExecutor()
// Neither sysctl nor system_profiler configured → all fail
mock.setError("sysctl", fmt.Errorf("command not found"))
mock.setError("system_profiler", fmt.Errorf("command not found"))
_, err := macOSCPUInfo(context.Background(), mock, nil)
if err == nil {
t.Error("Expected error when all CPU methods fail")
}
}
// TestParseStorageJSON tests proper JSON parsing of storage data.
func TestParseStorageJSON(t *testing.T) {
jsonOutput := `{
"SPStorageDataType": [
{
"_name": "Macintosh HD - Data",
"bsd_name": "disk3s1",
"physical_drive": {
"device_name": "APPLE SSD AP1024R",
"is_internal_disk": "yes",
"medium_type": "ssd"
}
},
{
"_name": "Macintosh HD",
"bsd_name": "disk3s3s1",
"physical_drive": {
"device_name": "APPLE SSD AP1024R",
"is_internal_disk": "yes",
"medium_type": "ssd"
}
},
{
"_name": "External Drive",
"bsd_name": "disk8s2",
"physical_drive": {
"device_name": "SA400S37960G",
"is_internal_disk": "no",
"medium_type": "ssd"
}
}
]
}`
result, err := parseStorageJSON(jsonOutput)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
// Should only have 1 entry: APPLE SSD AP1024R (deduplicated, internal only)
if len(result) != 1 {
t.Errorf("Expected 1 disk entry (deduplicated internal), got %d: %v", len(result), result)
}
if result[0] != "APPLE SSD AP1024R" {
t.Errorf("Expected 'APPLE SSD AP1024R', got '%s'", result[0])
}
}
// TestParseStorageJSONNoInternal tests when no internal disks are found.
func TestParseStorageJSONNoInternal(t *testing.T) {
jsonOutput := `{
"SPStorageDataType": [
{
"_name": "External",
"physical_drive": {
"device_name": "External SSD",
"is_internal_disk": "no"
}
}
]
}`
_, err := parseStorageJSON(jsonOutput)
if err == nil {
t.Error("Expected error when no internal disks found")
}
}
// TestParseStorageJSONInvalid tests invalid JSON.
func TestParseStorageJSONInvalid(t *testing.T) {
_, err := parseStorageJSON("not json")
if err == nil {
t.Error("Expected error for invalid JSON")
}
}
// TestMacOSDiskInfoError tests disk info when system_profiler fails.
func TestMacOSDiskInfoError(t *testing.T) {
mock := newMockExecutor()
mock.setError("system_profiler", fmt.Errorf("command failed"))
_, err := macOSDiskInfo(context.Background(), mock, nil)
if err == nil {
t.Error("Expected error when system_profiler fails")
}
}
// TestMacOSDiskInfoSuccess tests successful disk info via JSON.
func TestMacOSDiskInfoSuccess(t *testing.T) {
mock := newMockExecutor()
mock.setOutput("system_profiler", `{
"SPStorageDataType": [
{
"_name": "Macintosh HD",
"physical_drive": {
"device_name": "APPLE SSD AP1024R",
"is_internal_disk": "yes"
}
}
]
}`)
result, err := macOSDiskInfo(context.Background(), mock, nil)
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if len(result) != 1 {
t.Errorf("Expected 1 disk entry, got %d", len(result))
}
}
// TestMacOSHardwareUUIDWithLogger tests UUID fallback with logger enabled.
func TestMacOSHardwareUUIDWithLogger(t *testing.T) {
t.Run("system_profiler parse error falls back to ioreg with logging", func(t *testing.T) {
var buf bytes.Buffer
logger := slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug}))
mock := newMockExecutor()
mock.setOutput("system_profiler", "not json") // Will cause parse error
mock.setOutput("ioreg", `"IOPlatformUUID" = "FALLBACK-UUID-123"`)
result, err := macOSHardwareUUID(context.Background(), mock, logger)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if result != "FALLBACK-UUID-123" {
t.Errorf("Expected 'FALLBACK-UUID-123', got %q", result)
}
if !bytes.Contains(buf.Bytes(), []byte("system_profiler UUID parsing failed")) {
t.Error("Expected 'system_profiler UUID parsing failed' in log output")
}
if !bytes.Contains(buf.Bytes(), []byte("falling back to ioreg for hardware UUID")) {
t.Error("Expected 'falling back to ioreg' in log output")
}
})
t.Run("system_profiler command error falls back with logging", func(t *testing.T) {
var buf bytes.Buffer
logger := slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug}))
mock := newMockExecutor()
mock.setError("system_profiler", fmt.Errorf("command failed"))
mock.setOutput("ioreg", `"IOPlatformUUID" = "FALLBACK-UUID-456"`)
result, err := macOSHardwareUUID(context.Background(), mock, logger)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if result != "FALLBACK-UUID-456" {
t.Errorf("Expected 'FALLBACK-UUID-456', got %q", result)
}
if !bytes.Contains(buf.Bytes(), []byte("falling back to ioreg for hardware UUID")) {
t.Error("Expected fallback log message")
}
})
}
// TestMacOSSerialNumberWithLogger tests serial fallback with logger enabled.
func TestMacOSSerialNumberWithLogger(t *testing.T) {
var buf bytes.Buffer
logger := slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug}))
mock := newMockExecutor()
mock.setOutput("system_profiler", "not json") // Will cause parse error
mock.setOutput("ioreg", `"IOPlatformSerialNumber" = "SERIAL-LOG"`)
result, err := macOSSerialNumber(context.Background(), mock, logger)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if result != "SERIAL-LOG" {
t.Errorf("Expected 'SERIAL-LOG', got %q", result)
}
if !bytes.Contains(buf.Bytes(), []byte("system_profiler serial parsing failed")) {
t.Error("Expected 'system_profiler serial parsing failed' in log output")
}
if !bytes.Contains(buf.Bytes(), []byte("falling back to ioreg for serial number")) {
t.Error("Expected 'falling back to ioreg' in log output")
}
}
// TestMacOSHardwareUUIDViaIORegNotFoundWithLogger tests ioreg not-found with logger.
func TestMacOSHardwareUUIDViaIORegNotFoundWithLogger(t *testing.T) {
var buf bytes.Buffer
logger := slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug}))
mock := newMockExecutor()
mock.setOutput("ioreg", "output without UUID pattern")
_, err := macOSHardwareUUIDViaIOReg(context.Background(), mock, logger)
if err == nil {
t.Error("Expected error")
}
if !bytes.Contains(buf.Bytes(), []byte("hardware UUID not found in ioreg output")) {
t.Error("Expected 'hardware UUID not found in ioreg output' in log")
}
}
// TestMacOSSerialNumberViaIORegNotFoundWithLogger tests serial not-found with logger.
func TestMacOSSerialNumberViaIORegNotFoundWithLogger(t *testing.T) {
var buf bytes.Buffer
logger := slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug}))
mock := newMockExecutor()
mock.setOutput("ioreg", "output without serial pattern")
_, err := macOSSerialNumberViaIOReg(context.Background(), mock, logger)
if err == nil {
t.Error("Expected error")
}
if !bytes.Contains(buf.Bytes(), []byte("serial number not found in ioreg output")) {
t.Error("Expected 'serial number not found in ioreg output' in log")
}
}
// TestMacOSCPUInfoEmptyBrand tests sysctl returning empty brand string.
func TestMacOSCPUInfoEmptyBrand(t *testing.T) {
mock := newMockExecutor()
mock.setOutput("sysctl", "") // Empty brand string
mock.setOutput("system_profiler", `{
"SPHardwareDataType": [{
"chip_type": "Apple M2",
"machine_model": "Mac",
"platform_UUID": "UUID",
"serial_number": "SER"
}]
}`)
result, err := macOSCPUInfo(context.Background(), mock, nil)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if result != "Apple M2" {
t.Errorf("Expected 'Apple M2', got %q", result)
}
}
// TestMacOSCPUInfoEmptyBrandWithLogger tests empty brand path with logger.
func TestMacOSCPUInfoEmptyBrandWithLogger(t *testing.T) {
var buf bytes.Buffer
logger := slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug}))
mock := newMockExecutor()
mock.setOutput("sysctl", "") // Empty brand → falls to system_profiler
mock.setOutput("system_profiler", `{
"SPHardwareDataType": [{
"chip_type": "Apple M2 Pro",
"machine_model": "Mac",
"platform_UUID": "UUID",
"serial_number": "SER"
}]
}`)
result, err := macOSCPUInfo(context.Background(), mock, logger)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if result != "Apple M2 Pro" {
t.Errorf("Expected 'Apple M2 Pro', got %q", result)
}
if !bytes.Contains(buf.Bytes(), []byte("falling back to system_profiler for CPU info")) {
t.Error("Expected fallback log message")
}
}
// TestMacOSCPUInfoProfilerJSONParseFailWithLogger tests JSON parse failure with logger.
func TestMacOSCPUInfoProfilerJSONParseFailWithLogger(t *testing.T) {
var buf bytes.Buffer
logger := slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug}))
mock := newMockExecutor()
mock.setError("sysctl", fmt.Errorf("not found"))
mock.setOutput("system_profiler", "not valid json")
_, err := macOSCPUInfo(context.Background(), mock, logger)
if err == nil {
t.Error("Expected error when all methods fail")
}
if !bytes.Contains(buf.Bytes(), []byte("system_profiler CPU JSON parsing failed")) {
t.Error("Expected 'system_profiler CPU JSON parsing failed' in log")
}
if !bytes.Contains(buf.Bytes(), []byte("all CPU info methods failed")) {
t.Error("Expected 'all CPU info methods failed' in log")
}
}
// TestMacOSCPUInfoEmptyChipTypeWithLogger tests empty chip_type with logger.
func TestMacOSCPUInfoEmptyChipTypeWithLogger(t *testing.T) {
var buf bytes.Buffer
logger := slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug}))
mock := newMockExecutor()
mock.setError("sysctl", fmt.Errorf("not found"))
mock.setOutput("system_profiler", `{
"SPHardwareDataType": [{
"chip_type": "",
"machine_model": "Mac",
"platform_UUID": "UUID",
"serial_number": "SER"
}]
}`)
_, err := macOSCPUInfo(context.Background(), mock, logger)
if err == nil {
t.Error("Expected error when chip_type is empty")
}
if !bytes.Contains(buf.Bytes(), []byte("system_profiler returned empty chip_type")) {
t.Error("Expected 'system_profiler returned empty chip_type' in log")
}
}
// TestMacOSCPUInfoSysctlBrandWithFeaturesFail tests brand success but features fail.
func TestMacOSCPUInfoSysctlBrandWithFeaturesFail(t *testing.T) {
mock := newMockExecutor()
// The mock returns same output for all "sysctl" calls. To test the
// features-fail path, we set sysctl to error on the second call.
// Since mockExecutor doesn't support per-arg differentiation, we test
// the code path where sysctl succeeds for brand but the features call
// also "succeeds" (same mock behavior). The brand-only path is tested
// by making sysctl return error after first call isn't straightforward,
// so we test that a non-empty brand with features returns formatted output.
mock.setOutput("sysctl", "Intel Core i7")
result, err := macOSCPUInfo(context.Background(), mock, nil)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
// Both brand and features calls go to same mock → "Intel Core i7:Intel Core i7"
if !strings.Contains(result, "Intel Core i7") {
t.Errorf("Expected result to contain 'Intel Core i7', got %q", result)
}
}
// TestParseStorageJSONEmptyDeviceName tests entries with empty device_name are skipped.
func TestParseStorageJSONEmptyDeviceName(t *testing.T) {
jsonOutput := `{
"SPStorageDataType": [
{
"_name": "Volume 1",
"physical_drive": {
"device_name": "",
"is_internal_disk": "yes"
}
},
{
"_name": "Volume 2",
"physical_drive": {
"device_name": "APPLE SSD",
"is_internal_disk": "yes"
}
}
]
}`
result, err := parseStorageJSON(jsonOutput)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if len(result) != 1 {
t.Errorf("Expected 1 disk entry (empty name skipped), got %d", len(result))
}
if result[0] != "APPLE SSD" {
t.Errorf("Expected 'APPLE SSD', got %q", result[0])
}
}
// TestParseStorageJSONAllEmpty tests when all entries have empty device_name.
func TestParseStorageJSONAllEmpty(t *testing.T) {
jsonOutput := `{
"SPStorageDataType": [
{
"_name": "Volume 1",
"physical_drive": {
"device_name": "",
"is_internal_disk": "yes"
}
}
]
}`
_, err := parseStorageJSON(jsonOutput)
if err == nil {
t.Error("Expected error when all disk entries have empty device_name")
}
}
// TestParseStorageJSONEmptyArray tests empty storage array.
func TestParseStorageJSONEmptyArray(t *testing.T) {
jsonOutput := `{"SPStorageDataType": []}`
_, err := parseStorageJSON(jsonOutput)
if err == nil {
t.Error("Expected error for empty storage array")
}
}
// TestCollectMACAddressesWithLogger tests MAC collection with logger enabled.
func TestCollectMACAddressesWithLogger(t *testing.T) {
var buf bytes.Buffer
logger := slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug}))
macs, err := collectMACAddresses(MACFilterPhysical, logger)
if err != nil {
t.Logf("collectMACAddresses error (may be expected): %v", err)
return
}
// On most systems, some interfaces should produce log output
output := buf.String()
t.Logf("Found %d MACs, log output length: %d", len(macs), len(output))
// We can't assert specific log messages since they depend on system interfaces,
// but we can verify no panic occurred and logs were produced
if len(macs) > 0 && !bytes.Contains(buf.Bytes(), []byte("including interface")) {
t.Error("Expected 'including interface' log when MACs are found")
}
}
// TestExtractHardwareFieldErrorTypes tests that extractHardwareField returns correct error types.
func TestExtractHardwareFieldErrorTypes(t *testing.T) {
t.Run("invalid JSON returns ParseError", func(t *testing.T) {
_, err := extractHardwareField("not json", func(e spHardwareEntry) string {
return e.PlatformUUID
})
var parseErr *ParseError
if !errors.As(err, &parseErr) {
t.Fatalf("Expected ParseError, got %T: %v", err, err)
}
if parseErr.Source != "system_profiler hardware JSON" {
t.Errorf("ParseError.Source = %q, want %q", parseErr.Source, "system_profiler hardware JSON")
}
})
t.Run("no data returns ParseError with ErrNotFound", func(t *testing.T) {
_, err := extractHardwareField(`{"SPHardwareDataType": []}`, func(e spHardwareEntry) string {
return e.PlatformUUID
})
var parseErr *ParseError
if !errors.As(err, &parseErr) {
t.Fatalf("Expected ParseError, got %T: %v", err, err)
}
if !errors.Is(err, ErrNotFound) {
t.Error("Expected ErrNotFound in error chain")
}
})
t.Run("empty field returns ParseError with ErrEmptyValue", func(t *testing.T) {
_, err := extractHardwareField(`{"SPHardwareDataType": [{"platform_UUID": ""}]}`, func(e spHardwareEntry) string {
return e.PlatformUUID
})
var parseErr *ParseError
if !errors.As(err, &parseErr) {
t.Fatalf("Expected ParseError, got %T: %v", err, err)
}
if !errors.Is(err, ErrEmptyValue) {
t.Error("Expected ErrEmptyValue in error chain")
}
})
}
// TestMacOSHardwareUUIDViaIORegErrorType tests error type from ioreg not-found.
func TestMacOSHardwareUUIDViaIORegErrorType(t *testing.T) {
mock := newMockExecutor()
mock.setOutput("ioreg", "no UUID here")
_, err := macOSHardwareUUIDViaIOReg(context.Background(), mock, nil)
var parseErr *ParseError
if !errors.As(err, &parseErr) {
t.Fatalf("Expected ParseError, got %T: %v", err, err)
}
if !errors.Is(err, ErrNotFound) {
t.Error("Expected ErrNotFound in error chain")
}
}
// TestMacOSCPUInfoAllFailErrorType tests error type when all CPU methods fail.
func TestMacOSCPUInfoAllFailErrorType(t *testing.T) {
mock := newMockExecutor()
mock.setError("sysctl", fmt.Errorf("not found"))
mock.setError("system_profiler", fmt.Errorf("not found"))
_, err := macOSCPUInfo(context.Background(), mock, nil)
if !errors.Is(err, ErrAllMethodsFailed) {
t.Errorf("Expected ErrAllMethodsFailed, got %v", err)
}
}
// --- Null UUID rejection (D1) ---
// TestMacOSHardwareUUIDRejectsNullFromSystemProfiler verifies that a null UUID
// from system_profiler triggers the ioreg fallback rather than being accepted.
func TestMacOSHardwareUUIDRejectsNullFromSystemProfiler(t *testing.T) {
mock := newMockExecutor()
mock.setOutput("system_profiler", `{
"SPHardwareDataType": [{
"platform_UUID": "00000000-0000-0000-0000-000000000000",
"serial_number": "C02TEST"
}]
}`)
mock.setOutput("ioreg", `"IOPlatformUUID" = "REAL-UUID-FROM-IOREG"`)
result, err := macOSHardwareUUID(context.Background(), mock, nil)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if result != "REAL-UUID-FROM-IOREG" {
t.Errorf("Expected 'REAL-UUID-FROM-IOREG', got %q", result)
}
}
func TestMacOSHardwareUUIDRejectsNullFromSystemProfilerWithLogger(t *testing.T) {
var buf bytes.Buffer
logger := slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug}))
mock := newMockExecutor()
mock.setOutput("system_profiler", `{
"SPHardwareDataType": [{
"platform_UUID": "00000000-0000-0000-0000-000000000000"
}]
}`)
mock.setOutput("ioreg", `"IOPlatformUUID" = "REAL-UUID"`)
if _, err := macOSHardwareUUID(context.Background(), mock, logger); err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if !bytes.Contains(buf.Bytes(), []byte("system_profiler returned null UUID")) {
t.Error("Expected 'system_profiler returned null UUID' log")
}
}
// TestMacOSHardwareUUIDViaIORegRejectsNull verifies that ioreg null UUIDs
// return ErrNotFound so no garbage propagates into the machine ID.
func TestMacOSHardwareUUIDViaIORegRejectsNull(t *testing.T) {
mock := newMockExecutor()
mock.setOutput("ioreg", `"IOPlatformUUID" = "00000000-0000-0000-0000-000000000000"`)
_, err := macOSHardwareUUIDViaIOReg(context.Background(), mock, nil)
if err == nil {
t.Fatal("Expected error for null UUID from ioreg")
}
var parseErr *ParseError
if !errors.As(err, &parseErr) {
t.Errorf("Expected ParseError, got %T", err)
}
if !errors.Is(err, ErrNotFound) {
t.Errorf("Expected ErrNotFound, got %v", err)
}
}
// TestMacOSHardwareUUIDBothNull verifies both sources returning null fails.
func TestMacOSHardwareUUIDBothNull(t *testing.T) {
mock := newMockExecutor()
mock.setOutput("system_profiler", `{
"SPHardwareDataType": [{
"platform_UUID": "00000000-0000-0000-0000-000000000000"
}]
}`)
mock.setOutput("ioreg", `"IOPlatformUUID" = "00000000-0000-0000-0000-000000000000"`)
_, err := macOSHardwareUUID(context.Background(), mock, nil)
if err == nil {
t.Fatal("Expected error when both sources return null UUID")
}
if !errors.Is(err, ErrNotFound) {
t.Errorf("Expected ErrNotFound, got %v", err)
}
}
// --- Apple Silicon CPU path via args-aware mock (D2) ---
// TestMacOSCPUInfoAppleSiliconTrailingColon exercises the exact Apple Silicon
// production path: brand_string returns the chip name, features returns empty,
// producing "ChipType:" with a trailing colon that must be preserved for
// backward compatibility with existing license activations.
func TestMacOSCPUInfoAppleSiliconTrailingColon(t *testing.T) {
mock := newMockExecutor()
mock.setOutputForArgs("sysctl", []string{"-n", "machdep.cpu.brand_string"}, "Apple M1 Pro")
mock.setOutputForArgs("sysctl", []string{"-n", "machdep.cpu.features"}, "")
result, err := macOSCPUInfo(context.Background(), mock, nil)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if result != "Apple M1 Pro:" {
t.Errorf("Expected 'Apple M1 Pro:' (trailing colon), got %q", result)
}
}
// TestMacOSCPUInfoIntelBrandAndFeatures exercises the Intel production path
// where both brand_string and features return real data.
func TestMacOSCPUInfoIntelBrandAndFeatures(t *testing.T) {
mock := newMockExecutor()
mock.setOutputForArgs("sysctl", []string{"-n", "machdep.cpu.brand_string"}, "Intel(R) Core(TM) i7-9750H")
mock.setOutputForArgs("sysctl", []string{"-n", "machdep.cpu.features"}, "FPU VME DE PSE")
result, err := macOSCPUInfo(context.Background(), mock, nil)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
expected := "Intel(R) Core(TM) i7-9750H:FPU VME DE PSE"
if result != expected {
t.Errorf("Expected %q, got %q", expected, result)
}
}
// TestMacOSCPUInfoBrandOKFeaturesErrorDegrades documents the D3 quirk: when
// brand_string succeeds but features errors, the code returns just cpuBrand.
// This is intentionally preserved for backward compatibility (see the doc
// comment on macOSCPUInfo) — the test locks in the current behavior so any
// future change that would break existing license activations fails loudly.
func TestMacOSCPUInfoBrandOKFeaturesErrorDegrades(t *testing.T) {
mock := newMockExecutor()
mock.setOutputForArgs("sysctl", []string{"-n", "machdep.cpu.brand_string"}, "Apple M1 Pro")
mock.setErrorForArgs("sysctl", []string{"-n", "machdep.cpu.features"}, fmt.Errorf("sandboxed"))
result, err := macOSCPUInfo(context.Background(), mock, nil)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
// Degraded path: returns cpuBrand without trailing colon.
if result != "Apple M1 Pro" {
t.Errorf("Expected 'Apple M1 Pro' (degraded path), got %q", result)
}
}
// --- parseStorageJSON edge cases ---
// TestParseStorageJSONMissingInternalField verifies that entries without the
// is_internal_disk field are treated as non-internal (the current behavior).
func TestParseStorageJSONMissingInternalField(t *testing.T) {
jsonOutput := `{
"SPStorageDataType": [
{
"_name": "Volume",
"physical_drive": {
"device_name": "SOME DISK"
}
},
{
"_name": "Internal",
"physical_drive": {
"device_name": "APPLE SSD",
"is_internal_disk": "yes"
}
}
]
}`
result, err := parseStorageJSON(jsonOutput)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if len(result) != 1 || result[0] != "APPLE SSD" {
t.Errorf("Expected [APPLE SSD], got %v", result)
}
}