1 package colorful
2
3 import (
4 "encoding/json"
5 "reflect"
6 "testing"
7 )
8
9 func TestHexColor(t *testing.T) {
10 for _, tc := range []struct {
11 hc HexColor
12 s string
13 }{
14 {HexColor{R: 0, G: 0, B: 0}, "#000000"},
15 {HexColor{R: 1, G: 0, B: 0}, "#ff0000"},
16 {HexColor{R: 0, G: 1, B: 0}, "#00ff00"},
17 {HexColor{R: 0, G: 0, B: 1}, "#0000ff"},
18 {HexColor{R: 1, G: 1, B: 1}, "#ffffff"},
19 } {
20 var gotHC HexColor
21 if err := gotHC.Scan(tc.s); err != nil {
22 t.Errorf("_.Scan(%q) == %v, want <nil>", tc.s, err)
23 }
24 if !reflect.DeepEqual(gotHC, tc.hc) {
25 t.Errorf("_.Scan(%q) wrote %v, want %v", tc.s, gotHC, tc.hc)
26 }
27 if gotValue, err := tc.hc.Value(); err != nil || !reflect.DeepEqual(gotValue, tc.s) {
28 t.Errorf("%v.Value() == %v, %v, want %v, <nil>", tc.hc, gotValue, err, tc.s)
29 }
30 }
31 }
32
33 type CompositeType struct {
34 Name string `json:"name,omitempty"`
35 Color HexColor `json:"color,omitempty"`
36 }
37
38 func TestHexColorCompositeJson(t *testing.T) {
39 var obj = CompositeType{Name: "John", Color: HexColor{R: 1, G: 0, B: 1}}
40 var jsonData, err = json.Marshal(obj)
41 if err != nil {
42 t.Errorf("json.Marshall(obj) wrote %v", err)
43 }
44 var obj2 CompositeType
45 err = json.Unmarshal(jsonData, &obj2)
46
47 if err != nil {
48 t.Errorf("json.Unmarshall(%s) wrote %v", jsonData, err)
49 }
50
51 if !reflect.DeepEqual(obj2, obj) {
52 t.Errorf("json.Unmarshal(json.Marsrhall(obj)) != obj")
53 }
54
55 }
56
View as plain text