github.com/wfusion/gofusion@v1.1.14/test/db/cases/conn_test.go (about) 1 package cases 2 3 import ( 4 "context" 5 "math/rand" 6 "sync" 7 "testing" 8 "time" 9 10 "github.com/stretchr/testify/suite" 11 12 "github.com/wfusion/gofusion/db" 13 "github.com/wfusion/gofusion/log" 14 15 testDB "github.com/wfusion/gofusion/test/db" 16 ) 17 18 func TestConn(t *testing.T) { 19 testingSuite := &Conn{Test: new(testDB.Test)} 20 testingSuite.Init(testingSuite) 21 suite.Run(t, testingSuite) 22 } 23 24 type Conn struct { 25 *testDB.Test 26 } 27 28 func (t *Conn) BeforeTest(suiteName, testName string) { 29 t.Catch(func() { 30 log.Info(context.Background(), "right before %s %s", suiteName, testName) 31 }) 32 } 33 34 func (t *Conn) AfterTest(suiteName, testName string) { 35 t.Catch(func() { 36 log.Info(context.Background(), "right after %s %s", suiteName, testName) 37 }) 38 } 39 40 func (t *Conn) TestMysql() { 41 t.testDefault(nameMysqlRead, nameMysqlWrite) 42 } 43 44 func (t *Conn) TestPostgres() { 45 t.testDefault(namePostgres, namePostgres) 46 } 47 48 func (t *Conn) TestOpengauss() { 49 t.testDefault(nameOpenGauss, nameOpenGauss) 50 } 51 52 func (t *Conn) TestSqlserver() { 53 t.testDefault(nameSqlserver, nameSqlserver) 54 } 55 56 func (t *Conn) testDefault(read, write string) { 57 t.Catch(func() { 58 ctx, cancel := context.WithCancel(context.Background()) 59 defer cancel() 60 61 tx := db.Use(ctx, write, db.AppName(t.AppName())) 62 go func() { 63 ticker := time.NewTicker(time.Second) 64 defer ticker.Stop() 65 for range ticker.C { 66 connPool, err := tx.GetProxy().DB() 67 if err != nil { 68 log.Warn(ctx, "get conn pool failed: %s", err) 69 continue 70 } 71 s := connPool.Stats() 72 log.Info(ctx, "inuse(%v) idle(%v) open_conns(%v) pending(%v)", 73 s.InUse, s.Idle, s.OpenConnections, s.WaitCount) 74 } 75 }() 76 77 canExecChan := make(chan struct{}, 20) 78 go func() { 79 ticker := time.NewTicker(time.Millisecond) 80 defer ticker.Stop() 81 defer close(canExecChan) 82 for { 83 select { 84 case <-ctx.Done(): 85 case <-ticker.C: 86 canExecChan <- struct{}{} 87 } 88 } 89 }() 90 91 wg := new(sync.WaitGroup) 92 t.NoError(tx.Migrator().AutoMigrate(new(modelWithData))) 93 defer func() { 94 t.NoError(tx.Migrator().DropTable(new(modelWithData))) 95 }() 96 97 for i := 0; i < 100; i++ { 98 wg.Add(1) 99 go func() { 100 defer wg.Done() 101 // jitter within 500ms ~ 1500ms 102 time.Sleep(500*time.Millisecond + time.Duration(rand.Float64()*float64(time.Second))) 103 104 <-canExecChan 105 mwd1 := &modelWithData{Name: "az1"} 106 tx.Create(mwd1) 107 //tx.Create(mwd1) 108 109 // jitter within 500ms ~ 1500ms 110 <-canExecChan 111 time.Sleep(500*time.Millisecond + time.Duration(rand.Float64()*float64(time.Second))) 112 tx.Where("name = 'az1'").Delete(mwd1) 113 //tx.Where("name = 'az1'").Delete(mwd1) 114 }() 115 } 116 wg.Wait() 117 }) 118 }