github.com/ecodeclub/eorm@v0.0.2-0.20231001112437-dae71da914d0/result_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 eorm 16 17 import ( 18 "errors" 19 "testing" 20 21 "github.com/DATA-DOG/go-sqlmock" 22 "github.com/stretchr/testify/assert" 23 ) 24 25 func TestResult_RowsAffected(t *testing.T) { 26 testCases := []struct { 27 name string 28 res Result 29 wantAffected int64 30 wantErr error 31 }{ 32 { 33 name: "err", 34 wantErr: errors.New("exec err"), 35 res: Result{err: errors.New("exec err")}, 36 }, 37 { 38 name: "unknown error", 39 wantErr: errors.New("unknown error"), 40 res: Result{res: sqlmock.NewErrorResult(errors.New("unknown error"))}, 41 }, 42 { 43 name: "no err", 44 wantAffected: int64(234), 45 res: Result{res: sqlmock.NewResult(123, 234)}, 46 }, 47 } 48 for _, tc := range testCases { 49 t.Run(tc.name, func(t *testing.T) { 50 affected, err := tc.res.RowsAffected() 51 assert.Equal(t, tc.wantErr, err) 52 if err != nil { 53 return 54 } 55 assert.Equal(t, tc.wantAffected, affected) 56 }) 57 } 58 } 59 60 func TestResult_LastInsertId(t *testing.T) { 61 testCases := []struct { 62 name string 63 res Result 64 wantLastId int64 65 wantErr error 66 }{ 67 { 68 name: "err", 69 wantErr: errors.New("exec err"), 70 res: Result{err: errors.New("exec err")}, 71 }, 72 { 73 name: "res err", 74 wantErr: errors.New("exec err"), 75 res: Result{res: sqlmock.NewErrorResult(errors.New("exec err"))}, 76 }, 77 { 78 name: "no err", 79 wantLastId: int64(123), 80 res: Result{res: sqlmock.NewResult(123, 234)}, 81 }, 82 } 83 for _, tc := range testCases { 84 t.Run(tc.name, func(t *testing.T) { 85 id, err := tc.res.LastInsertId() 86 assert.Equal(t, tc.wantErr, err) 87 if err != nil { 88 return 89 } 90 assert.Equal(t, tc.wantLastId, id) 91 }) 92 } 93 }