-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinux_test.go
More file actions
669 lines (561 loc) · 17.5 KB
/
linux_test.go
File metadata and controls
669 lines (561 loc) · 17.5 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
//go:build linux
package machineid
import (
"bytes"
"context"
"errors"
"fmt"
"log/slog"
"os"
"path/filepath"
"testing"
)
// --- parseCPUInfo tests ---
func TestParseCPUInfoFull(t *testing.T) {
content := `processor : 0
vendor_id : GenuineIntel
cpu family : 6
model : 158
model name : Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
stepping : 10
cpu MHz : 2600.000
flags : fpu vme de pse tsc msr pae mce
`
result, err := parseCPUInfo(content)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
expected := "0:GenuineIntel:Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz:fpu vme de pse tsc msr pae mce"
if result != expected {
t.Errorf("Expected %q, got %q", expected, result)
}
}
func TestParseCPUInfoEmpty(t *testing.T) {
_, err := parseCPUInfo("")
if err == nil {
t.Fatal("Expected error for empty input")
}
if !errors.Is(err, ErrNotFound) {
t.Errorf("Expected ErrNotFound, got %v", err)
}
var parseErr *ParseError
if !errors.As(err, &parseErr) {
t.Errorf("Expected ParseError, got %T", err)
}
}
func TestParseCPUInfoPartial(t *testing.T) {
content := `processor : 3
vendor_id : AuthenticAMD
model name : AMD Ryzen 9 5950X
`
result, err := parseCPUInfo(content)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
expected := "3:AuthenticAMD:AMD Ryzen 9 5950X:"
if result != expected {
t.Errorf("Expected %q, got %q", expected, result)
}
}
func TestParseCPUInfoNoColon(t *testing.T) {
content := "some line without colon\nanother line\n"
_, err := parseCPUInfo(content)
if err == nil {
t.Fatal("Expected error when no fields present")
}
if !errors.Is(err, ErrNotFound) {
t.Errorf("Expected ErrNotFound, got %v", err)
}
}
func TestParseCPUInfoUnknownFieldsOnly(t *testing.T) {
// Lines have colons but none are recognized fields — should still error.
content := "some unknown key : value\nanother : thing\n"
_, err := parseCPUInfo(content)
if err == nil {
t.Fatal("Expected error when no recognized fields present")
}
if !errors.Is(err, ErrNotFound) {
t.Errorf("Expected ErrNotFound, got %v", err)
}
}
func TestParseCPUInfoMultipleProcessors(t *testing.T) {
// parseCPUInfo keeps overwriting, so the last processor block wins
content := `processor : 0
vendor_id : GenuineIntel
model name : Intel Core i7
flags : fpu vme
processor : 1
vendor_id : GenuineIntel
model name : Intel Core i7
flags : fpu vme avx
`
result, err := parseCPUInfo(content)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
// Last processor's values should win
expected := "1:GenuineIntel:Intel Core i7:fpu vme avx"
if result != expected {
t.Errorf("Expected %q, got %q", expected, result)
}
}
// --- isValidUUID tests ---
func TestIsValidUUID(t *testing.T) {
tests := []struct {
name string
uuid string
valid bool
}{
{"valid UUID", "4C4C4544-0058-5210-8048-B4C04F595031", true},
{"empty", "", false},
{"null UUID", "00000000-0000-0000-0000-000000000000", false},
{"simple string", "abc123", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := isValidUUID(tt.uuid); got != tt.valid {
t.Errorf("isValidUUID(%q) = %v, want %v", tt.uuid, got, tt.valid)
}
})
}
}
// --- isValidSerial tests ---
func TestIsValidSerial(t *testing.T) {
tests := []struct {
name string
serial string
valid bool
}{
{"valid serial", "ABC12345", true},
{"empty", "", false},
{"OEM placeholder", "To be filled by O.E.M.", false},
{"simple string", "SERIAL123", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := isValidSerial(tt.serial); got != tt.valid {
t.Errorf("isValidSerial(%q) = %v, want %v", tt.serial, got, tt.valid)
}
})
}
}
// --- isNonEmpty tests ---
func TestIsNonEmpty(t *testing.T) {
if isNonEmpty("") {
t.Error("Expected false for empty string")
}
if !isNonEmpty("hello") {
t.Error("Expected true for non-empty string")
}
}
// --- linuxDiskSerialsLSBLK tests ---
func TestLinuxDiskSerialsLSBLKSuccess(t *testing.T) {
mock := newMockExecutor()
mock.setOutput("lsblk", "WD-12345\nSAMSUNG-67890\n")
serials, err := linuxDiskSerialsLSBLK(context.Background(), mock, nil)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if len(serials) != 2 {
t.Fatalf("Expected 2 serials, got %d", len(serials))
}
if serials[0] != "WD-12345" || serials[1] != "SAMSUNG-67890" {
t.Errorf("Unexpected serials: %v", serials)
}
}
func TestLinuxDiskSerialsLSBLKEmpty(t *testing.T) {
mock := newMockExecutor()
mock.setOutput("lsblk", "\n\n")
serials, err := linuxDiskSerialsLSBLK(context.Background(), mock, nil)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if len(serials) != 0 {
t.Errorf("Expected 0 serials for empty output, got %d", len(serials))
}
}
func TestLinuxDiskSerialsLSBLKError(t *testing.T) {
mock := newMockExecutor()
mock.setError("lsblk", fmt.Errorf("lsblk not found"))
_, err := linuxDiskSerialsLSBLK(context.Background(), mock, nil)
if err == nil {
t.Error("Expected error when lsblk fails")
}
}
func TestLinuxDiskSerialsLSBLKSkipsEmpty(t *testing.T) {
mock := newMockExecutor()
mock.setOutput("lsblk", "WD-12345\n\n\nSAMSUNG-67890\n")
serials, err := linuxDiskSerialsLSBLK(context.Background(), mock, nil)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if len(serials) != 2 {
t.Errorf("Expected 2 serials (empty lines skipped), got %d", len(serials))
}
}
func TestLinuxDiskSerialsLSBLKFiltersOEM(t *testing.T) {
mock := newMockExecutor()
mock.setOutput("lsblk", "WD-12345\nTo be filled by O.E.M.\nSAMSUNG-67890\n")
serials, err := linuxDiskSerialsLSBLK(context.Background(), mock, nil)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if len(serials) != 2 {
t.Fatalf("Expected 2 serials (OEM filtered), got %d: %v", len(serials), serials)
}
for _, s := range serials {
if s == biosFirmwareMessage {
t.Error("OEM placeholder leaked into lsblk disk serials")
}
}
}
// --- linuxDiskSerialsSys tests (with injected sysBlockDir) ---
func withSysBlockDir(t *testing.T, dir string) {
t.Helper()
orig := sysBlockDir
sysBlockDir = dir
t.Cleanup(func() { sysBlockDir = orig })
}
func writeFakeDisk(t *testing.T, root, name, serial string) {
t.Helper()
deviceDir := filepath.Join(root, name, "device")
if err := os.MkdirAll(deviceDir, 0o755); err != nil {
t.Fatalf("mkdir %q: %v", deviceDir, err)
}
if err := os.WriteFile(filepath.Join(deviceDir, "serial"), []byte(serial), 0o644); err != nil {
t.Fatalf("write serial %q: %v", name, err)
}
}
func TestLinuxDiskSerialsSysSuccess(t *testing.T) {
tmp := t.TempDir()
withSysBlockDir(t, tmp)
writeFakeDisk(t, tmp, "sda", "WD-AAA\n")
writeFakeDisk(t, tmp, "sdb", "SAMSUNG-BBB\n")
serials, err := linuxDiskSerialsSys(nil)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if len(serials) != 2 {
t.Fatalf("Expected 2 serials, got %d: %v", len(serials), serials)
}
}
func TestLinuxDiskSerialsSysSkipsLoop(t *testing.T) {
tmp := t.TempDir()
withSysBlockDir(t, tmp)
writeFakeDisk(t, tmp, "sda", "WD-AAA\n")
writeFakeDisk(t, tmp, "loop0", "SHOULD-SKIP\n")
serials, err := linuxDiskSerialsSys(nil)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if len(serials) != 1 || serials[0] != "WD-AAA" {
t.Errorf("Expected [WD-AAA], got %v", serials)
}
}
func TestLinuxDiskSerialsSysFiltersOEMAndEmpty(t *testing.T) {
tmp := t.TempDir()
withSysBlockDir(t, tmp)
writeFakeDisk(t, tmp, "sda", "WD-REAL\n")
writeFakeDisk(t, tmp, "sdb", "To be filled by O.E.M.\n")
writeFakeDisk(t, tmp, "sdc", "\n")
serials, err := linuxDiskSerialsSys(nil)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if len(serials) != 1 || serials[0] != "WD-REAL" {
t.Errorf("Expected [WD-REAL], got %v", serials)
}
}
func TestLinuxDiskSerialsSysMissingDir(t *testing.T) {
withSysBlockDir(t, filepath.Join(t.TempDir(), "does-not-exist"))
_, err := linuxDiskSerialsSys(nil)
if err == nil {
t.Error("Expected error when sysBlockDir does not exist")
}
}
// --- linuxDiskSerials end-to-end with both backends failing ---
func TestLinuxDiskSerialsBothBackendsFail(t *testing.T) {
// lsblk errors, sys dir does not exist → ErrNotFound.
withSysBlockDir(t, filepath.Join(t.TempDir(), "nope"))
mock := newMockExecutor()
mock.setError("lsblk", fmt.Errorf("lsblk not found"))
_, err := linuxDiskSerials(context.Background(), mock, nil)
if err == nil {
t.Fatal("Expected error when both backends fail")
}
if !errors.Is(err, ErrNotFound) {
t.Errorf("Expected ErrNotFound, got %v", err)
}
}
func TestLinuxDiskSerialsPartialSuccess(t *testing.T) {
// lsblk succeeds, /sys/block missing → no error, lsblk results returned.
withSysBlockDir(t, filepath.Join(t.TempDir(), "nope"))
mock := newMockExecutor()
mock.setOutput("lsblk", "SERIAL-X\n")
serials, err := linuxDiskSerials(context.Background(), mock, nil)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if len(serials) != 1 || serials[0] != "SERIAL-X" {
t.Errorf("Expected [SERIAL-X], got %v", serials)
}
}
func TestLinuxDiskSerialsDeduplicatesAcrossBackends(t *testing.T) {
tmp := t.TempDir()
withSysBlockDir(t, tmp)
writeFakeDisk(t, tmp, "sda", "SHARED\n")
writeFakeDisk(t, tmp, "sdb", "ONLY-SYS\n")
mock := newMockExecutor()
mock.setOutput("lsblk", "SHARED\nONLY-LSBLK\n")
serials, err := linuxDiskSerials(context.Background(), mock, nil)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
// Expected: SHARED, ONLY-LSBLK, ONLY-SYS — no duplicates.
if len(serials) != 3 {
t.Fatalf("Expected 3 unique serials, got %d: %v", len(serials), serials)
}
count := map[string]int{}
for _, s := range serials {
count[s]++
}
for k, c := range count {
if c != 1 {
t.Errorf("Serial %q appeared %d times", k, c)
}
}
}
func TestLinuxDiskSerialsFiltersOEMAcrossBackends(t *testing.T) {
tmp := t.TempDir()
withSysBlockDir(t, tmp)
writeFakeDisk(t, tmp, "sda", "GOOD-SYS\n")
mock := newMockExecutor()
mock.setOutput("lsblk", "GOOD-LSBLK\nTo be filled by O.E.M.\n")
serials, err := linuxDiskSerials(context.Background(), mock, nil)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
for _, s := range serials {
if s == biosFirmwareMessage {
t.Error("OEM placeholder leaked through linuxDiskSerials")
}
}
if len(serials) != 2 {
t.Errorf("Expected 2 serials, got %d: %v", len(serials), serials)
}
}
// --- readFirstValidFromLocations success path ---
func TestReadFirstValidFromLocationsFindsFile(t *testing.T) {
tmp := t.TempDir()
goodPath := filepath.Join(tmp, "good")
if err := os.WriteFile(goodPath, []byte(" HELLO \n"), 0o644); err != nil {
t.Fatalf("write: %v", err)
}
locations := []string{
filepath.Join(tmp, "missing"),
goodPath,
}
value, err := readFirstValidFromLocations(locations, isNonEmpty, nil)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if value != "HELLO" {
t.Errorf("Expected %q, got %q", "HELLO", value)
}
}
func TestReadFirstValidFromLocationsSkipsInvalid(t *testing.T) {
tmp := t.TempDir()
invalidPath := filepath.Join(tmp, "invalid")
goodPath := filepath.Join(tmp, "good")
if err := os.WriteFile(invalidPath, []byte("00000000-0000-0000-0000-000000000000\n"), 0o644); err != nil {
t.Fatalf("write invalid: %v", err)
}
if err := os.WriteFile(goodPath, []byte("real-uuid\n"), 0o644); err != nil {
t.Fatalf("write good: %v", err)
}
value, err := readFirstValidFromLocations([]string{invalidPath, goodPath}, isValidUUID, nil)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if value != "real-uuid" {
t.Errorf("Expected %q, got %q", "real-uuid", value)
}
}
// --- linuxDiskSerials deduplication tests ---
func TestLinuxDiskSerialsDeduplicated(t *testing.T) {
mock := newMockExecutor()
mock.setOutput("lsblk", "SERIAL-A\nSERIAL-B\n")
serials, err := linuxDiskSerials(context.Background(), mock, nil)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
// lsblk should succeed; /sys/block will likely fail in test environment
t.Logf("Found %d disk serials from lsblk", len(serials))
}
func TestLinuxDiskSerialsWithLogger(t *testing.T) {
var buf bytes.Buffer
logger := slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug}))
mock := newMockExecutor()
mock.setOutput("lsblk", "SERIAL-LOG\n")
_, err := linuxDiskSerials(context.Background(), mock, logger)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if !bytes.Contains(buf.Bytes(), []byte("collected disk serials via lsblk")) {
t.Error("Expected 'collected disk serials via lsblk' in log")
}
}
// --- Provider integration tests with mock executor (Linux) ---
func TestProviderWithMockExecutor(t *testing.T) {
mock := newMockExecutor()
mock.setOutput("lsblk", "SERIAL-A\n")
p := New().WithExecutor(mock).WithDisk()
id, err := p.ID(context.Background())
if err != nil {
t.Fatalf("ID() error: %v", err)
}
if len(id) != 64 {
t.Errorf("Expected 64-char ID, got %d", len(id))
}
}
func TestProviderErrorHandlingLinux(t *testing.T) {
mock := newMockExecutor()
mock.setError("lsblk", fmt.Errorf("lsblk not found"))
// Disk-only: lsblk fails, /sys/block also likely fails in test
p := New().WithExecutor(mock).WithDisk()
_, err := p.ID(context.Background())
// This might succeed or fail depending on /sys/block availability
t.Logf("ID() result: err=%v", err)
}
func TestProviderDiagnosticsLinux(t *testing.T) {
mock := newMockExecutor()
mock.setOutput("lsblk", "SERIAL\n")
p := New().WithExecutor(mock).WithDisk()
if p.Diagnostics() != nil {
t.Error("Diagnostics should be nil before ID()")
}
if _, err := p.ID(context.Background()); err != nil {
t.Logf("ID() error (may be expected): %v", err)
}
diag := p.Diagnostics()
if diag == nil {
t.Fatal("Diagnostics should not be nil after ID()")
}
t.Logf("Collected: %v, Errors: %v", diag.Collected, diag.Errors)
}
func TestProviderWithLoggerLinux(t *testing.T) {
var buf bytes.Buffer
logger := slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug}))
mock := newMockExecutor()
mock.setOutput("lsblk", "SERIAL\n")
p := New().WithExecutor(mock).WithLogger(logger).WithDisk()
_, err := p.ID(context.Background())
if err != nil {
t.Fatalf("ID() error: %v", err)
}
if !bytes.Contains(buf.Bytes(), []byte("generating machine ID")) {
t.Error("Expected 'generating machine ID' in log")
}
}
func TestProviderValidateLinux(t *testing.T) {
mock := newMockExecutor()
mock.setOutput("lsblk", "SERIAL\n")
p := New().WithExecutor(mock).WithDisk()
id, err := p.ID(context.Background())
if err != nil {
t.Fatalf("ID() error: %v", err)
}
valid, err := p.Validate(context.Background(), id)
if err != nil {
t.Fatalf("Validate error: %v", err)
}
if !valid {
t.Error("Expected validation to succeed")
}
valid, err = p.Validate(context.Background(), "wrong-id")
if err != nil {
t.Fatalf("Validate error: %v", err)
}
if valid {
t.Error("Expected validation to fail for wrong ID")
}
}
func TestCollectIdentifiersLinuxAllFail(t *testing.T) {
mock := newMockExecutor()
mock.setError("lsblk", fmt.Errorf("not found"))
p := New().WithExecutor(mock).WithCPU().WithSystemUUID()
diag := &DiagnosticInfo{Errors: make(map[string]error)}
identifiers, err := collectIdentifiers(context.Background(), p, diag)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
// CPU and UUID read from files, not commands — they may or may not work
// depending on the test environment
t.Logf("Identifiers: %d, Collected: %v, Errors: %v", len(identifiers), diag.Collected, diag.Errors)
}
func TestCollectIdentifiersLinuxNoComponents(t *testing.T) {
p := New()
diag := &DiagnosticInfo{Errors: make(map[string]error)}
identifiers, err := collectIdentifiers(context.Background(), p, diag)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if len(identifiers) != 0 {
t.Errorf("Expected 0 identifiers with no components, got %d", len(identifiers))
}
}
func TestValidateErrorLinux(t *testing.T) {
mock := newMockExecutor()
mock.setError("lsblk", fmt.Errorf("command failed"))
// WithCPU on Linux reads files, not commands — might not fail.
// Use a component that requires the mock executor to ensure failure.
p := New().WithExecutor(mock)
// Don't enable any components — will get ErrNoIdentifiers
_, err := p.ID(context.Background())
if err == nil {
// No components enabled means no identifiers
t.Logf("No error with no components enabled (expected)")
}
}
func TestProviderCachedIDLinux(t *testing.T) {
mock := newMockExecutor()
mock.setOutput("lsblk", "SERIAL1\n")
p := New().WithExecutor(mock).WithDisk()
id1, err := p.ID(context.Background())
if err != nil {
t.Fatalf("First ID() error: %v", err)
}
mock.setOutput("lsblk", "SERIAL2\n")
id2, err := p.ID(context.Background())
if err != nil {
t.Fatalf("Second ID() error: %v", err)
}
if id1 != id2 {
t.Error("Cached ID was modified on subsequent call")
}
}
// --- readFirstValidFromLocations tests ---
func TestReadFirstValidFromLocationsAllFail(t *testing.T) {
locations := []string{
"/nonexistent/path/1",
"/nonexistent/path/2",
}
_, err := readFirstValidFromLocations(locations, isNonEmpty, nil)
if err == nil {
t.Error("Expected error when all locations fail")
}
if !errors.Is(err, ErrNotFound) {
t.Errorf("Expected ErrNotFound, got %v", err)
}
}
func TestReadFirstValidFromLocationsWithLogger(t *testing.T) {
var buf bytes.Buffer
logger := slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug}))
locations := []string{"/nonexistent/path/test"}
if _, err := readFirstValidFromLocations(locations, isNonEmpty, logger); err == nil {
t.Error("Expected error for nonexistent path")
}
if !bytes.Contains(buf.Bytes(), []byte("failed to read file")) {
t.Error("Expected 'failed to read file' in log")
}
}