diff --git a/tests/easer_test.go b/tests/easer_test.go deleted file mode 100644 index 74b26af4..00000000 --- a/tests/easer_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package tests_test - -import ( - "gorm.io/gorm" - "gorm.io/gorm/utils/tests" - "sync" - "testing" - "time" -) - -func TestEaser(t *testing.T) { - t.Run("once", func(t *testing.T) { - db1, _ := gorm.Open(tests.DummyDialector{}, &gorm.Config{ - Ease: true, - }) - - wg := &sync.WaitGroup{} - wg.Add(2) - - incr := 0 - - testQuery := func(d *gorm.DB) { - time.Sleep(time.Second) - incr++ - } - - go func() { - db1.Ease(testQuery) - wg.Done() - }() - - go func() { - time.Sleep(500 * time.Millisecond) - db1.Ease(testQuery) - wg.Done() - }() - - wg.Wait() - - if incr != 1 { - t.Error("easer had to run the query only once") - } - }) - t.Run("twice", func(t *testing.T) { - db1, _ := gorm.Open(tests.DummyDialector{}, &gorm.Config{ - Ease: true, - }) - - wg := &sync.WaitGroup{} - wg.Add(2) - - incr := 0 - - testQuery := func(d *gorm.DB) { - time.Sleep(time.Second) - incr++ - } - - go func() { - db1.Statement.SQL.WriteString("q1") - db1.Ease(testQuery) - wg.Done() - }() - - go func() { - time.Sleep(500 * time.Millisecond) - db1.Statement.SQL.WriteString("q2") - db1.Ease(testQuery) - wg.Done() - }() - - wg.Wait() - - if incr != 2 { - t.Error("easer had to run two separate queries") - } - }) -} diff --git a/tests/gorm_test.go b/tests/gorm_test.go index 9827465c..6931f92c 100644 --- a/tests/gorm_test.go +++ b/tests/gorm_test.go @@ -1,9 +1,13 @@ package tests_test import ( + "sync" + "sync/atomic" "testing" + "time" "gorm.io/gorm" + "gorm.io/gorm/utils/tests" ) func TestReturningWithNullToZeroValues(t *testing.T) { @@ -91,3 +95,76 @@ func TestReturningWithNullToZeroValues(t *testing.T) { } } + +func TestEaserSameQueryTwice(t *testing.T) { + db, _ := gorm.Open(tests.DummyDialector{}, &gorm.Config{ + Ease: true, + }) + + wg := &sync.WaitGroup{} + wg.Add(2) + + var incr uint32 + + testQuery := func(d *gorm.DB) { + time.Sleep(time.Second) + atomic.AddUint32(&incr, 1) + } + + go func() { + db.Ease(testQuery) + wg.Done() + }() + + go func() { + time.Sleep(500 * time.Millisecond) + db.Ease(testQuery) + wg.Done() + }() + + wg.Wait() + + if incr != 1 { + t.Error("easer had to run the query only once") + } +} + +func TestEaserTwoDifferentQueries(t *testing.T) { + db, _ := gorm.Open(tests.DummyDialector{}, &gorm.Config{ + Ease: true, + }) + + wg := &sync.WaitGroup{} + mu := &sync.Mutex{} + wg.Add(2) + + var incr uint32 = 0 + + testQuery := func(d *gorm.DB) { + time.Sleep(time.Second) + atomic.AddUint32(&incr, 1) + } + + go func() { + mu.Lock() + db.Statement.SQL.WriteString("q1") + db.Ease(testQuery) + mu.Unlock() + wg.Done() + }() + + go func() { + time.Sleep(500 * time.Millisecond) + mu.Lock() + db.Statement.SQL.WriteString("q2") + db.Ease(testQuery) + mu.Unlock() + wg.Done() + }() + + wg.Wait() + + if incr != 2 { + t.Error("easer had to run two separate queries") + } +}