mirror of
https://github.com/go-gitea/gitea
synced 2024-11-02 00:04:25 +00:00
34283a74e8
Fix #19513 This PR introduce a new db method `InTransaction(context.Context)`, and also builtin check on `db.TxContext` and `db.WithTx`. There is also a new method `db.AutoTx` has been introduced but could be used by other PRs. `WithTx` will always open a new transaction, if a transaction exist in context, return an error. `AutoTx` will try to open a new transaction if no transaction exist in context. That means it will always enter a transaction if there is no error. Co-authored-by: delvh <dev.lh@web.de> Co-authored-by: 6543 <6543@obermui.de>
34 lines
881 B
Go
34 lines
881 B
Go
// Copyright 2022 The Gitea Authors. All rights reserved.
|
|
// Use of this source code is governed by a MIT-style
|
|
// license that can be found in the LICENSE file.
|
|
|
|
package db_test
|
|
|
|
import (
|
|
"context"
|
|
"testing"
|
|
|
|
"code.gitea.io/gitea/models/db"
|
|
"code.gitea.io/gitea/models/unittest"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
)
|
|
|
|
func TestInTransaction(t *testing.T) {
|
|
assert.NoError(t, unittest.PrepareTestDatabase())
|
|
assert.False(t, db.InTransaction(db.DefaultContext))
|
|
assert.NoError(t, db.WithTx(db.DefaultContext, func(ctx context.Context) error {
|
|
assert.True(t, db.InTransaction(ctx))
|
|
return nil
|
|
}))
|
|
|
|
ctx, committer, err := db.TxContext(db.DefaultContext)
|
|
assert.NoError(t, err)
|
|
defer committer.Close()
|
|
assert.True(t, db.InTransaction(ctx))
|
|
assert.Error(t, db.WithTx(ctx, func(ctx context.Context) error {
|
|
assert.True(t, db.InTransaction(ctx))
|
|
return nil
|
|
}))
|
|
}
|