github.com/rudderlabs/rudder-go-kit@v0.30.0/sqlutil/monitor_test.go (about) 1 package sqlutil_test 2 3 import ( 4 "context" 5 "testing" 6 "time" 7 8 "github.com/ory/dockertest/v3" 9 "github.com/stretchr/testify/require" 10 11 "github.com/rudderlabs/rudder-go-kit/config" 12 "github.com/rudderlabs/rudder-go-kit/sqlutil" 13 "github.com/rudderlabs/rudder-go-kit/stats" 14 "github.com/rudderlabs/rudder-go-kit/stats/memstats" 15 "github.com/rudderlabs/rudder-go-kit/testhelper/docker/resource/postgres" 16 ) 17 18 func TestMonitorDatabase(t *testing.T) { 19 pool, err := dockertest.NewPool("") 20 require.NoError(t, err) 21 postgresContainer, err := postgres.Setup(pool, t) 22 require.NoError(t, err) 23 24 postgresContainer.DB.SetMaxOpenConns(10) 25 postgresContainer.DB.SetMaxIdleConns(5) 26 27 statsStore, err := memstats.New() 28 require.NoError(t, err) 29 30 identifier := "test" 31 32 conf := config.New() 33 conf.Set("Database.statsReportInterval", "1s") 34 35 ctx, cancel := context.WithCancel(context.Background()) 36 defer cancel() 37 38 setupCh := make(chan struct{}) 39 go func() { 40 defer close(setupCh) 41 sqlutil.MonitorDatabase(ctx, conf, statsStore, postgresContainer.DB, identifier) 42 }() 43 44 require.Eventually(t, func() bool { 45 return statsStore.Get("db_max_open_connections", stats.Tags{ 46 "identifier": identifier, 47 }).LastValue() == 10 48 }, 49 5*time.Second, 50 100*time.Millisecond, 51 ) 52 require.Eventually(t, func() bool { 53 return statsStore.Get("db_open_connections", stats.Tags{ 54 "identifier": identifier, 55 }).LastValue() == 1 56 }, 57 5*time.Second, 58 100*time.Millisecond, 59 ) 60 require.Eventually(t, func() bool { 61 return statsStore.Get("db_idle", stats.Tags{ 62 "identifier": identifier, 63 }).LastValue() == 1 64 }, 65 5*time.Second, 66 100*time.Millisecond, 67 ) 68 69 cancel() 70 <-setupCh 71 }