1
2
3
4
5 package driver
6
7 import (
8 "reflect"
9 "testing"
10 "time"
11 )
12
13 type valueConverterTest struct {
14 c ValueConverter
15 in any
16 out any
17 err string
18 }
19
20 var now = time.Now()
21 var answer int64 = 42
22
23 type (
24 i int64
25 f float64
26 b bool
27 bs []byte
28 s string
29 t time.Time
30 is []int
31 )
32
33 var valueConverterTests = []valueConverterTest{
34 {Bool, "true", true, ""},
35 {Bool, "True", true, ""},
36 {Bool, []byte("t"), true, ""},
37 {Bool, true, true, ""},
38 {Bool, "1", true, ""},
39 {Bool, 1, true, ""},
40 {Bool, int64(1), true, ""},
41 {Bool, uint16(1), true, ""},
42 {Bool, "false", false, ""},
43 {Bool, false, false, ""},
44 {Bool, "0", false, ""},
45 {Bool, 0, false, ""},
46 {Bool, int64(0), false, ""},
47 {Bool, uint16(0), false, ""},
48 {c: Bool, in: "foo", err: "sql/driver: couldn't convert \"foo\" into type bool"},
49 {c: Bool, in: 2, err: "sql/driver: couldn't convert 2 into type bool"},
50 {DefaultParameterConverter, now, now, ""},
51 {DefaultParameterConverter, (*int64)(nil), nil, ""},
52 {DefaultParameterConverter, &answer, answer, ""},
53 {DefaultParameterConverter, &now, now, ""},
54 {DefaultParameterConverter, i(9), int64(9), ""},
55 {DefaultParameterConverter, f(0.1), float64(0.1), ""},
56 {DefaultParameterConverter, b(true), true, ""},
57 {DefaultParameterConverter, bs{1}, []byte{1}, ""},
58 {DefaultParameterConverter, s("a"), "a", ""},
59 {DefaultParameterConverter, is{1}, nil, "unsupported type driver.is, a slice of int"},
60 {DefaultParameterConverter, dec{exponent: -6}, dec{exponent: -6}, ""},
61 }
62
63 func TestValueConverters(t *testing.T) {
64 for i, tt := range valueConverterTests {
65 out, err := tt.c.ConvertValue(tt.in)
66 goterr := ""
67 if err != nil {
68 goterr = err.Error()
69 }
70 if goterr != tt.err {
71 t.Errorf("test %d: %T(%T(%v)) error = %q; want error = %q",
72 i, tt.c, tt.in, tt.in, goterr, tt.err)
73 }
74 if tt.err != "" {
75 continue
76 }
77 if !reflect.DeepEqual(out, tt.out) {
78 t.Errorf("test %d: %T(%T(%v)) = %v (%T); want %v (%T)",
79 i, tt.c, tt.in, tt.in, out, out, tt.out, tt.out)
80 }
81 }
82 }
83
84 type dec struct {
85 form byte
86 neg bool
87 coefficient [16]byte
88 exponent int32
89 }
90
91 func (d dec) Decompose(buf []byte) (form byte, negative bool, coefficient []byte, exponent int32) {
92 coef := make([]byte, 16)
93 copy(coef, d.coefficient[:])
94 return d.form, d.neg, coef, d.exponent
95 }
96
View as plain text