code.gitea.io/gitea@v1.21.7/models/db/context_committer_test.go (about) 1 // Copyright 2022 The Gitea Authors. All rights reserved. 2 // SPDX-License-Identifier: MIT 3 4 package db // it's not db_test, because this file is for testing the private type halfCommitter 5 6 import ( 7 "fmt" 8 "testing" 9 10 "github.com/stretchr/testify/assert" 11 ) 12 13 type MockCommitter struct { 14 wants []string 15 gots []string 16 } 17 18 func NewMockCommitter(wants ...string) *MockCommitter { 19 return &MockCommitter{ 20 wants: wants, 21 } 22 } 23 24 func (c *MockCommitter) Commit() error { 25 c.gots = append(c.gots, "commit") 26 return nil 27 } 28 29 func (c *MockCommitter) Close() error { 30 c.gots = append(c.gots, "close") 31 return nil 32 } 33 34 func (c *MockCommitter) Assert(t *testing.T) { 35 assert.Equal(t, c.wants, c.gots, "want operations %v, but got %v", c.wants, c.gots) 36 } 37 38 func Test_halfCommitter(t *testing.T) { 39 /* 40 Do something like: 41 42 ctx, committer, err := db.TxContext(db.DefaultContext) 43 if err != nil { 44 return nil 45 } 46 defer committer.Close() 47 48 // ... 49 50 if err != nil { 51 return nil 52 } 53 54 // ... 55 56 return committer.Commit() 57 */ 58 59 testWithCommitter := func(committer Committer, f func(committer Committer) error) { 60 if err := f(&halfCommitter{committer: committer}); err == nil { 61 committer.Commit() 62 } 63 committer.Close() 64 } 65 66 t.Run("commit and close", func(t *testing.T) { 67 mockCommitter := NewMockCommitter("commit", "close") 68 69 testWithCommitter(mockCommitter, func(committer Committer) error { 70 defer committer.Close() 71 return committer.Commit() 72 }) 73 74 mockCommitter.Assert(t) 75 }) 76 77 t.Run("rollback and close", func(t *testing.T) { 78 mockCommitter := NewMockCommitter("close", "close") 79 80 testWithCommitter(mockCommitter, func(committer Committer) error { 81 defer committer.Close() 82 if true { 83 return fmt.Errorf("error") 84 } 85 return committer.Commit() 86 }) 87 88 mockCommitter.Assert(t) 89 }) 90 91 t.Run("close and commit", func(t *testing.T) { 92 mockCommitter := NewMockCommitter("close", "close") 93 94 testWithCommitter(mockCommitter, func(committer Committer) error { 95 committer.Close() 96 committer.Commit() 97 return fmt.Errorf("error") 98 }) 99 100 mockCommitter.Assert(t) 101 }) 102 }