github.com/PDOK/gokoala@v0.50.6/internal/ogc/features/datasources/sqllog_test.go (about) 1 package datasources 2 3 import ( 4 "bytes" 5 "context" 6 "log" 7 "os" 8 "testing" 9 "time" 10 11 "github.com/stretchr/testify/assert" 12 ) 13 14 func TestNewSQLLogFromEnv(t *testing.T) { 15 tests := []struct { 16 name string 17 logSQL string 18 slowQueryTime string 19 wantLogSQL bool 20 wantDuration time.Duration 21 }{ 22 {"Both environment variables are set", "true", "5s", true, 5 * time.Second}, 23 {"Only logSql is set", "false", "", false, 5 * time.Second}, 24 {"Only slowQueryTime is set", "", "10s", false, 10 * time.Second}, 25 {"Neither environment variables are set", "", "", false, 5 * time.Second}, 26 } 27 for _, tt := range tests { 28 t.Run(tt.name, func(t *testing.T) { 29 if tt.logSQL != "" { 30 t.Setenv(envLogSQL, tt.logSQL) 31 } else { 32 t.Setenv(envLogSQL, "") 33 } 34 if tt.slowQueryTime != "" { 35 t.Setenv(envSlowQueryTime, tt.slowQueryTime) 36 } else { 37 t.Setenv(envSlowQueryTime, "") 38 } 39 got := NewSQLLogFromEnv() 40 assert.Equal(t, tt.wantLogSQL, got.LogSQL) 41 assert.Equal(t, tt.wantDuration, got.SlowQueryTime) 42 }) 43 } 44 } 45 46 func TestSQLLog_CheckLogMessageWhenExplicitEnabled(t *testing.T) { 47 var capturedLogOutput bytes.Buffer 48 log.SetOutput(&capturedLogOutput) 49 t.Cleanup(func() { log.SetOutput(os.Stderr) }) 50 51 s := &SQLLog{LogSQL: true, SlowQueryTime: 10 * time.Hour} 52 53 ctx, err := s.Before(context.Background(), "SELECT * FROM test WHERE id = ?", 123) 54 assert.NoError(t, err) 55 56 _, err = s.After(ctx, "SELECT * FROM test WHERE id = ?", 123) 57 assert.NoError(t, err) 58 59 assert.Contains(t, capturedLogOutput.String(), "SQL:\nSELECT * FROM test WHERE id = 123\n--- SQL query took") 60 } 61 62 func TestSQLLog_CheckLogInCaseOfSlowQuery(t *testing.T) { 63 var capturedLogOutput bytes.Buffer 64 log.SetOutput(&capturedLogOutput) 65 t.Cleanup(func() { log.SetOutput(os.Stderr) }) 66 67 s := &SQLLog{LogSQL: false, SlowQueryTime: 1 * time.Nanosecond} 68 69 ctx, err := s.Before(context.Background(), "SELECT * FROM test WHERE id = ?", 123) 70 assert.NoError(t, err) 71 72 _, err = s.After(ctx, "SELECT * FROM test WHERE id = ?", 123) 73 assert.NoError(t, err) 74 75 assert.Contains(t, capturedLogOutput.String(), "SQL:\nSELECT * FROM test WHERE id = 123\n--- SQL query took") 76 }