db_pool_test.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package repository
  2. import (
  3. "database/sql"
  4. "testing"
  5. "time"
  6. "github.com/Wei-Shaw/sub2api/internal/config"
  7. "github.com/stretchr/testify/require"
  8. _ "github.com/lib/pq"
  9. )
  10. func TestClampDBPoolSettings(t *testing.T) {
  11. tests := []struct {
  12. name string
  13. connMaxLifetime int
  14. connMaxIdleTime int
  15. wantMaxLifetime time.Duration
  16. wantConnMaxIdleTime time.Duration
  17. }{
  18. {
  19. name: "zero values fall back to safe defaults",
  20. connMaxLifetime: 0,
  21. connMaxIdleTime: 0,
  22. wantMaxLifetime: 30 * time.Minute,
  23. wantConnMaxIdleTime: 5 * time.Minute,
  24. },
  25. {
  26. name: "negative values fall back to safe defaults",
  27. connMaxLifetime: -1,
  28. connMaxIdleTime: -5,
  29. wantMaxLifetime: 30 * time.Minute,
  30. wantConnMaxIdleTime: 5 * time.Minute,
  31. },
  32. {
  33. name: "reasonable values pass through",
  34. connMaxLifetime: 15,
  35. connMaxIdleTime: 3,
  36. wantMaxLifetime: 15 * time.Minute,
  37. wantConnMaxIdleTime: 3 * time.Minute,
  38. },
  39. {
  40. name: "values over twenty four hours fall back to safe defaults",
  41. connMaxLifetime: 24*60 + 1,
  42. connMaxIdleTime: 24*60 + 1,
  43. wantMaxLifetime: 30 * time.Minute,
  44. wantConnMaxIdleTime: 5 * time.Minute,
  45. },
  46. }
  47. for _, tt := range tests {
  48. t.Run(tt.name, func(t *testing.T) {
  49. cfg := &config.Config{
  50. Database: config.DatabaseConfig{
  51. MaxOpenConns: 50,
  52. MaxIdleConns: 10,
  53. ConnMaxLifetimeMinutes: tt.connMaxLifetime,
  54. ConnMaxIdleTimeMinutes: tt.connMaxIdleTime,
  55. },
  56. }
  57. settings := clampDBPoolSettings(cfg)
  58. require.Equal(t, 50, settings.MaxOpenConns)
  59. require.Equal(t, 10, settings.MaxIdleConns)
  60. require.Equal(t, tt.wantMaxLifetime, settings.ConnMaxLifetime)
  61. require.Equal(t, tt.wantConnMaxIdleTime, settings.ConnMaxIdleTime)
  62. })
  63. }
  64. }
  65. func TestApplyDBPoolSettings(t *testing.T) {
  66. cfg := &config.Config{
  67. Database: config.DatabaseConfig{
  68. MaxOpenConns: 40,
  69. MaxIdleConns: 8,
  70. ConnMaxLifetimeMinutes: 15,
  71. ConnMaxIdleTimeMinutes: 3,
  72. },
  73. }
  74. db, err := sql.Open("postgres", "host=127.0.0.1 port=5432 user=postgres sslmode=disable")
  75. require.NoError(t, err)
  76. t.Cleanup(func() {
  77. _ = db.Close()
  78. })
  79. applyDBPoolSettings(db, cfg)
  80. stats := db.Stats()
  81. require.Equal(t, 40, stats.MaxOpenConnections)
  82. }