1 package pgtype_test
2
3 import (
4 "context"
5 "testing"
6
7 "github.com/jackc/pgx/v5/pgtype"
8 "github.com/jackc/pgx/v5/pgxtest"
9 )
10
11 func TestFloat4Codec(t *testing.T) {
12 pgxtest.RunValueRoundTripTests(context.Background(), t, defaultConnTestRunner, nil, "float4", []pgxtest.ValueRoundTripTest{
13 {pgtype.Float4{Float32: -1, Valid: true}, new(pgtype.Float4), isExpectedEq(pgtype.Float4{Float32: -1, Valid: true})},
14 {pgtype.Float4{Float32: 0, Valid: true}, new(pgtype.Float4), isExpectedEq(pgtype.Float4{Float32: 0, Valid: true})},
15 {pgtype.Float4{Float32: 1, Valid: true}, new(pgtype.Float4), isExpectedEq(pgtype.Float4{Float32: 1, Valid: true})},
16 {float32(0.00001), new(float32), isExpectedEq(float32(0.00001))},
17 {float32(9999.99), new(float32), isExpectedEq(float32(9999.99))},
18 {pgtype.Float4{}, new(pgtype.Float4), isExpectedEq(pgtype.Float4{})},
19 {int64(1), new(int64), isExpectedEq(int64(1))},
20 {"1.23", new(string), isExpectedEq("1.23")},
21 {nil, new(*float32), isExpectedEq((*float32)(nil))},
22 })
23 }
24
25 func TestFloat4MarshalJSON(t *testing.T) {
26 successfulTests := []struct {
27 source pgtype.Float4
28 result string
29 }{
30 {source: pgtype.Float4{Float32: 0}, result: "null"},
31 {source: pgtype.Float4{Float32: 1.23, Valid: true}, result: "1.23"},
32 }
33 for i, tt := range successfulTests {
34 r, err := tt.source.MarshalJSON()
35 if err != nil {
36 t.Errorf("%d: %v", i, err)
37 }
38
39 if string(r) != tt.result {
40 t.Errorf("%d: expected %v to convert to %v, but it was %v", i, tt.source, tt.result, string(r))
41 }
42 }
43 }
44
45 func TestFloat4UnmarshalJSON(t *testing.T) {
46 successfulTests := []struct {
47 source string
48 result pgtype.Float4
49 }{
50 {source: "null", result: pgtype.Float4{Float32: 0}},
51 {source: "1.23", result: pgtype.Float4{Float32: 1.23, Valid: true}},
52 }
53 for i, tt := range successfulTests {
54 var r pgtype.Float4
55 err := r.UnmarshalJSON([]byte(tt.source))
56 if err != nil {
57 t.Errorf("%d: %v", i, err)
58 }
59
60 if r != tt.result {
61 t.Errorf("%d: expected %v to convert to %v, but it was %v", i, tt.source, tt.result, r)
62 }
63 }
64 }
65
View as plain text