-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy patherror_scenarios_test.go
More file actions
352 lines (295 loc) · 8.82 KB
/
error_scenarios_test.go
File metadata and controls
352 lines (295 loc) · 8.82 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
package extsort_test
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"github.com/lanrat/extsort"
)
// TestSerializationError tests handling of ToBytes() failures
func TestSerializationError(t *testing.T) {
inputChan := make(chan extsort.SortType, 10)
// Add more items to ensure multi-chunk behavior
for i := 0; i < 8; i++ {
inputChan <- val{Key: i, Order: i}
}
errorItem := &errorVal{shouldFail: true}
t.Logf("Adding errorVal with shouldFail=true: %+v", errorItem)
inputChan <- errorItem // This will fail ToBytes()
inputChan <- val{Key: 9, Order: 9} // Add one more after error
close(inputChan)
// Force multiple chunks to trigger serialization
config := &extsort.Config{ChunkSize: 3} // Create multiple chunks
sort, outChan, errChan := extsort.New(inputChan, fromBytesForTest, func(a, b extsort.SortType) bool {
// Handle mixed types safely
av, aok := a.(val)
bv, bok := b.(val)
if aok && bok {
return av.Key < bv.Key
}
return false // Fallback for error types
}, config)
sort.Sort(context.Background())
// Drain output and count results
resultCount := 0
for result := range outChan {
resultCount++
t.Logf("Output %d: %T = %+v", resultCount, result, result)
// Consume output
}
t.Logf("Got %d results from output channel", resultCount)
// Should now get a proper error instead of panic
if err := <-errChan; err != nil {
t.Logf("Got expected serialization error: %v", err)
// Verify it's our specific error type
var serErr *extsort.SerializationError
if !errors.As(err, &serErr) {
t.Errorf("Expected SerializationError, got: %T", err)
}
if !strings.Contains(err.Error(), "serialization panic") {
t.Errorf("Expected 'serialization panic' in error message, got: %v", err)
}
} else {
t.Fatal("Expected serialization error, got nil")
}
}
// TestDeserializationError tests handling of FromBytes() failures
func TestDeserializationError(t *testing.T) {
inputChan := make(chan extsort.SortType, 3)
for i := 0; i < 3; i++ {
inputChan <- val{Key: i, Order: i}
}
close(inputChan)
// Use a FromBytes function that always fails
failingFromBytes := func(data []byte) extsort.SortType {
panic("deserialization failed") // Simulate critical failure
}
sort, outChan, errChan := extsort.New(inputChan, failingFromBytes, KeyLessThan, nil)
// This should panic or fail gracefully during merge phase
defer func() {
if r := recover(); r != nil {
t.Logf("Expected panic during deserialization: %v", r)
}
}()
sort.Sort(context.Background())
// Drain output
for range outChan {
// Consume output
}
// If we get here, check for error
if err := <-errChan; err != nil {
t.Logf("Got expected deserialization error: %v", err)
// Verify it's our specific error type
var deserErr *extsort.DeserializationError
if !errors.As(err, &deserErr) {
t.Errorf("Expected DeserializationError, got: %T", err)
}
}
}
// TestNilInputs tests behavior with nil function parameters
func TestNilInputs(t *testing.T) {
inputChan := make(chan extsort.SortType, 1)
inputChan <- val{Key: 1, Order: 1}
close(inputChan)
// Test with nil fromBytes function
func() {
defer func() {
if r := recover(); r != nil {
t.Logf("Expected panic with nil fromBytes: %v", r)
}
}()
sort, _, _ := extsort.New(inputChan, nil, KeyLessThan, nil)
sort.Sort(context.Background())
}()
// Recreate input for next test
inputChan2 := make(chan extsort.SortType, 1)
inputChan2 <- val{Key: 1, Order: 1}
close(inputChan2)
// Test with nil comparison function
func() {
defer func() {
if r := recover(); r != nil {
t.Logf("Expected panic with nil lessFunc: %v", r)
}
}()
sort, _, _ := extsort.New(inputChan2, fromBytesForTest, nil, nil)
sort.Sort(context.Background())
}()
}
// TestLargeDataElements tests with unusually large individual elements
func TestLargeDataElements(t *testing.T) {
inputChan := make(chan extsort.SortType, 3)
// Create elements with large data
largeString := make([]byte, 1024*1024) // 1MB element
for i := range largeString {
largeString[i] = byte('A' + (i % 26))
}
// Add a few large elements
inputChan <- &largeVal{Key: 3, Data: largeString}
inputChan <- &largeVal{Key: 1, Data: largeString}
inputChan <- &largeVal{Key: 2, Data: largeString}
close(inputChan)
sort, outChan, errChan := extsort.New(inputChan, fromBytesForLargeVal, largeLessThan, nil)
sort.Sort(context.Background())
var results []*largeVal
for rec := range outChan {
results = append(results, rec.(*largeVal))
}
if err := <-errChan; err != nil {
t.Fatalf("unexpected error with large elements: %v", err)
}
if len(results) != 3 {
t.Fatalf("expected 3 results, got %d", len(results))
}
// Verify sorted
for i := 1; i < len(results); i++ {
if results[i-1].Key > results[i].Key {
t.Fatalf("large elements not sorted at position %d", i)
}
}
}
// Test types for error scenarios
// errorVal is a type that fails during serialization
type errorVal struct {
shouldFail bool
}
func (e *errorVal) ToBytes() []byte {
if e.shouldFail {
panic("intentional serialization failure")
}
return []byte(`{"shouldFail": false}`)
}
// largeVal is a type with large data
type largeVal struct {
Key int
Data []byte
}
func (l *largeVal) ToBytes() []byte {
// Simple encoding: key as 4 bytes + data
result := make([]byte, 4+len(l.Data))
result[0] = byte(l.Key >> 24)
result[1] = byte(l.Key >> 16)
result[2] = byte(l.Key >> 8)
result[3] = byte(l.Key)
copy(result[4:], l.Data)
return result
}
func fromBytesForLargeVal(data []byte) extsort.SortType {
if len(data) < 4 {
panic("invalid large val data")
}
key := int(data[0])<<24 | int(data[1])<<16 | int(data[2])<<8 | int(data[3])
return &largeVal{
Key: key,
Data: data[4:],
}
}
func largeLessThan(a, b extsort.SortType) bool {
return a.(*largeVal).Key < b.(*largeVal).Key
}
// TestComparisonFunctionPanic tests handling of panics in comparison function
func TestComparisonFunctionPanic(t *testing.T) {
inputChan := make(chan extsort.SortType, 3)
inputChan <- val{Key: 1, Order: 1}
inputChan <- val{Key: 2, Order: 2}
inputChan <- val{Key: 3, Order: 3}
close(inputChan)
// Comparison function that panics
panicLessFunc := func(a, b extsort.SortType) bool {
panic("comparison function panic")
}
sort, outChan, errChan := extsort.New(inputChan, fromBytesForTest, panicLessFunc, nil)
// Should handle the panic gracefully
defer func() {
if r := recover(); r != nil {
t.Logf("Caught expected panic from comparison function: %v", r)
}
}()
sort.Sort(context.Background())
// Drain channels
for range outChan {
// Consume output
}
// Check for error
if err := <-errChan; err != nil {
t.Logf("Got expected error from panicking comparison: %v", err)
// Verify it's our specific error type
var compErr *extsort.ComparisonError
if !errors.As(err, &compErr) {
t.Errorf("Expected ComparisonError, got: %T", err)
}
}
}
// TestMixedTypeComparison tests comparison function with different types
func TestMixedTypeComparison(t *testing.T) {
inputChan := make(chan extsort.SortType, 4)
inputChan <- val{Key: 1, Order: 1}
inputChan <- &differentType{Value: 2}
inputChan <- val{Key: 3, Order: 3}
inputChan <- &differentType{Value: 0}
close(inputChan)
// Comparison function that handles mixed types
mixedLessFunc := func(a, b extsort.SortType) bool {
aVal := getComparableValue(a)
bVal := getComparableValue(b)
return aVal < bVal
}
// FromBytes that can handle both types
mixedFromBytes := func(data []byte) extsort.SortType {
// Check if it's a differentType by looking for "value" key
if strings.Contains(string(data), `"value"`) {
var d differentType
if err := json.Unmarshal(data, &d); err == nil {
return &d
}
}
// Otherwise try as val
var v val
if err := json.Unmarshal(data, &v); err == nil {
return v
}
panic("unknown type in deserialization")
}
sort, outChan, errChan := extsort.New(inputChan, mixedFromBytes, mixedLessFunc, nil)
sort.Sort(context.Background())
var results []extsort.SortType
for rec := range outChan {
results = append(results, rec)
}
if err := <-errChan; err != nil {
t.Fatalf("unexpected error with mixed types: %v", err)
}
if len(results) != 4 {
t.Fatalf("expected 4 results, got %d", len(results))
}
// Verify sorted by comparable value
for i := 1; i < len(results); i++ {
prev := getComparableValue(results[i-1])
curr := getComparableValue(results[i])
if prev > curr {
t.Fatalf("mixed types not sorted at position %d: %d > %d", i, prev, curr)
}
}
}
// Helper types and functions for mixed type test
type differentType struct {
Value int `json:"value"`
}
func (d *differentType) ToBytes() []byte {
bytes, err := json.Marshal(d)
if err != nil {
panic(err)
}
return bytes
}
func getComparableValue(item extsort.SortType) int {
switch v := item.(type) {
case val:
return v.Key
case *differentType:
return v.Value
default:
return 0
}
}