github.com/kaleido-io/firefly@v0.0.0-20210622132723-8b4b6aacb971/pkg/fftypes/byteable_test.go (about) 1 // Copyright © 2021 Kaleido, Inc. 2 // 3 // SPDX-License-Identifier: Apache-2.0 4 // 5 // Licensed under the Apache License, Version 2.0 (the "License"); 6 // you may not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, software 12 // distributed under the License is distributed on an "AS IS" BASIS, 13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 // See the License for the specific language governing permissions and 15 // limitations under the License. 16 17 package fftypes 18 19 import ( 20 "encoding/json" 21 "testing" 22 23 "github.com/stretchr/testify/assert" 24 ) 25 26 func TestByteableSerializeNull(t *testing.T) { 27 28 type testStruct struct { 29 Prop1 *Byteable `json:"prop1"` 30 Prop2 *Byteable `json:"prop2,omitempty"` 31 } 32 33 ts := &testStruct{} 34 35 err := json.Unmarshal([]byte(`{}`), &ts) 36 assert.NoError(t, err) 37 assert.Nil(t, ts.Prop1) 38 assert.Nil(t, ts.Prop2) 39 b, err := json.Marshal(&ts) 40 assert.Equal(t, `{"prop1":null}`, string(b)) 41 42 } 43 44 func TestByteableSerializeObjects(t *testing.T) { 45 46 type testStruct struct { 47 Prop *Byteable `json:"prop,omitempty"` 48 } 49 50 ts := &testStruct{} 51 52 err := json.Unmarshal([]byte(`{"prop":{"b":"test","b":"duplicate","a":12345,"c":{"e":1.00000000001,"d":false}}}`), &ts) 53 assert.NoError(t, err) 54 b, err := json.Marshal(&ts) 55 assert.NoError(t, err) 56 assert.Equal(t, `{"prop":{"b":"test","b":"duplicate","a":12345,"c":{"e":1.00000000001,"d":false}}}`, string(b)) 57 err = json.Unmarshal([]byte(`{"prop" 58 :{"b":"test", "b":"duplicate","a" :12345,"c":{ 59 "e":1.00000000001, 60 "d":false} 61 }}`), &ts) 62 b, err = json.Marshal(&ts) 63 assert.NoError(t, err) 64 assert.Equal(t, `{"prop":{"b":"test","b":"duplicate","a":12345,"c":{"e":1.00000000001,"d":false}}}`, string(b)) 65 b, err = json.Marshal(&ts.Prop) 66 assert.Equal(t, `{"b":"test","b":"duplicate","a":12345,"c":{"e":1.00000000001,"d":false}}`, string(b)) 67 assert.Equal(t, "8eff3083f052a77bda0934236bf8e5eccbd186d5ae81ada7a5bbee516ecd5726", ts.Prop.Hash().String()) 68 69 jo, ok := ts.Prop.JSONObjectOk() 70 assert.True(t, ok) 71 assert.Equal(t, "duplicate", jo.GetString("b")) 72 73 } 74 75 func TestByteableMarshalNull(t *testing.T) { 76 77 var pb Byteable 78 b, err := pb.MarshalJSON() 79 assert.NoError(t, err) 80 assert.Equal(t, "null", string(b)) 81 } 82 83 func TestByteableUnmarshalFail(t *testing.T) { 84 85 var b Byteable 86 err := b.UnmarshalJSON([]byte(`!json`)) 87 assert.Error(t, err) 88 89 jo := b.JSONObject() 90 assert.Equal(t, JSONObject{}, *jo) 91 }