-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinux_test.go
More file actions
417 lines (343 loc) · 10.6 KB
/
linux_test.go
File metadata and controls
417 lines (343 loc) · 10.6 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
//go:build linux
package machineid
import (
"bytes"
"context"
"errors"
"fmt"
"log/slog"
"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 := parseCPUInfo(content)
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) {
result := parseCPUInfo("")
expected := ":::"
if result != expected {
t.Errorf("Expected %q for empty input, got %q", expected, result)
}
}
func TestParseCPUInfoPartial(t *testing.T) {
content := `processor : 3
vendor_id : AuthenticAMD
model name : AMD Ryzen 9 5950X
`
result := parseCPUInfo(content)
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"
result := parseCPUInfo(content)
expected := ":::"
if result != expected {
t.Errorf("Expected %q, got %q", expected, result)
}
}
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 := parseCPUInfo(content)
// 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))
}
}
// --- 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")
}
}