test: no cache preload in goroutine

This commit is contained in:
rokeyzhao 2020-11-26 20:27:55 +08:00
parent 557b874ee3
commit 590e73ff95
2 changed files with 47 additions and 0 deletions

View File

@ -6,6 +6,7 @@ require (
github.com/google/uuid v1.1.1
github.com/jinzhu/now v1.1.1
github.com/lib/pq v1.6.0
github.com/stretchr/testify v1.5.1
gorm.io/driver/mysql v1.0.3
gorm.io/driver/postgres v1.0.5
gorm.io/driver/sqlite v1.1.3

View File

@ -5,8 +5,11 @@ import (
"regexp"
"sort"
"strconv"
"sync"
"testing"
"github.com/stretchr/testify/assert"
"gorm.io/gorm"
"gorm.io/gorm/clause"
. "gorm.io/gorm/utils/tests"
@ -212,3 +215,46 @@ func TestPreloadEmptyData(t *testing.T) {
t.Errorf("json marshal is not empty slice, got %v", string(r))
}
}
// TestPreloadGoroutine goroutine中在没有缓存的情况下使用Preload
func TestPreloadGoroutine(t *testing.T) {
// 这里不要用Create因为会缓存relations
// 把tests_test.go中init()函数中的RunMigrations()注释掉数据库中保留一些数据来触发Preload
var wg sync.WaitGroup
DB = DB.Where("id = ?", 1)
tx := DB.Session(&gorm.Session{})
wg.Add(2)
for i := 0; i < 2; i++ {
go func() {
defer wg.Done()
var user2 []User
tx = tx.Preload("Team")
err := tx.Find(&user2).Error
ast := assert.New(t)
// 这里会报错,Team: unsupported relations
// relations是空的
ast.Equal(err, nil)
}()
}
wg.Wait()
}
// TestPreloadNotGoroutine 正常情况在没有缓存的时候下使用Preload
func TestPreloadNotGoroutine(t *testing.T) {
// 这里不要用Create因为会缓存relations
// 把tests_test.go中init()函数中的RunMigrations()注释掉数据库中保留一些数据来触发Preload
DB = DB.Where("id = ?", 1)
tx := DB.Session(&gorm.Session{})
var user2 []User
tx = tx.Preload("Team")
err := tx.Find(&user2).Error
ast := assert.New(t)
// 这里不会报错
// relations不是空的
ast.Equal(err, nil)
}