-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathrobust_test.go
More file actions
630 lines (550 loc) · 18.8 KB
/
Copy pathrobust_test.go
File metadata and controls
630 lines (550 loc) · 18.8 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
// 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"
"fmt"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestReadNDEFWithRetry_FunctionExists verifies that the robust reading functions exist and can be called
func TestReadNDEFWithRetry_FunctionExists(t *testing.T) {
t.Parallel()
device, mockTransport := createMockDeviceWithTransport(t)
// Test NTAG ReadNDEFWithRetry exists
uid := []byte{0x04, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB}
ntagTag := NewNTAGTag(device, uid, 0x00)
// Mock an empty NDEF response that should trigger ErrNoNDEF
mockTransport.SetResponse(0x40, []byte{
0x41, 0x00, // InDataExchange response + success status
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Empty block
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
})
_, err := ntagTag.ReadNDEFWithRetry(context.Background())
require.Error(t, err) // Should error because no NDEF data
t.Log("✓ NTAGTag.ReadNDEFWithRetry(context.Background()) function exists and callable")
// Test MIFARE ReadNDEFWithRetry exists
mifareUID := []byte{0x04, 0x12, 0x34, 0x56}
mifareTag := NewMIFARETag(device, mifareUID, 0x00)
// Reset mock for MIFARE test
mockTransport.Reset()
// Mock auth failure - this means tag is not NDEF formatted, should return empty NDEF
mockTransport.SetError(0x40, errors.New("authentication failed"))
msg, err := mifareTag.ReadNDEFWithRetry(context.Background())
require.NoError(t, err) // Auth failure = not NDEF formatted = empty NDEF, not error
require.NotNil(t, msg)
require.Empty(t, msg.Records)
t.Log("✓ MIFARETag.ReadNDEFWithRetry(context.Background()) function exists and callable")
}
// TestErrorTypeEnhancements verifies that the new error types exist
func TestErrorTypeEnhancements(t *testing.T) {
t.Parallel()
// Test that new error types exist
require.Error(t, ErrTagEmptyData)
require.Error(t, ErrTagDataCorrupt)
require.Error(t, ErrTagUnreliable)
// Test error type identification
require.Equal(t, "tag detected but returned empty data", ErrTagEmptyData.Error())
require.Equal(t, "tag data appears corrupted", ErrTagDataCorrupt.Error())
require.Equal(t, "tag readings are inconsistent", ErrTagUnreliable.Error())
t.Log("✓ New error types are properly defined")
}
// TestIsRetryableError verifies the retry logic helper functions
func TestIsRetryableError(t *testing.T) {
t.Parallel()
tests := []struct {
err error
name string
expected bool
}{
{name: "nil error", err: nil, expected: false},
{name: "auth error 14", err: NewPN532Error(0x14, "InDataExchange", "authentication error"), expected: true},
{name: "timeout error", err: ErrTransportTimeout, expected: true},
{name: "read failure", err: fmt.Errorf("%w: block 5", ErrTagReadFailed), expected: true},
{name: "other error", err: errors.New("some other error"), expected: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
result := isRetryableError(tt.err)
require.Equal(t, tt.expected, result)
})
}
t.Log("✓ isRetryableError() works correctly")
}
// TestIsMifareRetryableError verifies MIFARE-specific retry logic
func TestIsMifareRetryableError(t *testing.T) {
t.Parallel()
tests := []struct {
err error
name string
expected bool
}{
{name: "nil error", err: nil, expected: false},
{name: "auth failed", err: fmt.Errorf("%w: sector 1", ErrTagAuthFailed), expected: true},
{name: "timeout error", err: ErrTransportTimeout, expected: true},
{name: "read failure", err: fmt.Errorf("%w: block 4", ErrTagReadFailed), expected: true},
{name: "data exchange error", err: NewPN532Error(0x01, "InDataExchange", "timeout"), expected: true},
{name: "other error", err: errors.New("some other error"), expected: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
result := isMifareRetryableError(tt.err)
require.Equal(t, tt.expected, result)
})
}
t.Log("✓ isMifareRetryableError() works correctly")
}
// TestReadNDEFWithRetry tests the core retry logic function
//
//nolint:revive,funlen // Function complexity and length are necessary to test 6 comprehensive retry scenarios
func TestReadNDEFWithRetry(t *testing.T) {
t.Parallel()
tests := []struct {
expectedError error
setupFunc func() (ReadNDEFFunc, IsRetryableFunc)
expectedResult *NDEFMessage
name string
}{
{
name: "Success on first attempt",
setupFunc: func() (ReadNDEFFunc, IsRetryableFunc) {
msg := &NDEFMessage{
Records: []NDEFRecord{
{Type: NDEFTypeText, Payload: []byte("Hello")},
},
}
readFunc := func() (*NDEFMessage, error) {
return msg, nil
}
retryFunc := func(_ error) bool {
return false // Shouldn't be called
}
return readFunc, retryFunc
},
expectedResult: &NDEFMessage{
Records: []NDEFRecord{
{Type: NDEFTypeText, Payload: []byte("Hello")},
},
},
},
{
name: "Empty data is valid success",
setupFunc: func() (ReadNDEFFunc, IsRetryableFunc) {
readFunc := func() (*NDEFMessage, error) {
// Return empty data - this is valid (e.g., tag with [03 00 FE] TLV)
return &NDEFMessage{Records: []NDEFRecord{}}, nil
}
retryFunc := func(_ error) bool {
return false
}
return readFunc, retryFunc
},
expectedResult: &NDEFMessage{
Records: []NDEFRecord{}, // Empty is valid
},
},
{
name: "Retryable error then success",
setupFunc: func() (ReadNDEFFunc, IsRetryableFunc) {
attempt := 0
readFunc := func() (*NDEFMessage, error) {
attempt++
if attempt == 1 {
return nil, ErrTransportTimeout
}
// Success on second attempt
return &NDEFMessage{
Records: []NDEFRecord{
{Type: NDEFTypeText, Payload: []byte("Retry Success")},
},
}, nil
}
retryFunc := func(err error) bool {
return errors.Is(err, ErrTransportTimeout)
}
return readFunc, retryFunc
},
expectedResult: &NDEFMessage{
Records: []NDEFRecord{
{Type: NDEFTypeText, Payload: []byte("Retry Success")},
},
},
},
{
name: "Non-retryable error fails immediately",
setupFunc: func() (ReadNDEFFunc, IsRetryableFunc) {
readFunc := func() (*NDEFMessage, error) {
return nil, ErrDeviceNotFound
}
retryFunc := func(_ error) bool {
return false // Device not found is not retryable
}
return readFunc, retryFunc
},
expectedError: ErrDeviceNotFound,
},
{
name: "Retryable error exhausts retries",
setupFunc: func() (ReadNDEFFunc, IsRetryableFunc) {
readFunc := func() (*NDEFMessage, error) {
return nil, ErrTransportTimeout
}
retryFunc := func(err error) bool {
return errors.Is(err, ErrTransportTimeout)
}
return readFunc, retryFunc
},
expectedError: ErrTransportTimeout,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
readFunc, retryFunc := tt.setupFunc()
result, err := readNDEFWithRetry(readFunc, retryFunc, "TEST")
if tt.expectedError != nil {
require.Error(t, err)
require.ErrorIs(t, err, tt.expectedError,
"Expected error %v, got %v", tt.expectedError, err)
require.Nil(t, result)
} else {
require.NoError(t, err)
require.NotNil(t, result)
require.Len(t, result.Records, len(tt.expectedResult.Records))
if len(result.Records) > 0 {
require.Equal(t, tt.expectedResult.Records[0].Type, result.Records[0].Type)
require.Equal(t, tt.expectedResult.Records[0].Payload, result.Records[0].Payload)
}
}
})
}
}
// TestNTAGReadNDEFWithRetry tests NTAG robust reading functionality
func TestNTAGReadNDEFWithRetry(t *testing.T) {
t.Parallel()
tests := []struct {
errorType error
setupMock func(*MockTransport)
name string
expectError bool
}{
{
name: "Success after retry",
setupMock: func(mt *MockTransport) {
// First call returns empty data
mt.SetResponse(0x40, []byte{
0x41, 0x00, // InDataExchange response + success status
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Empty block
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
})
// Second call would get better data, but we'll simulate the "no NDEF" scenario
},
expectError: true,
errorType: ErrNoNDEF, // Empty data will result in no valid NDEF
},
{
name: "Read failure then authentication fallback",
setupMock: func(mt *MockTransport) {
// First call gets PN532 authentication error (0x14)
mt.SetResponse(0x40, []byte{0x7F, 0x14})
// Fallback to InCommunicateThru succeeds
mt.SetResponse(0x42, []byte{
0x43, 0x00, // InCommunicateThru response + success
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Empty block
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
})
},
expectError: true,
errorType: ErrTagReadFailed, // Auth error propagates as read failure
},
{
name: "Timeout error triggers retry logic",
setupMock: func(mt *MockTransport) {
// Simulate transport timeout
mt.SetError(0x40, ErrTransportTimeout)
},
expectError: true,
errorType: ErrTransportTimeout,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
device, mockTransport := createMockDeviceWithTransport(t)
tt.setupMock(mockTransport)
uid := []byte{0x04, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB}
tag := NewNTAGTag(device, uid, 0x00)
_, err := tag.ReadNDEFWithRetry(context.Background())
if tt.expectError {
require.Error(t, err)
if tt.errorType != nil {
require.True(t, errors.Is(err, tt.errorType) ||
strings.Contains(err.Error(), tt.errorType.Error()),
"Expected error type %v, got %v", tt.errorType, err)
}
} else {
require.NoError(t, err)
}
})
}
}
// TestMIFAREReadNDEFWithRetry tests MIFARE robust reading functionality
func TestMIFAREReadNDEFWithRetry(t *testing.T) {
t.Parallel()
tests := []struct {
errorType error
setupMock func(*MockTransport)
name string
expectError bool
}{
{
name: "Authentication failure returns empty NDEF",
setupMock: func(mt *MockTransport) {
// Authentication will fail - but this is now treated as "not NDEF formatted"
// and returns empty NDEF instead of error (consistent with NTAG behavior)
mt.SetError(0x40, NewPN532Error(0x14, "InDataExchange", "auth failed"))
},
expectError: false, // Auth failure on sector 1 = not NDEF formatted = empty NDEF
errorType: nil,
},
{
name: "Read failure after auth success",
setupMock: func(mt *MockTransport) {
// Set up authentication success first
mt.SetResponse(0x40, []byte{0x41, 0x00}) // Auth success
// Then read failure - this should still error (auth succeeded, read failed)
mt.SetError(0x40, ErrTagReadFailed)
},
expectError: true,
errorType: ErrTagReadFailed,
},
{
name: "Transport timeout triggers retry",
setupMock: func(mt *MockTransport) {
// Transport timeout is a communication error, not auth failure
mt.SetError(0x40, ErrTransportTimeout)
},
expectError: true,
errorType: ErrTransportTimeout,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
device, mockTransport := createMockDeviceWithTransport(t)
tt.setupMock(mockTransport)
uid := []byte{0x04, 0x12, 0x34, 0x56}
tag := NewMIFARETag(device, uid, 0x00)
_, err := tag.ReadNDEFWithRetry(context.Background())
if tt.expectError {
require.Error(t, err)
if tt.errorType != nil {
require.True(t, errors.Is(err, tt.errorType) ||
strings.Contains(err.Error(), tt.errorType.Error()),
"Expected error type %v, got %v", tt.errorType, err)
}
} else {
require.NoError(t, err)
}
})
}
}
// TestRetryHelperFunctions tests the helper functions for error classification
func TestRetryHelperFunctions(t *testing.T) {
t.Parallel()
t.Run("isRetryableError", func(t *testing.T) {
t.Parallel()
tests := []struct {
err error
name string
want bool
}{
{name: "nil error", err: nil, want: false},
{name: "transport timeout", err: ErrTransportTimeout, want: true},
{name: "tag read failed", err: ErrTagReadFailed, want: true},
{name: "device not found", err: ErrDeviceNotFound, want: false},
{name: "PN532 timeout", err: NewPN532Error(0x01, "InDataExchange", ""), want: true},
{name: "PN532 auth error", err: NewPN532Error(0x14, "InDataExchange", ""), want: true},
{name: "PN532 command not supported", err: NewPN532Error(0x81, "InDataExchange", ""), want: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
got := isRetryableError(tt.err)
require.Equal(t, tt.want, got)
})
}
})
t.Run("isMifareRetryableError", func(t *testing.T) {
t.Parallel()
tests := []struct {
err error
name string
want bool
}{
{name: "nil error", err: nil, want: false},
{name: "auth failed", err: ErrTagAuthFailed, want: true},
{name: "read failed", err: ErrTagReadFailed, want: true},
{name: "transport timeout", err: ErrTransportTimeout, want: true},
{name: "device not found", err: ErrDeviceNotFound, want: false},
{name: "PN532 timeout", err: NewPN532Error(0x01, "InDataExchange", ""), want: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
got := isMifareRetryableError(tt.err)
require.Equal(t, tt.want, got)
})
}
})
}
// TestWriteNDEFWithRetry tests the write retry logic function
//
//nolint:revive,funlen // Function complexity and length are necessary to test comprehensive retry scenarios
func TestWriteNDEFWithRetry(t *testing.T) {
t.Parallel()
t.Run("Success on first attempt", func(t *testing.T) {
t.Parallel()
var attempts int32
writeFunc := func(_ context.Context) error {
atomic.AddInt32(&attempts, 1)
return nil
}
err := WriteNDEFWithRetry(context.Background(), writeFunc, 3, "TEST")
require.NoError(t, err)
assert.Equal(t, int32(1), atomic.LoadInt32(&attempts), "Should only attempt once on success")
})
t.Run("Retryable error then success", func(t *testing.T) {
t.Parallel()
var attempts int32
writeFunc := func(_ context.Context) error {
count := atomic.AddInt32(&attempts, 1)
if count < 3 {
return ErrTransportTimeout // Retryable
}
return nil // Success on 3rd attempt
}
err := WriteNDEFWithRetry(context.Background(), writeFunc, 3, "TEST")
require.NoError(t, err)
assert.Equal(t, int32(3), atomic.LoadInt32(&attempts), "Should retry until success")
})
t.Run("Non-retryable error fails immediately", func(t *testing.T) {
t.Parallel()
var attempts int32
writeFunc := func(_ context.Context) error {
atomic.AddInt32(&attempts, 1)
return ErrDeviceNotFound // Not retryable
}
err := WriteNDEFWithRetry(context.Background(), writeFunc, 3, "TEST")
require.Error(t, err)
require.ErrorIs(t, err, ErrDeviceNotFound)
assert.Equal(t, int32(1), atomic.LoadInt32(&attempts), "Should not retry non-retryable errors")
})
t.Run("Retryable error exhausts all retries", func(t *testing.T) {
t.Parallel()
var attempts int32
writeFunc := func(_ context.Context) error {
atomic.AddInt32(&attempts, 1)
return ErrTransportTimeout // Always fail with retryable error
}
err := WriteNDEFWithRetry(context.Background(), writeFunc, 3, "TEST")
require.Error(t, err)
assert.Contains(t, err.Error(), "failed to write TEST NDEF data after 3 retries")
require.ErrorIs(t, err, ErrTransportTimeout)
assert.Equal(t, int32(3), atomic.LoadInt32(&attempts), "Should exhaust all retries")
})
t.Run("Context cancellation before first attempt", func(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(context.Background())
cancel() // Cancel immediately
var attempts int32
writeFunc := func(_ context.Context) error {
atomic.AddInt32(&attempts, 1)
return nil
}
err := WriteNDEFWithRetry(ctx, writeFunc, 3, "TEST")
require.Error(t, err)
require.ErrorIs(t, err, context.Canceled)
assert.Equal(t, int32(0), atomic.LoadInt32(&attempts), "Should not attempt when context is already cancelled")
})
t.Run("Context cancellation during retry delay", func(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(context.Background())
var attempts int32
writeFunc := func(_ context.Context) error {
count := atomic.AddInt32(&attempts, 1)
if count == 1 {
// Cancel after first failure, during the retry delay
go func() {
time.Sleep(10 * time.Millisecond)
cancel()
}()
return ErrTransportTimeout // Trigger retry
}
return nil
}
start := time.Now()
err := WriteNDEFWithRetry(ctx, writeFunc, 3, "TEST")
elapsed := time.Since(start)
require.Error(t, err)
require.ErrorIs(t, err, context.Canceled)
assert.Equal(t, int32(1), atomic.LoadInt32(&attempts), "Should stop after context cancellation")
// Should cancel during the 100ms delay, not wait the full delay
assert.Less(t, elapsed, 80*time.Millisecond, "Should cancel quickly, not wait for full delay")
})
t.Run("Default max retries when zero provided", func(t *testing.T) {
t.Parallel()
var attempts int32
writeFunc := func(_ context.Context) error {
atomic.AddInt32(&attempts, 1)
return ErrTransportTimeout
}
err := WriteNDEFWithRetry(context.Background(), writeFunc, 0, "TEST")
require.Error(t, err)
assert.Equal(t, int32(3), atomic.LoadInt32(&attempts), "Should default to 3 retries when 0 provided")
})
t.Run("ACK error is not retried", func(t *testing.T) {
t.Parallel()
var attempts int32
writeFunc := func(_ context.Context) error {
atomic.AddInt32(&attempts, 1)
return ErrNoACK // ACK error is NOT retryable (transport already retried)
}
err := WriteNDEFWithRetry(context.Background(), writeFunc, 3, "TEST")
require.Error(t, err)
assert.Equal(t, int32(1), atomic.LoadInt32(&attempts), "Should NOT retry on ACK errors")
})
t.Run("PN532 timeout error is retried", func(t *testing.T) {
t.Parallel()
var attempts int32
writeFunc := func(_ context.Context) error {
count := atomic.AddInt32(&attempts, 1)
if count < 2 {
return NewPN532Error(0x01, "InDataExchange", "") // Timeout
}
return nil
}
err := WriteNDEFWithRetry(context.Background(), writeFunc, 3, "TEST")
require.NoError(t, err)
assert.Equal(t, int32(2), atomic.LoadInt32(&attempts), "Should retry on PN532 timeout")
})
}