Fixed tests' race condition for Easer and moved them to where they belong

This commit is contained in:
ktsivkov 2023-03-20 17:42:17 +01:00
parent 76bc83ea2b
commit 16f1168cdd
2 changed files with 77 additions and 78 deletions

View File

@ -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")
}
})
}

View File

@ -1,9 +1,13 @@
package tests_test package tests_test
import ( import (
"sync"
"sync/atomic"
"testing" "testing"
"time"
"gorm.io/gorm" "gorm.io/gorm"
"gorm.io/gorm/utils/tests"
) )
func TestReturningWithNullToZeroValues(t *testing.T) { 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")
}
}