test: coverage for foreign key violation err

This commit is contained in:
Saeid Saeidee 2023-06-11 21:17:41 +02:00
parent 2066138684
commit e550ed71b6
2 changed files with 49 additions and 4 deletions

View File

@ -58,3 +58,48 @@ func TestSupportedDialectorWithErrDuplicatedKey(t *testing.T) {
t.Fatalf("expected err: %v got err: %v", gorm.ErrDuplicatedKey, err)
}
}
func TestSupportedDialectorWithErrForeignKeyViolated(t *testing.T) {
type Country struct {
gorm.Model
Name string `gorm:"unique"`
}
type City struct {
gorm.Model
Name string `gorm:"unique"`
CountryID uint
Country Country `gorm:"Constraint:OnUpdate:CASCADE,OnDelete:CASCADE;FOREIGNKEY:CountryID;References:ID"`
}
db, err := OpenTestConnection(&gorm.Config{TranslateError: true})
if err != nil {
t.Fatalf("failed to connect database, got error %v", err)
}
dialectors := map[string]bool{"sqlite": true, "postgres": true, "mysql": false, "sqlserver": false}
if supported, found := dialectors[db.Dialector.Name()]; !(found && supported) {
return
}
if err = db.AutoMigrate(&Country{}, &City{}); err != nil {
t.Fatalf("failed to migrate countries & cities tables, got error: %v", err)
}
country := &Country{Name: "Netherlands"}
err = db.Create(country).Error
if err != nil {
t.Fatalf("failed to create country: %v", err)
}
err = db.Create(&City{Name: "Amsterdam", CountryID: country.ID}).Error
if err != nil {
t.Fatalf("failed to create city: %v", err)
}
err = db.Create(&City{Name: "Rotterdam", CountryID: 123}).Error
if !errors.Is(err, gorm.ErrForeignKeyViolated) {
t.Fatalf("expected err: %v got err: %v", gorm.ErrForeignKeyViolated, err)
}
}

View File

@ -6,13 +6,13 @@ require (
github.com/google/uuid v1.3.0
github.com/jackc/pgx/v5 v5.3.1 // indirect
github.com/jinzhu/now v1.1.5
github.com/lib/pq v1.10.8
github.com/lib/pq v1.10.9
github.com/mattn/go-sqlite3 v1.14.16 // indirect
gorm.io/driver/mysql v1.5.0
gorm.io/driver/postgres v1.5.0
gorm.io/driver/sqlite v1.5.0
gorm.io/driver/postgres v1.5.3-0.20230607070428-18bc84b75196
gorm.io/driver/sqlite v1.5.2
gorm.io/driver/sqlserver v1.5.1
gorm.io/gorm v1.25.1
gorm.io/gorm v1.25.2-0.20230530020048-26663ab9bf55
)
replace gorm.io/gorm => ../