Files
mysqlx/mysqlx_test.go
2026-06-07 15:20:10 +08:00

83 lines
2.0 KiB
Go

package mysqlx
import (
"testing"
"time"
"github.com/DATA-DOG/go-sqlmock"
drivermysql "gorm.io/driver/mysql"
"gorm.io/gorm/logger"
)
type testModel struct {
ID uint `gorm:"primaryKey"`
Name string
}
func TestNewWithCustomDialector(t *testing.T) {
sqlDB, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("failed to create sqlmock: %v", err)
}
defer sqlDB.Close()
mock.ExpectQuery("SELECT VERSION()").WillReturnRows(sqlmock.NewRows([]string{"VERSION()"}).AddRow("5.7.0"))
client, err := NewDB(
WithDialector(drivermysql.New(drivermysql.Config{Conn: sqlDB})),
WithLogger(logger.Default.LogMode(logger.Silent)),
WithConnectionPool(2, 5, 5*time.Minute, 10*time.Minute),
)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer client.Close()
if client.DB() == nil {
t.Fatal("expected non-nil DB")
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("sqlmock expectations were not met: %v", err)
}
}
func TestBuildDSNWithExpandedConfig(t *testing.T) {
cfg := defaultConfig()
WithDSNUser("testuser")(cfg)
WithDSNPassword("password")(cfg)
WithDSNNet("tcp")(cfg)
WithDSNAddr("127.0.0.1:3306")(cfg)
WithDSNDBName("testdb")(cfg)
WithDSNParams(map[string]string{"parseTime": "true", "loc": "Local"})(cfg)
WithDSNTLSConfig("false")(cfg)
dsn, err := buildDSN(cfg)
if err != nil {
t.Fatalf("buildDSN returned error: %v", err)
}
if dsn == "" {
t.Fatal("expected non-empty DSN")
}
}
func TestDefaultConfigUsesSingularTable(t *testing.T) {
cfg := defaultConfig()
if !cfg.NamingStrategy.SingularTable {
t.Fatal("expected default naming strategy to use singular table names")
}
}
func TestWithSingularTableOption(t *testing.T) {
cfg := defaultConfig()
WithSingularTable(false)(cfg)
if cfg.NamingStrategy.SingularTable {
t.Fatal("expected naming strategy singular table to be disabled")
}
}
func TestNewWithoutDSNOrDialector(t *testing.T) {
_, err := NewDB()
if err == nil {
t.Fatal("expected error when DSN and Dialector are missing")
}
}