export_test.go (2816B)
1 package export 2 3 import ( 4 "math/big" 5 "testing" 6 "time" 7 8 "github.com/jackc/pgx/v5/pgtype" 9 ) 10 11 func TestFormatValue(t *testing.T) { 12 tests := []struct { 13 name string 14 v any 15 want string 16 }{ 17 {"nil", nil, ""}, 18 {"string", "hello", "hello"}, 19 {"bytes", []byte("data"), "data"}, 20 {"int", 42, "42"}, 21 {"float", 3.14, "3.14"}, 22 {"bool", true, "true"}, 23 {"date only", time.Date(2020, 1, 2, 0, 0, 0, 0, time.UTC), "2020-01-02"}, 24 {"datetime", time.Date(2020, 1, 2, 15, 4, 5, 0, time.UTC), "2020-01-02T15:04:05Z"}, 25 {"numeric valid", pgtype.Numeric{Int: big.NewInt(12345), Exp: -2, Valid: true}, "123.45"}, 26 {"numeric invalid", pgtype.Numeric{Valid: false}, ""}, 27 {"numeric NaN", pgtype.Numeric{Valid: true, NaN: true}, "NaN"}, 28 {"numeric Infinity", pgtype.Numeric{Valid: true, InfinityModifier: pgtype.Infinity}, "Infinity"}, 29 {"numeric -Infinity", pgtype.Numeric{Valid: true, InfinityModifier: pgtype.NegativeInfinity}, "-Infinity"}, 30 {"numeric zero exp", pgtype.Numeric{Int: big.NewInt(42), Exp: 0, Valid: true}, "42"}, 31 {"numeric positive exp", pgtype.Numeric{Int: big.NewInt(5), Exp: 3, Valid: true}, "5000"}, 32 } 33 34 for _, tt := range tests { 35 t.Run(tt.name, func(t *testing.T) { 36 got := formatValue(tt.v) 37 if got != tt.want { 38 t.Errorf("formatValue(%v) = %q, want %q", tt.v, got, tt.want) 39 } 40 }) 41 } 42 } 43 44 func TestConvertValue(t *testing.T) { 45 epoch := time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC) 46 47 tests := []struct { 48 name string 49 v any 50 ct colType 51 want any 52 }{ 53 {"nil", nil, colString, nil}, 54 {"bool true", true, colBool, true}, 55 {"bool false", false, colBool, false}, 56 {"int16 to int32", int16(42), colInt32, int32(42)}, 57 {"int32 passthrough", int32(100), colInt32, int32(100)}, 58 {"int64 to int32", int64(200), colInt32, int32(200)}, 59 {"int64 passthrough", int64(999), colInt64, int64(999)}, 60 {"int32 to int64", int32(50), colInt64, int64(50)}, 61 {"int16 to int64", int16(10), colInt64, int64(10)}, 62 {"float32 passthrough", float32(1.5), colFloat32, float32(1.5)}, 63 {"float64 to float32", float64(2.5), colFloat32, float32(2.5)}, 64 {"float64 passthrough", float64(3.14), colFloat64, float64(3.14)}, 65 {"float32 to float64", float32(1.5), colFloat64, float64(1.5)}, 66 {"date", time.Date(2020, 1, 2, 0, 0, 0, 0, time.UTC), colDate, 67 int32(time.Date(2020, 1, 2, 0, 0, 0, 0, time.UTC).Sub(epoch).Hours() / 24)}, 68 {"timestamp", time.Date(2020, 6, 15, 12, 30, 0, 0, time.UTC), colTimestamp, 69 time.Date(2020, 6, 15, 12, 30, 0, 0, time.UTC).Sub(epoch).Microseconds()}, 70 {"string passthrough", "hello", colString, "hello"}, 71 } 72 73 for _, tt := range tests { 74 t.Run(tt.name, func(t *testing.T) { 75 got := convertValue(tt.v, tt.ct) 76 if got != tt.want { 77 t.Errorf("convertValue(%v, %v) = %v (%T), want %v (%T)", tt.v, tt.ct, got, got, tt.want, tt.want) 78 } 79 }) 80 } 81 }