package database import ( "database/sql" "os" "testing" "github.com/stretchr/testify/mock" ) // Mock for the database service type MockService struct { mock.Mock } func (m *MockService) Health() map[string]map[string]string { args := m.Called() return args.Get(0).(map[string]map[string]string) } func (m *MockService) GetDB(name string) (*sql.DB, error) { args := m.Called(name) return args.Get(0).(*sql.DB), args.Error(1) } func (m *MockService) Close() error { return m.Called().Error(0) } func (m *MockService) ListDBs() []string { args := m.Called() return args.Get(0).([]string) } func (m *MockService) GetDBType(name string) (DatabaseType, error) { args := m.Called(name) return args.Get(0).(DatabaseType), args.Error(1) } func TestNew(t *testing.T) { srv := New() if srv == nil { t.Fatal("New() returned nil") } } func TestHealth(t *testing.T) { srv := New() stats := srv.Health() // Since we don't have any databases configured in test, we expect empty stats if len(stats) == 0 { t.Log("No databases configured, health check returns empty stats") return } // If we have databases, check their health for dbName, dbStats := range stats { if dbStats["status"] != "up" { t.Errorf("database %s status is not up: %s", dbName, dbStats["status"]) } if err, ok := dbStats["error"]; ok && err != "" { t.Errorf("database %s has error: %s", dbName, err) } } } func TestClose(t *testing.T) { srv := New() if srv.Close() != nil { t.Fatalf("expected Close() to return nil") } } // Test for loading database configurations func TestLoadDatabaseConfigs(t *testing.T) { // Set environment variables for testing os.Setenv("DB_TEST_TYPE", "postgres") os.Setenv("DB_TEST_HOST", "localhost") os.Setenv("DB_TEST_PORT", "5432") os.Setenv("DB_TEST_DATABASE", "testdb") os.Setenv("DB_TEST_USERNAME", "testuser") os.Setenv("DB_TEST_PASSWORD", "testpass") configs := loadDatabaseConfigs() if len(configs) == 0 { t.Fatal("Expected database configurations to be loaded") } if configs[0].Type != "postgres" { t.Errorf("Expected database type to be postgres, got %s", configs[0].Type) } } // Test for connection pooling settings func TestConnectionPooling(t *testing.T) { srv := New() // Check health after loading configurations stats := srv.Health() if len(stats) == 0 { t.Fatal("Expected databases to be configured, but found none") } db, err := srv.GetDB("testdb") if err != nil { t.Fatalf("Failed to get database: %v", err) } if db.Stats().MaxOpenConnections != 10 { t.Errorf("Expected max open connections to be 10, got %d", db.Stats().MaxOpenConnections) } } // Test for error handling during connection func TestErrorHandling(t *testing.T) { srv := New() // Check health to see if it handles errors stats := srv.Health() if len(stats) > 0 { t.Fatal("Expected no databases to be configured, but found some") } }