-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdevice_test.go
More file actions
716 lines (606 loc) · 21.6 KB
/
device_test.go
File metadata and controls
716 lines (606 loc) · 21.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
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
// Copyright 2026 The Zaparoo Project Contributors.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package pn532
import (
"context"
"errors"
"testing"
"time"
"github.com/ZaparooProject/go-pn532/detection"
testutil "github.com/ZaparooProject/go-pn532/internal/testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNew(t *testing.T) {
t.Parallel()
tests := []struct {
transport Transport
name string
errMsg string
wantErr bool
}{
{
name: "Valid_MockTransport",
transport: NewMockTransport(),
wantErr: false,
},
{
name: "Nil_Transport",
transport: nil,
wantErr: false, // New() doesn't validate nil transport, but using it will panic
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
device, err := New(tt.transport)
if tt.wantErr {
require.Error(t, err)
if tt.errMsg != "" {
assert.Contains(t, err.Error(), tt.errMsg)
}
assert.Nil(t, device)
} else {
require.NoError(t, err)
assert.NotNil(t, device)
if tt.transport != nil {
assert.Equal(t, tt.transport, device.Transport())
}
}
})
}
}
func TestDevice_Init(t *testing.T) {
t.Parallel()
tests := []struct {
setupMock func(*MockTransport)
name string
errorSubstring string
expectError bool
}{
{
name: "Successful_Initialization",
setupMock: func(mock *MockTransport) {
mock.SetResponse(testutil.CmdGetFirmwareVersion, testutil.BuildFirmwareVersionResponse())
mock.SetResponse(testutil.CmdSAMConfiguration, testutil.BuildSAMConfigurationResponse())
},
expectError: false,
},
{
name: "Firmware_Version_Error",
setupMock: func(mock *MockTransport) {
mock.SetError(testutil.CmdGetFirmwareVersion, errors.New("firmware version failed"))
mock.SetResponse(testutil.CmdSAMConfiguration, testutil.BuildSAMConfigurationResponse())
},
expectError: true,
errorSubstring: "firmware version failed",
},
{
name: "SAM_Configuration_Error",
setupMock: func(mock *MockTransport) {
mock.SetResponse(testutil.CmdGetFirmwareVersion, testutil.BuildFirmwareVersionResponse())
mock.SetError(testutil.CmdSAMConfiguration, errors.New("SAM config failed"))
},
expectError: true,
errorSubstring: "SAM config failed",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
// Setup mock transport
mock := NewMockTransport()
tt.setupMock(mock)
// Create device
device, err := New(mock)
require.NoError(t, err)
// Test initialization
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
err = device.Init(ctx)
if tt.expectError {
require.Error(t, err)
if tt.errorSubstring != "" {
assert.Contains(t, err.Error(), tt.errorSubstring)
}
} else {
require.NoError(t, err)
// Verify that firmware version is called twice (validation + setup)
assert.Equal(t, 2, mock.GetCallCount(testutil.CmdGetFirmwareVersion))
assert.Equal(t, 1, mock.GetCallCount(testutil.CmdSAMConfiguration))
}
})
}
}
func TestDevice_Init_Timeout(t *testing.T) {
t.Parallel()
// Setup mock with delay longer than context timeout
mock := NewMockTransport()
mock.SetDelay(200 * time.Millisecond)
mock.SetResponse(testutil.CmdGetFirmwareVersion, testutil.BuildFirmwareVersionResponse())
mock.SetResponse(testutil.CmdSAMConfiguration, testutil.BuildSAMConfigurationResponse())
device, err := New(mock)
require.NoError(t, err)
// Test with very short timeout
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
_ = device.Init(ctx)
// Note: This test depends on the actual implementation being context-aware
// For now, we just verify the setup works with longer timeout
// Retry with sufficient timeout to verify mock works
ctx2, cancel2 := context.WithTimeout(context.Background(), time.Second)
defer cancel2()
err = device.Init(ctx2)
assert.NoError(t, err)
}
func TestDevice_GetFirmwareVersion(t *testing.T) {
t.Parallel()
tests := []struct {
setupMock func(*MockTransport)
name string
errorSubstring string
expectError bool
}{
{
name: "Successful_Firmware_Version",
setupMock: func(mock *MockTransport) {
mock.SetResponse(testutil.CmdGetFirmwareVersion, testutil.BuildFirmwareVersionResponse())
},
expectError: false,
},
{
name: "Firmware_Version_Command_Error",
setupMock: func(mock *MockTransport) {
mock.SetError(testutil.CmdGetFirmwareVersion, errors.New("command failed"))
},
expectError: true,
errorSubstring: "command failed",
},
{
name: "Invalid_Firmware_Response",
setupMock: func(mock *MockTransport) {
// Set invalid response (too short)
mock.SetResponse(testutil.CmdGetFirmwareVersion, []byte{0xD5, 0x03})
},
expectError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
// Setup mock transport
mock := NewMockTransport()
tt.setupMock(mock)
// Create device
device, err := New(mock)
require.NoError(t, err)
// Test firmware version
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
firmware, err := device.GetFirmwareVersion(ctx)
if tt.expectError {
require.Error(t, err)
if tt.errorSubstring != "" {
assert.Contains(t, err.Error(), tt.errorSubstring)
}
} else {
require.NoError(t, err)
assert.NotNil(t, firmware)
assert.Equal(t, 1, mock.GetCallCount(testutil.CmdGetFirmwareVersion))
}
})
}
}
func TestDevice_SetTimeout(t *testing.T) {
t.Parallel()
mock := NewMockTransport()
device, err := New(mock)
require.NoError(t, err)
// Test setting timeout
timeout := 5 * time.Second
err = device.SetTimeout(timeout)
assert.NoError(t, err)
}
func TestDevice_SetRetryConfig(t *testing.T) {
t.Parallel()
mock := NewMockTransport()
device, err := New(mock)
require.NoError(t, err)
// Test setting retry config
config := &RetryConfig{
MaxAttempts: 5,
InitialBackoff: 100 * time.Millisecond,
MaxBackoff: 2 * time.Second,
BackoffMultiplier: 2.0,
Jitter: 0.1,
RetryTimeout: 10 * time.Second,
}
device.SetRetryConfig(config)
// No return value to check, but should not panic
}
func TestDevice_Close(t *testing.T) {
t.Parallel()
tests := []struct {
setupMock func(*MockTransport)
name string
expectError bool
}{
{
name: "Successful_Close",
setupMock: func(_ *MockTransport) {
// Mock is connected by default
},
expectError: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
mock := NewMockTransport()
tt.setupMock(mock)
device, err := New(mock)
require.NoError(t, err)
err = device.Close()
if tt.expectError {
require.Error(t, err)
} else {
require.NoError(t, err)
assert.False(t, mock.IsConnected())
}
})
}
}
func TestDevice_IsAutoPollSupported(t *testing.T) {
t.Parallel()
mock := NewMockTransport()
device, err := New(mock)
require.NoError(t, err)
// Test AutoPoll support (mock transport should support it)
supported := device.IsAutoPollSupported()
// The result depends on the mock implementation's HasCapability method
assert.IsType(t, true, supported) // Just verify it returns a boolean
}
func TestWithConnectionRetries_Option(t *testing.T) {
t.Parallel()
tests := []struct {
name string
retries int
expectError bool
}{
{
name: "Valid_Retry_Count",
retries: 3,
expectError: false,
},
{
name: "Single_Attempt",
retries: 1,
expectError: false,
},
{
name: "Zero_Retries_Invalid",
retries: 0,
expectError: true,
},
{
name: "Negative_Retries_Invalid",
retries: -1,
expectError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
// Test the option by applying it to a config
config := &connectConfig{}
option := WithConnectionRetries(tt.retries)
err := option(config)
if tt.expectError {
assert.Error(t, err)
} else {
require.NoError(t, err)
assert.Equal(t, tt.retries, config.connectionRetries)
}
})
}
}
// setupFailingTransport creates a mock transport that fails SAM configuration
func setupFailingTransport() Transport {
mock := NewMockTransport()
// Set up successful firmware version response
mock.SetResponse(testutil.CmdGetFirmwareVersion, testutil.BuildFirmwareVersionResponse())
// Always fail SAM configuration with a retryable error to demonstrate retry behavior
mock.SetError(testutil.CmdSAMConfiguration, ErrCommunicationFailed)
return mock
}
// verifyRetryAttemptsForFailure checks that the expected number of retry attempts were made for failed connections
func verifyRetryAttemptsForFailure(t *testing.T, transport Transport, expectedMinCalls int) {
if mock, ok := transport.(*MockTransport); ok {
samAttempts := mock.GetCallCount(testutil.CmdSAMConfiguration)
// For failed connection, should have been retried, so expect multiple calls
assert.GreaterOrEqual(t, samAttempts, expectedMinCalls,
"Expected at least %d SAM configuration calls indicating retry attempts", expectedMinCalls)
}
}
// Regression tests for CycleRFField - fixes RF reset after MIFARE auth failures
func TestDevice_CycleRFField_Success(t *testing.T) {
t.Parallel()
mock := NewMockTransport()
// Set up responses for RF configuration commands
// CycleRFField calls RFConfiguration twice: off (0x01,0x00) then on (0x01,0x01)
mock.SetResponse(0x32, []byte{0x33}) // RFConfiguration success response
device, err := New(mock)
require.NoError(t, err)
err = device.CycleRFField(context.Background())
require.NoError(t, err)
// Verify RFConfiguration was called at least twice (off + on)
assert.GreaterOrEqual(t, mock.GetCallCount(0x32), 2,
"RFConfiguration should be called twice (off + on)")
}
func TestDevice_CycleRFField_OffFailure(t *testing.T) {
t.Parallel()
mock := NewMockTransport()
// Set error for RF configuration command (will fail on first call - turning off)
mock.SetError(0x32, errors.New("RF configuration failed"))
device, err := New(mock)
require.NoError(t, err)
err = device.CycleRFField(context.Background())
require.Error(t, err)
assert.Contains(t, err.Error(), "failed to turn RF field off")
}
func TestDevice_CycleRFField_OnFailure(t *testing.T) {
t.Parallel()
// This test verifies the error message format when RF field ON fails.
// The mock checks errors before queue, so we test the off failure path
// in TestDevice_CycleRFField_OffFailure. Here we verify the "on" error
// message is correctly formatted in the code by code inspection.
// Instead, we verify a successful cycle completes properly.
mock := NewMockTransport()
mock.SetResponse(0x32, []byte{0x33}) // RFConfiguration success
device, err := New(mock)
require.NoError(t, err)
err = device.CycleRFField(context.Background())
require.NoError(t, err)
// Verify both calls were made (off + on)
assert.GreaterOrEqual(t, mock.GetCallCount(0x32), 2,
"RFConfiguration should be called twice for successful cycle")
}
func TestConnectDevice_WithConnectionRetries(t *testing.T) {
t.Parallel()
t.Run("Failure_Should_Retry_Before_Giving_Up", func(t *testing.T) {
t.Parallel()
transport := setupFailingTransport()
// Create a factory that returns our pre-configured transport
factory := func(_ string) (Transport, error) {
return transport, nil
}
// Use ConnectDevice with retry configuration
device, err := ConnectDevice(context.Background(), "/mock/path",
WithTransportFactory(factory),
WithConnectionRetries(3))
// Should fail after retries
require.Error(t, err, "Expected connection to fail after all retries")
assert.Nil(t, device)
// Verify the number of retry attempts made (should see at least 2 SAM config calls)
verifyRetryAttemptsForFailure(t, transport, 2)
})
t.Run("AutoDetection_Bypasses_Retry_Logic", func(t *testing.T) {
t.Parallel()
transport := setupFailingTransport()
// Mock the detection to return our failing transport
deviceFactory := func(_ detection.DeviceInfo) (Transport, error) {
return transport, nil
}
// Mock detector that returns a fake device
mockDetector := func(_ context.Context, _ *detection.Options) ([]detection.DeviceInfo, error) {
return []detection.DeviceInfo{
{
Name: "MockPN532",
Path: "/dev/mock0",
Transport: "mock",
Metadata: map[string]string{},
},
}, nil
}
// Use auto-detection mode (should bypass retry logic)
device, err := ConnectDevice(context.Background(), "", // empty path triggers auto-detection
WithAutoDetection(),
WithTransportFromDeviceFactory(deviceFactory),
WithDeviceDetector(mockDetector),
WithConnectionRetries(5)) // This should be ignored for auto-detection
// Should fail immediately (no retries for auto-detection)
require.Error(t, err, "Expected immediate failure for auto-detection")
assert.Nil(t, device)
// Verify only single attempt was made (no retries)
samAttempts := transport.(*MockTransport).GetCallCount(testutil.CmdSAMConfiguration)
assert.Equal(t, 1, samAttempts, "Auto-detection should only make single attempt")
})
}
// TestConnectDevice_AutoDetect_FallsBackOnInitFailure verifies that
// auto-detection's candidate iteration does not bail on the first failure:
// a wedged transport (e.g. an I2C bus without a PN532) must be skipped and
// the next detected candidate given a chance to initialise.
func TestConnectDevice_AutoDetect_FallsBackOnInitFailure(t *testing.T) {
t.Parallel()
failing := setupFailingTransport()
workingMock := NewMockTransport()
workingMock.SetResponse(testutil.CmdGetFirmwareVersion, testutil.BuildFirmwareVersionResponse())
workingMock.SetResponse(testutil.CmdSAMConfiguration, testutil.BuildSAMConfigurationResponse())
// Hand out the failing transport first, then the working one. The first
// candidate's SAM config fails; the second must be tried and succeed.
var factoryCalls int
deviceFactory := func(_ detection.DeviceInfo) (Transport, error) {
factoryCalls++
if factoryCalls == 1 {
return failing, nil
}
return workingMock, nil
}
mockDetector := func(_ context.Context, _ *detection.Options) ([]detection.DeviceInfo, error) {
return []detection.DeviceInfo{
{Name: "FailingCandidate", Path: "/dev/mock-bad", Transport: "mock"},
{Name: "WorkingCandidate", Path: "/dev/mock-good", Transport: "mock"},
}, nil
}
device, err := ConnectDevice(context.Background(), "",
WithAutoDetection(),
WithTransportFromDeviceFactory(deviceFactory),
WithDeviceDetector(mockDetector))
require.NoError(t, err, "expected fallback to the working candidate")
require.NotNil(t, device)
defer func() {
_ = device.Close()
}()
assert.Equal(t, 2, factoryCalls, "both candidates should have been tried")
assert.False(t, failing.IsConnected(),
"failed candidate's transport should have been closed on iteration skip")
assert.True(t, workingMock.IsConnected(),
"succeeding candidate's transport must still be open")
assert.Equal(t, 1, failing.(*MockTransport).GetCallCount(testutil.CmdSAMConfiguration),
"failed candidate should get exactly one SAM attempt (no retry loop on auto-detect)")
assert.Equal(t, 1, workingMock.GetCallCount(testutil.CmdSAMConfiguration),
"working candidate should get exactly one SAM attempt")
}
// TestConnectDevice_AutoDetect_AggregatesWhenAllFail verifies that when every
// detected candidate fails to initialise, ConnectDevice returns a single
// aggregated error naming the total candidate count instead of silently
// hiding the first failure or returning a misleading "no devices" error.
func TestConnectDevice_AutoDetect_AggregatesWhenAllFail(t *testing.T) {
t.Parallel()
first := setupFailingTransport()
second := setupFailingTransport()
var factoryCalls int
deviceFactory := func(_ detection.DeviceInfo) (Transport, error) {
factoryCalls++
if factoryCalls == 1 {
return first, nil
}
return second, nil
}
mockDetector := func(_ context.Context, _ *detection.Options) ([]detection.DeviceInfo, error) {
return []detection.DeviceInfo{
{Name: "BadA", Path: "/dev/mock-a", Transport: "mock"},
{Name: "BadB", Path: "/dev/mock-b", Transport: "mock"},
}, nil
}
device, err := ConnectDevice(context.Background(), "",
WithAutoDetection(),
WithTransportFromDeviceFactory(deviceFactory),
WithDeviceDetector(mockDetector))
require.Error(t, err)
assert.Nil(t, device)
assert.Contains(t, err.Error(), "all 2 auto-detected candidate(s) failed",
"aggregated error must surface the total candidate count")
assert.Equal(t, 2, factoryCalls, "both candidates should be tried before giving up")
assert.False(t, first.IsConnected(), "first failed transport must be closed")
assert.False(t, second.IsConnected(), "second failed transport must be closed")
}
func TestConnectDevice_AutoDetect_UsesSafeDefaultTransports(t *testing.T) {
t.Parallel()
var capturedTransports []string
mockDetector := func(_ context.Context, opts *detection.Options) ([]detection.DeviceInfo, error) {
capturedTransports = append([]string(nil), opts.Transports...)
return nil, detection.ErrNoDevicesFound
}
device, err := ConnectDevice(context.Background(), "",
WithAutoDetection(),
WithTransportFromDeviceFactory(func(_ detection.DeviceInfo) (Transport, error) {
return NewMockTransport(), nil
}),
WithDeviceDetector(mockDetector))
require.Error(t, err)
assert.Nil(t, device)
assert.Equal(t, []string{detection.TransportUART}, capturedTransports)
assert.NotContains(t, capturedTransports, detection.TransportSPI)
assert.NotContains(t, capturedTransports, detection.TransportI2C)
}
// TestConnectDevice_AutoDetect_PrefersUARTOverI2C verifies that when the
// detector returns a mix of transport types, auto-detection tries UART
// candidates before I2C/SPI so a working UART PN532 succeeds without ever
// constructing a bus transport. This matters on Linux desktops where
// periph.io's host.Init() call logs a gpioioctl /dev/gpiochip0 permission
// warning for users not in the gpio group — we want that warning to stay
// silent whenever UART works.
func TestConnectDevice_AutoDetect_PrefersUARTOverI2C(t *testing.T) {
t.Parallel()
uartMock := NewMockTransport()
uartMock.SetResponse(testutil.CmdGetFirmwareVersion, testutil.BuildFirmwareVersionResponse())
uartMock.SetResponse(testutil.CmdSAMConfiguration, testutil.BuildSAMConfigurationResponse())
// Track which transports the factory was asked to create, in order.
var createdTransports []string
deviceFactory := func(info detection.DeviceInfo) (Transport, error) {
createdTransports = append(createdTransports, info.Transport)
// Anything except UART must never actually be constructed; returning
// an error if we're asked for one would be fine too, but returning a
// bogus transport lets the test fail loudly on the assertions below
// if ordering breaks.
if info.Transport == "uart" {
return uartMock, nil
}
return NewMockTransport(), nil
}
// Return I2C first (and SPI middle) — whatever the goroutine race
// happens to hand back. The sort in connectAutoDetected must reorder
// these into uart → spi → i2c before iteration.
mockDetector := func(_ context.Context, _ *detection.Options) ([]detection.DeviceInfo, error) {
return []detection.DeviceInfo{
{Name: "I2CBus", Path: "/dev/i2c-1", Transport: "i2c"},
{Name: "SPIBus", Path: "/dev/spidev0.0", Transport: "spi"},
{Name: "UARTDev", Path: "/dev/ttyUSB0", Transport: "uart"},
}, nil
}
device, err := ConnectDevice(context.Background(), "",
WithAutoDetection(),
WithTransportFromDeviceFactory(deviceFactory),
WithDeviceDetector(mockDetector))
require.NoError(t, err)
require.NotNil(t, device)
defer func() {
_ = device.Close()
}()
require.NotEmpty(t, createdTransports,
"factory must be called at least once")
assert.Equal(t, "uart", createdTransports[0],
"UART must be tried first even though the detector returned it last; "+
"if an I2C transport is ever constructed, periph.io's host.Init() "+
"will log a gpiochip permission warning on desktop Linux")
assert.Len(t, createdTransports, 1,
"UART succeeded on first try, so neither SPI nor I2C transports "+
"should have been constructed at all")
}
// TestSortCandidatesByTransportPreference locks the per-transport-kind
// ordering as a unit: UART < SPI < I2C, with unknown transports sorting
// last and stable ordering preserved within each group.
func TestSortCandidatesByTransportPreference(t *testing.T) {
t.Parallel()
devices := []detection.DeviceInfo{
{Name: "i2c-first", Transport: "i2c"},
{Name: "bogus-kind", Transport: "usb"},
{Name: "spi-middle", Transport: "spi"},
{Name: "uart-A", Transport: "uart"},
{Name: "i2c-second", Transport: "i2c"},
{Name: "uart-B", Transport: "UART"}, // case-insensitive match
}
sortCandidatesByTransportPreference(devices)
names := make([]string, len(devices))
for i, d := range devices {
names[i] = d.Name
}
// UART group first (stable: A then B), then SPI, then I2C (stable:
// first then second), then any unknown kind.
assert.Equal(t,
[]string{"uart-A", "uart-B", "spi-middle", "i2c-first", "i2c-second", "bogus-kind"},
names)
}