diff --git a/tests/go.mod b/tests/go.mod index 55495de3..fa293987 100644 --- a/tests/go.mod +++ b/tests/go.mod @@ -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 diff --git a/tests/preload_test.go b/tests/preload_test.go index d9035661..dbac037a 100644 --- a/tests/preload_test.go +++ b/tests/preload_test.go @@ -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) +}