-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathgonull_test.go
616 lines (548 loc) · 14.8 KB
/
gonull_test.go
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
package gonull
import (
"database/sql/driver"
"encoding/json"
"errors"
"fmt"
"reflect"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestNewNullable(t *testing.T) {
value := "test"
n := NewNullable(value)
assert.True(t, n.Valid)
assert.Equal(t, value, n.Val)
}
type NullableInt struct {
Int int
Null bool
}
func TestNullableScan(t *testing.T) {
tests := []struct {
name string
value any
Valid bool
Present bool
wantErr bool
}{
{
name: "nil value",
value: nil,
Valid: false,
Present: true,
},
{
name: "string value",
value: "test",
Valid: true,
Present: true,
},
{
name: "unsupported type",
value: []byte{1, 2, 3},
wantErr: true,
Present: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var n Nullable[string]
err := n.Scan(tt.value)
if tt.wantErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
assert.Equal(t, tt.Valid, n.Valid)
assert.Equal(t, tt.Present, n.Present)
if tt.Valid {
assert.Equal(t, tt.value, n.Val)
}
}
})
}
}
func TestNullableValue(t *testing.T) {
tests := []struct {
name string
nullable Nullable[string]
wantValue driver.Value
wantErr error
}{
{
name: "valid value",
nullable: NewNullable("test"),
wantValue: "test",
wantErr: nil,
},
{
name: "unset value",
nullable: Nullable[string]{Valid: false},
wantValue: nil,
wantErr: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
value, err := tt.nullable.Value()
assert.Equal(t, tt.wantErr, err)
assert.Equal(t, tt.wantValue, value)
})
}
}
func TestNullableUnmarshalJSON(t *testing.T) {
type testCase struct {
name string
jsonData []byte
expectedVal any
expectedValid bool
expectedPresent bool
}
testCases := []testCase{
{
name: "ValuePresent",
jsonData: []byte(`123`),
expectedVal: 123,
expectedValid: true,
expectedPresent: true,
},
{
name: "ValueNull",
jsonData: []byte(`null`),
expectedVal: 0,
expectedValid: false,
expectedPresent: true,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
var nullable Nullable[int]
err := nullable.UnmarshalJSON(tc.jsonData)
assert.NoError(t, err)
assert.Equal(t, tc.expectedVal, nullable.Val)
assert.Equal(t, tc.expectedValid, nullable.Valid)
assert.Equal(t, tc.expectedPresent, nullable.Present)
})
}
}
func TestNullableUnmarshalJSON_Error(t *testing.T) {
jsonData := []byte(`"invalid_number"`)
var nullable Nullable[int]
err := nullable.UnmarshalJSON(jsonData)
assert.Error(t, err)
assert.False(t, nullable.Valid)
}
func TestNullableMarshalJSON(t *testing.T) {
type testCase struct {
name string
nullable Nullable[int]
expectedJSON []byte
}
testCases := []testCase{
{
name: "ValuePresent",
nullable: NewNullable[int](123),
expectedJSON: []byte(`123`),
},
{
name: "ValueNull",
nullable: Nullable[int]{Val: 0, Valid: false},
expectedJSON: []byte(`null`),
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
jsonData, err := tc.nullable.MarshalJSON()
assert.NoError(t, err)
assert.Equal(t, tc.expectedJSON, jsonData)
})
}
}
func TestNullableScan_UnconvertibleFromInt64(t *testing.T) {
value := int64(123456789012345)
var n Nullable[string]
err := n.Scan(value)
assert.Error(t, err)
assert.False(t, n.Valid)
}
func TestConvertToTypeFromInt64(t *testing.T) {
tests := []struct {
name string
targetType string
value int64
expectedError error
}{
{name: "Convert int64 to int", targetType: "int", value: int64(1), expectedError: nil},
{name: "Convert int64 to int8", targetType: "int8", value: int64(2), expectedError: nil},
{name: "Convert int64 to int16", targetType: "int16", value: int64(3), expectedError: nil},
{name: "Convert int64 to int32", targetType: "int32", value: int64(4), expectedError: nil},
{name: "Convert int64 to uint", targetType: "uint", value: int64(5), expectedError: nil},
{name: "Convert int64 to uint8", targetType: "uint8", value: int64(6), expectedError: nil},
{name: "Convert int64 to uint16", targetType: "uint16", value: int64(7), expectedError: nil},
{name: "Convert int64 to uint32", targetType: "uint32", value: int64(8), expectedError: nil},
// Add more tests as necessary
{name: "Convert int64 to string (expected to fail)", targetType: "string", value: int64(9), expectedError: ErrUnsupportedConversion},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var err error
switch tt.targetType {
case "int":
n := Nullable[int]{}
err = n.Scan(tt.value)
case "int8":
n := Nullable[int8]{}
err = n.Scan(tt.value)
case "int16":
n := Nullable[int16]{}
err = n.Scan(tt.value)
case "int32":
n := Nullable[int32]{}
err = n.Scan(tt.value)
case "uint":
n := Nullable[uint]{}
err = n.Scan(tt.value)
case "uint8":
n := Nullable[uint8]{}
err = n.Scan(tt.value)
case "uint16":
n := Nullable[uint16]{}
err = n.Scan(tt.value)
case "uint32":
n := Nullable[uint32]{}
err = n.Scan(tt.value)
case "string":
n := Nullable[string]{}
err = n.Scan(tt.value)
default:
t.Fatalf("Unsupported type: %s", tt.targetType)
return
}
if tt.expectedError == nil {
assert.NoError(t, err)
} else {
assert.Equal(t, tt.expectedError, err)
}
})
}
}
func TestNullableScanWithCustomEnum(t *testing.T) {
type TestEnum float32
const (
TestEnumA TestEnum = iota
TestEnumB
)
type TestModel struct {
ID int
Field Nullable[TestEnum]
}
// Simulate the scenario where the SQL driver returns an int64
// This is common as database integer types are usually scanned as int64 in Go
//
// sqlReturnedValue (int64(0)) is convertible to float32.
// The converted value 0 (as float32) matches TestEnumA, which is also 0 when converted to float32.
sqlReturnedValue := int64(0)
model := TestModel{ID: 1, Field: NewNullable(TestEnumA)}
err := model.Field.Scan(sqlReturnedValue)
assert.NoError(t, err, "Scan failed with unsupported type conversion")
assert.Equal(t, TestEnumA, model.Field.Val, "Scanned value does not match expected enum value")
}
func TestConvertToTypeWithNilValue(t *testing.T) {
tests := []struct {
name string
expected any
}{
{
name: "Nil to int",
expected: int(0),
},
{
name: "Nil to int8",
expected: int8(0),
},
{
name: "Nil to int16",
expected: int16(0),
},
{
name: "Nil to int32",
expected: int32(0),
},
{
name: "Nil to int64",
expected: int64(0),
},
{
name: "Nil to uint",
expected: uint(0),
},
{
name: "Nil to uint8 (byte)",
expected: uint8(0),
},
{
name: "Nil to uint16",
expected: uint16(0),
},
{
name: "Nil to uint32",
expected: uint32(0),
},
{
name: "Nil to uint64",
expected: uint64(0),
},
{
name: "Nil to float32",
expected: float32(0),
},
{
name: "Nil to float64",
expected: float64(0),
},
{
name: "Nil to bool",
expected: bool(false),
},
{
name: "Nil to string",
expected: "",
},
{
name: "Nil to time.Time",
expected: time.Time{},
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
var result any
var err error
switch tc.expected.(type) {
case int:
result, err = convertToType[int](nil)
case int8:
result, err = convertToType[int8](nil)
case int16:
result, err = convertToType[int16](nil)
case int32:
result, err = convertToType[int32](nil)
case int64:
result, err = convertToType[int64](nil)
case uint:
result, err = convertToType[uint](nil)
case uint8:
result, err = convertToType[uint8](nil)
case uint16:
result, err = convertToType[uint16](nil)
case uint32:
result, err = convertToType[uint32](nil)
case uint64:
result, err = convertToType[uint64](nil)
case float32:
result, err = convertToType[float32](nil)
case float64:
result, err = convertToType[float64](nil)
case bool:
result, err = convertToType[bool](nil)
case string:
result, err = convertToType[string](nil)
case time.Time:
result, err = convertToType[time.Time](nil)
}
assert.NoError(t, err)
assert.Equal(t, tc.expected, result)
})
}
}
type testStruct struct {
Foo Nullable[*string] `json:"foo"`
}
func TestPresent(t *testing.T) {
var nullable1 testStruct
var nullable2 testStruct
var nullable3 testStruct
err := json.Unmarshal([]byte(`{"foo":"f"}`), &nullable1)
assert.NoError(t, err)
assert.Equal(t, true, nullable1.Foo.Valid)
assert.Equal(t, true, nullable1.Foo.Present)
err = json.Unmarshal([]byte(`{}`), &nullable2)
assert.NoError(t, err)
assert.Equal(t, false, nullable2.Foo.Valid)
assert.Equal(t, false, nullable3.Foo.Present)
assert.Nil(t, nullable2.Foo.Val)
err = json.Unmarshal([]byte(`{"foo": null}`), &nullable3)
assert.NoError(t, err)
assert.Equal(t, false, nullable3.Foo.Valid)
assert.Equal(t, true, nullable3.Foo.Present)
assert.Nil(t, nullable3.Foo.Val)
}
type testValuerScannerStruct struct {
b []byte
}
func (t testValuerScannerStruct) Value() (driver.Value, error) {
return t.b, nil
}
func (t *testValuerScannerStruct) Scan(src any) error {
if src == nil {
return nil
}
if str, ok := src.(string); ok && str == "error" {
return errors.New("intentional error")
}
switch v := src.(type) {
case string:
t.b = []byte(v)
return nil
case []byte:
t.b = v
return nil
default:
return fmt.Errorf("unsupported type: %T", v)
}
}
func TestValuerAndScanner(t *testing.T) {
valueNullable1 := Nullable[testValuerScannerStruct]{
Val: testValuerScannerStruct{b: []byte("test output string")},
Valid: true,
Present: true,
}
valueNullable2 := Nullable[testValuerScannerStruct]{
Valid: false,
Present: true,
}
valueResult1, valueErr1 := valueNullable1.Value()
assert.NoError(t, valueErr1)
assert.Equal(t, []byte("test output string"), valueResult1)
valueResult2, valueErr2 := valueNullable2.Value()
assert.NoError(t, valueErr2)
assert.Equal(t, nil, valueResult2)
scannerData1 := []byte("test input string")
var scannerNullable1 Nullable[testValuerScannerStruct]
var scannerNullable2 Nullable[testValuerScannerStruct]
scannerErr1 := scannerNullable1.Scan(scannerData1)
assert.NoError(t, scannerErr1)
assert.Equal(t, Nullable[testValuerScannerStruct]{
Present: true,
Valid: true,
Val: testValuerScannerStruct{
b: []byte("test input string"),
},
}, scannerNullable1)
scannerErr2 := scannerNullable2.Scan(nil)
assert.NoError(t, scannerErr2)
assert.Equal(t, Nullable[testValuerScannerStruct]{
Present: true,
Valid: false,
Val: testValuerScannerStruct{
b: []byte(nil),
},
}, scannerNullable2)
var scannerNullableUnsupported Nullable[testValuerScannerStruct]
scannerErrUnsupported := scannerNullableUnsupported.Scan(123)
assert.Error(t, scannerErrUnsupported)
assert.Contains(t, scannerErrUnsupported.Error(), "unsupported type")
assert.Equal(t, Nullable[testValuerScannerStruct]{
Present: true,
Valid: false,
Val: testValuerScannerStruct{},
}, scannerNullableUnsupported)
}
func TestNullableOrElse(t *testing.T) {
value := "hello"
nonEmpty := NewNullable(value)
assert.Equal(t, value, nonEmpty.OrElse("world"))
var empty Nullable[string]
assert.Equal(t, "world", empty.OrElse("world"))
}
type customValuer struct {
value any
err error
}
type unknowType interface{}
func (cv customValuer) Value() (driver.Value, error) {
return cv.value, cv.err
}
func TestConvertToDriverValue(t *testing.T) {
var (
intVal int = 123
int8Val int8 = 12
int16Val int16 = 1234
int32Val int32 = 12345
int64Val int64 = 123456
uintVal uint = 123
uint8Val uint8 = 12
uint16Val uint16 = 1234
uint32Val uint32 = 12345
uint64Val uint64 = 1 << 62
float32Val float32 = 12.34
float64Val float64 = 123.456
boolVal bool = true
stringVal string = "test"
timeVal time.Time = time.Date(2006, 1, 2, 15, 4, 5, 0, time.UTC)
byteSlice []byte = []byte("byte slice")
ptrToInt *int = &intVal
nilPtr *int = nil
valuerSuccess customValuer = customValuer{value: "valuer value", err: nil}
valuerError customValuer = customValuer{err: errors.New("valuer error")}
unknowTypeError unknowType = map[bool]bool{}
unsupportedSlice = []int{1, 2, 3}
)
tests := []struct {
name string
value any
want driver.Value
wantErr bool
}{
{"Int", intVal, int64(intVal), false},
{"Int8", int8Val, int64(int8Val), false},
{"Int16", int16Val, int64(int16Val), false},
{"Int32", int32Val, int64(int32Val), false},
{"Int64", int64Val, int64(int64Val), false},
{"Uint", uintVal, int64(uintVal), false},
{"Uint8", uint8Val, int64(uint8Val), false},
{"Uint16", uint16Val, int64(uint16Val), false},
{"Uint32", uint32Val, int64(uint32Val), false},
{"Uint64", uint64Val, int64(uint64Val), false},
{"Float32", float32Val, float64(float32Val), false},
{"Float64", float64Val, float64(float64Val), false},
{"Bool", boolVal, boolVal, false},
{"String", stringVal, stringVal, false},
{"ByteSlice", byteSlice, byteSlice, false},
{"Time", timeVal, timeVal, false},
{"PointerToInt", ptrToInt, int64(*ptrToInt), false},
{"NilPointer", nilPtr, nil, false},
{"UnsupportedType", struct{}{}, nil, true},
{"Uint64HighBitSet", uint64(1 << 63), nil, true}, // Uint64 with high bit set
{"ValuerInterfaceSuccess", valuerSuccess, "valuer value", false},
{"ValuerInterfaceError", valuerError, nil, true},
{"UnknowTypeError", unknowTypeError, nil, true},
{"UnsupportedSliceType", unsupportedSlice, nil, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := convertToDriverValue(tt.value)
if (err != nil) != tt.wantErr {
t.Errorf("convertToDriverValue() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("convertToDriverValue() = %v, want %v", got, tt.want)
}
})
}
}
func TestNullableValue_Uint32(t *testing.T) {
uint32Val := uint32(12345)
nullableUint32 := NewNullable(uint32Val)
convertedValue, err := nullableUint32.Value()
if err != nil {
t.Fatalf("Nullable[uint32].Value() returned an error: %v", err)
}
if _, ok := convertedValue.(int64); !ok {
t.Fatalf("Nullable[uint32].Value() returned a non-int64 type: %T", convertedValue)
}
if int64(uint32Val) != convertedValue.(int64) {
t.Errorf("Nullable[uint32].Value() returned %v, want %v", convertedValue, uint32Val)
}
}