github.com/ecodeclub/eorm@v0.0.2-0.20231001112437-dae71da914d0/internal/test/types_test.go (about) 1 // Copyright 2021 ecodeclub 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package test 16 17 import ( 18 "testing" 19 20 "github.com/ecodeclub/ekit" 21 "github.com/stretchr/testify/assert" 22 ) 23 24 func TestJsonColumn_Scan(t *testing.T) { 25 type User struct { 26 Name string 27 } 28 testCases := []struct { 29 name string 30 input any 31 wantVal User 32 wantErr string 33 }{ 34 { 35 name: "empty string", 36 input: ``, 37 }, 38 { 39 name: "no fields", 40 input: `{}`, 41 wantVal: User{}, 42 }, 43 { 44 name: "string", 45 input: `{"name":"Tom"}`, 46 wantVal: User{Name: "Tom"}, 47 }, 48 { 49 name: "nil bytes", 50 input: []byte(nil), 51 }, 52 { 53 name: "empty bytes", 54 input: []byte(""), 55 }, 56 { 57 name: "bytes", 58 input: []byte(`{"name":"Tom"}`), 59 wantVal: User{Name: "Tom"}, 60 }, 61 { 62 name: "nil", 63 }, 64 { 65 name: "empty bytes ptr", 66 input: ekit.ToPtr[[]byte]([]byte("")), 67 }, 68 { 69 name: "bytes ptr", 70 input: ekit.ToPtr[[]byte]([]byte(`{"name":"Tom"}`)), 71 wantVal: User{Name: "Tom"}, 72 }, 73 } 74 75 for _, tc := range testCases { 76 t.Run(tc.name, func(t *testing.T) { 77 js := &JsonColumn{} 78 err := js.Scan(tc.input) 79 if tc.wantErr != "" { 80 assert.EqualError(t, err, tc.wantErr) 81 return 82 } else { 83 assert.Nil(t, err) 84 } 85 _, err = js.Value() 86 assert.Nil(t, err) 87 assert.EqualValues(t, tc.wantVal, js.Val) 88 }) 89 } 90 }