@@ -114,3 +114,60 @@ func TestInetAssignTo(t *testing.T) {
114114 }
115115 }
116116}
117+
118+ func TestInetMarshalJSON (t * testing.T ) {
119+ successfulTests := []struct {
120+ json string
121+ source pgtype.Inet
122+ }{
123+ {source : pgtype.Inet {IPNet : mustParseCIDR (t , "127.0.0.1/32" ), Status : pgtype .Present }, json : `"127.0.0.1/32"` },
124+ {source : pgtype.Inet {IPNet : mustParseCIDR (t , "2607:f8b0:4009:80b::200e/128" ), Status : pgtype .Present }, json : `"2607:f8b0:4009:80b::200e/128"` },
125+ {source : pgtype.Inet {Status : pgtype .Null }, json : `""` },
126+ {source : pgtype.Inet {}, json : `""` },
127+ }
128+
129+ for i , tt := range successfulTests {
130+ got , err := tt .source .MarshalJSON ()
131+ if err != nil {
132+ t .Errorf ("%d: %v" , i , err )
133+ }
134+ if ! reflect .DeepEqual (got , []byte (tt .json )) {
135+ t .Errorf ("%d: expected JSON `%s`, but it was %s" , i , tt .json , string (got ))
136+ }
137+ }
138+ }
139+
140+ func TestInetUnmarshalJSON (t * testing.T ) {
141+ successfulTests := []struct {
142+ json string
143+ expected pgtype.Inet
144+ }{
145+ {expected : pgtype.Inet {IPNet : mustParseCIDR (t , "127.0.0.1/32" ), Status : pgtype .Present }, json : `"127.0.0.1/32"` },
146+ {expected : pgtype.Inet {IPNet : mustParseCIDR (t , "127.0.0.1/32" ), Status : pgtype .Present }, json : `"127.0.0.1"` },
147+ {expected : pgtype.Inet {IPNet : mustParseCIDR (t , "2607:f8b0:4009:80b::200e/128" ), Status : pgtype .Present }, json : `"2607:f8b0:4009:80b::200e/128"` },
148+ {expected : pgtype.Inet {IPNet : mustParseCIDR (t , "2607:f8b0:4009:80b::200e/128" ), Status : pgtype .Present }, json : `"2607:f8b0:4009:80b::200e"` },
149+ {expected : pgtype.Inet {Status : pgtype .Null }, json : `""` }, // empty is OK, equivalent to our null struct
150+ }
151+ badJSON := []string {
152+ `"127.0.0.1/"` , // no network
153+ `"444.555.666.777/32"` , // bad addr
154+ `"nonsense"` , // bad everything
155+ }
156+
157+ for i , tt := range successfulTests {
158+ got := pgtype.Inet {}
159+ if err := got .UnmarshalJSON ([]byte (tt .json )); err != nil {
160+ t .Errorf ("%d: %v" , i , err )
161+ }
162+ if ! reflect .DeepEqual (got , tt .expected ) {
163+ t .Errorf ("%d: expected %v from JSON `%s`, but it was %v" , i , tt .expected , tt .json , got )
164+ }
165+ }
166+
167+ for i , example := range badJSON {
168+ got := pgtype.Inet {}
169+ if err := got .UnmarshalJSON ([]byte (example )); err == nil {
170+ t .Errorf ("%d: Expected error for %s, but got none" , i , example )
171+ }
172+ }
173+ }
0 commit comments