github.com/spi-ca/misc@v1.0.1/types/json_test.go (about) 1 package types 2 3 import ( 4 "bytes" 5 "testing" 6 ) 7 8 func TestJSONString(t *testing.T) { 9 t.Parallel() 10 11 j := JSON("hello") 12 if j.String() != "hello" { 13 t.Errorf("Expected %q, got %s", "hello", j.String()) 14 } 15 } 16 17 func TestJSONUnmarshal(t *testing.T) { 18 t.Parallel() 19 20 type JSONTest struct { 21 Name string `json:"name"` 22 Age int `json:"age"` 23 } 24 var jt JSONTest 25 26 j := JSON(`{"name":"hi","age":15}`) 27 err := j.Unmarshal(&jt) 28 if err != nil { 29 t.Error(err) 30 } 31 32 if jt.Name != "hi" { 33 t.Errorf("Expected %q, got %s", "hi", jt.Name) 34 } 35 if jt.Age != 15 { 36 t.Errorf("Expected %v, got %v", 15, jt.Age) 37 } 38 } 39 40 func TestJSONMarshal(t *testing.T) { 41 t.Parallel() 42 43 type JSONTest struct { 44 Name string `json:"name"` 45 Age int `json:"age"` 46 } 47 jt := JSONTest{ 48 Name: "hi", 49 Age: 15, 50 } 51 52 var j JSON 53 err := j.Marshal(jt) 54 if err != nil { 55 t.Error(err) 56 } 57 58 if j.String() != `{"name":"hi","age":15}` { 59 t.Errorf("expected %s, got %s", `{"name":"hi","age":15}`, j.String()) 60 } 61 } 62 63 func TestJSONUnmarshalJSON(t *testing.T) { 64 t.Parallel() 65 66 j := JSON(nil) 67 68 err := j.UnmarshalJSON(JSON(`"hi"`)) 69 if err != nil { 70 t.Error(err) 71 } 72 73 if j.String() != `"hi"` { 74 t.Errorf("Expected %q, got %s", "hi", j.String()) 75 } 76 } 77 78 func TestJSONMarshalJSON(t *testing.T) { 79 t.Parallel() 80 81 j := JSON(`"hi"`) 82 res, err := j.MarshalJSON() 83 if err != nil { 84 t.Error(err) 85 } 86 87 if !bytes.Equal(res, []byte(`"hi"`)) { 88 t.Errorf("Expected %q, got %v", `"hi"`, res) 89 } 90 } 91 92 func TestJSONValue(t *testing.T) { 93 t.Parallel() 94 95 j := JSON(`{"name":"hi","age":15}`) 96 v, err := j.Value() 97 if err != nil { 98 t.Error(err) 99 } 100 101 if !bytes.Equal(j, v.([]byte)) { 102 t.Errorf("byte mismatch, %v %v", j, v) 103 } 104 } 105 106 func TestJSONScan(t *testing.T) { 107 t.Parallel() 108 109 j := JSON{} 110 111 err := j.Scan(`"hello"`) 112 if err != nil { 113 t.Error(err) 114 } 115 116 if !bytes.Equal(j, []byte(`"hello"`)) { 117 t.Errorf("bad []byte: %#v ≠ %#v\n", j, string([]byte(`"hello"`))) 118 } 119 }