func OpenTestConnection() (db *gorm.DB, err error) { switch os.Getenv("GORM_DIALECT") { case "mysql": // CREATE USER 'gorm'@'localhost' IDENTIFIED BY 'gorm'; // CREATE DATABASE gorm; // GRANT ALL ON gorm.* TO 'gorm'@'localhost'; fmt.Println("testing mysql...") dbhost := os.Getenv("GORM_DBADDRESS") if dbhost != "" { dbhost = fmt.Sprintf("tcp(%v)", dbhost) } db, err = gorm.Open("mysql", fmt.Sprintf("gorm:gorm@%v/gorm?charset=utf8&parseTime=True", dbhost)) case "postgres": fmt.Println("testing postgres...") dbhost := os.Getenv("GORM_DBHOST") if dbhost != "" { dbhost = fmt.Sprintf("host=%v ", dbhost) } db, err = gorm.Open("postgres", fmt.Sprintf("%vuser=gorm password=gorm DB.name=gorm sslmode=disable", dbhost)) case "foundation": fmt.Println("testing foundation...") db, err = gorm.Open("foundation", "dbname=gorm port=15432 sslmode=disable") case "mssql": fmt.Println("testing mssql...") db, err = gorm.Open("mssql", "server=SERVER_HERE;database=rogue;user id=USER_HERE;password=PW_HERE;port=1433") default: fmt.Println("testing sqlite3...") db, err = gorm.Open("sqlite3", filepath.Join(os.TempDir(), "gorm.db")) } // db.SetLogger(Logger{log.New(os.Stdout, "\r\n", 0)}) // db.SetLogger(log.New(os.Stdout, "\r\n", 0)) if os.Getenv("DEBUG") == "true" { db.LogMode(true) } db.DB().SetMaxIdleConns(10) return }
func TestOpenExistingDB(t *testing.T) { DB.Save(&User{Name: "jnfeinstein"}) dialect := os.Getenv("GORM_DIALECT") db, err := gorm.Open(dialect, DB.DB()) if err != nil { t.Errorf("Should have wrapped the existing DB connection") } var user User if db.Where("name = ?", "jnfeinstein").First(&user).Error == gorm.ErrRecordNotFound { t.Errorf("Should have found existing record") } }
func TestCompatibilityMode(t *testing.T) { DB, _ := gorm.Open("testdb", "") testdb.SetQueryFunc(func(query string) (driver.Rows, error) { columns := []string{"id", "name", "age"} result := ` 1,Tim,20 2,Joe,25 3,Bob,30 ` return testdb.RowsFromCSVString(columns, result), nil }) var users []User DB.Find(&users) if (users[0].Name != "Tim") || len(users) != 3 { t.Errorf("Unexcepted result returned") } }