Skip to content

Commit

Permalink
✅ 添加创建数据触发唯一约束条件单元测试
Browse files Browse the repository at this point in the history
修改优化单元测试相关代码

Signed-off-by: liutianqi <zixizixi@vip.qq.com>
  • Loading branch information
iTanken committed Jan 8, 2024
1 parent b0f6c72 commit 1853e2e
Show file tree
Hide file tree
Showing 3 changed files with 176 additions and 48 deletions.
108 changes: 107 additions & 1 deletion create_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,20 @@ package oracle

import (
"encoding/json"
"strings"
"testing"
"time"
)

func TestMergeCreate(t *testing.T) {
db, err := openTestConnection(true, true)
db, err := dbNamingCase, dbErrors[0]
if err != nil {
t.Fatal(err)
}
if db == nil {
t.Log("db is nil!")
return
}

model := TestTableUser{}
migrator := db.Set("gorm:table_comments", "用户信息表").Migrator()
Expand Down Expand Up @@ -65,3 +71,103 @@ func TestMergeCreate(t *testing.T) {
t.Logf("result: %s", dataJsonBytes)
})
}

type TestTableUserUnique struct {
ID uint64 `gorm:"column:id;size:64;not null;autoIncrement:true;autoIncrementIncrement:1;primaryKey;comment:自增 ID" json:"id"`
UID string `gorm:"column:uid;type:varchar(50);comment:用户身份标识;unique" json:"uid"`
Name string `gorm:"column:name;size:50;comment:用户姓名" json:"name"`
Account string `gorm:"column:account;type:varchar(50);comment:登录账号" json:"account"`
Password string `gorm:"column:password;type:varchar(512);comment:登录密码(密文)" json:"password"`
Email string `gorm:"column:email;type:varchar(128);comment:邮箱地址" json:"email"`
PhoneNumber string `gorm:"column:phone_number;type:varchar(15);comment:E.164" json:"phoneNumber"`
Sex string `gorm:"column:sex;type:char(1);comment:性别" json:"sex"`
Birthday *time.Time `gorm:"column:birthday;->:false;<-:create;comment:生日" json:"birthday,omitempty"`
UserType int `gorm:"column:user_type;size:8;comment:用户类型" json:"userType"`
Enabled bool `gorm:"column:enabled;comment:是否可用" json:"enabled"`
Remark string `gorm:"column:remark;size:1024;comment:备注信息" json:"remark"`
}

func (TestTableUserUnique) TableName() string {
return "test_user_unique"
}

func TestMergeCreateUnique(t *testing.T) {
db, err := dbNamingCase, dbErrors[0]
if err != nil {
t.Fatal(err)
}
if db == nil {
t.Log("db is nil!")
return
}

model := TestTableUserUnique{}
migrator := db.Set("gorm:table_comments", "用户信息表").Migrator()
if migrator.HasTable(model) {
if err = migrator.DropTable(model); err != nil {
t.Fatalf("DropTable() error = %v", err)
}
}
if err = migrator.AutoMigrate(model); err != nil {
t.Fatalf("AutoMigrate() error = %v", err)
} else if err == nil {
t.Log("AutoMigrate() success!")
}

data := []TestTableUserUnique{
{
UID: "U1",
Name: "Lisa",
Account: "lisa",
Password: "H6aLDNr",
PhoneNumber: "+8616666666666",
Sex: "0",
UserType: 1,
Enabled: true,
},
{
UID: "U2",
Name: "Daniela",
Account: "daniela",
Password: "Si7l1sRIC79",
PhoneNumber: "+8619999999999",
Sex: "1",
UserType: 1,
Enabled: true,
},
{
UID: "U2",
Name: "Daniela",
Account: "daniela",
Password: "Si7l1sRIC79",
PhoneNumber: "+8619999999999",
Sex: "1",
UserType: 1,
Enabled: true,
},
}
t.Run("MergeCreateUnique", func(t *testing.T) {
tx := db.Create(&data)
if err = tx.Error; err != nil {
if strings.HasPrefix(err.Error(), "ORA-00001") {
t.Log(err) // ORA-00001: 违反唯一约束条件
var gotData []TestTableUserUnique
tx = db.Where(map[string]interface{}{"uid": []string{"U1", "U2"}}).Find(&gotData)
if err = tx.Error; err != nil {
t.Fatal(err)
} else {
if len(gotData) > 0 {
t.Error("Unique constraint violation, but some data was inserted!")
} else {
t.Log("Unique constraint violation, rolled back!")
}
}
} else {
t.Fatal(err)
}
return
}
dataJsonBytes, _ := json.MarshalIndent(data, "", " ")
t.Logf("result: %s", dataJsonBytes)
})
}
10 changes: 6 additions & 4 deletions migrator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@ import (
)

func TestMigrator_AutoMigrate(t *testing.T) {
db, err := openTestConnection(true, true)
if db == nil && err == nil {
return
} else if err != nil {
db, err := dbNamingCase, dbErrors[0]
if err != nil {
t.Fatal(err)
}
if db == nil {
t.Log("db is nil!")
return
}

type args struct {
drop bool
Expand Down
106 changes: 63 additions & 43 deletions oracle_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,56 +13,26 @@ import (
"gorm.io/gorm/logger"
)

var (
dbNamingCase *gorm.DB
dbIgnoreCase *gorm.DB

dbErrors = make([]error, 2)
)

func init() {
if wait := os.Getenv("GORM_ORA_WAIT_MIN"); wait != "" {
if min, e := strconv.Atoi(wait); e == nil {
log.Println("wait for oracle database initialization to complete...")
time.Sleep(time.Duration(min) * time.Minute)
}
}
}

func TestGetStringExpr(t *testing.T) {
db, err := openTestConnection(true, true)
if db == nil && err == nil {
return
} else if err != nil {
t.Fatal(err)
}

type args struct {
prepareSQL string
value string
quote bool
}
tests := []struct {
name string
args args
wantSQL string
}{
{"1", args{`SELECT ? AS HELLO FROM DUAL`, "Hi!", true}, `SELECT 'Hi!' AS HELLO FROM DUAL`},
{"2", args{`SELECT '?' AS HELLO FROM DUAL`, "Hi!", false}, `SELECT 'Hi!' AS HELLO FROM DUAL`},
{"3", args{`SELECT ? AS HELLO FROM DUAL`, "What's your name?", true}, `SELECT q'[What's your name?]' AS HELLO FROM DUAL`},
{"4", args{`SELECT '?' AS HELLO FROM DUAL`, "What's your name?", false}, `SELECT 'What''s your name?' AS HELLO FROM DUAL`},
{"5", args{`SELECT ? AS HELLO FROM DUAL`, "What's up]'?", true}, `SELECT q'{What's up]'?}' AS HELLO FROM DUAL`},
{"6", args{`SELECT ? AS HELLO FROM DUAL`, "What's up]'}'?", true}, `SELECT q'<What's up]'}'?>' AS HELLO FROM DUAL`},
{"7", args{`SELECT ? AS HELLO FROM DUAL`, "What's up]'}'>'?", true}, `SELECT q'(What's up]'}'>'?)' AS HELLO FROM DUAL`},
{"8", args{`SELECT ? AS HELLO FROM DUAL`, "What's up)'}'>'?", true}, `SELECT q'[What's up)'}'>'?]' AS HELLO FROM DUAL`},
var err error
if dbNamingCase, err = openTestConnection(true, true); err != nil {
dbErrors[0] = err
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotSQL := db.ToSQL(func(tx *gorm.DB) *gorm.DB {
return tx.Raw(tt.args.prepareSQL, GetStringExpr(tt.args.value, tt.args.quote))
})
if !reflect.DeepEqual(gotSQL, tt.wantSQL) {
t.Fatalf("ToSQL = %v, want %v", gotSQL, tt.wantSQL)
}
var results []map[string]interface{}
if err = db.Raw(gotSQL).Find(&results).Error; err != nil {
t.Fatalf("finds all records from raw sql got error: %v", err)
}
t.Log("result:", results)
})
if dbIgnoreCase, err = openTestConnection(true, false); err != nil {
dbErrors[1] = err
}
}

Expand Down Expand Up @@ -117,10 +87,14 @@ func openTestConnection(ignoreCase, namingCase bool) (db *gorm.DB, err error) {
}

func TestAddSessionParams(t *testing.T) {
db, err := openTestConnection(true, false)
db, err := dbIgnoreCase, dbErrors[1]
if err != nil {
t.Fatal(err)
}
if db == nil {
t.Log("db is nil!")
return
}
var sqlDB *sql.DB
if sqlDB, err = db.DB(); err != nil {
t.Fatal(err)
Expand Down Expand Up @@ -164,3 +138,49 @@ func TestAddSessionParams(t *testing.T) {
})
}
}

func TestGetStringExpr(t *testing.T) {
db, err := dbNamingCase, dbErrors[0]
if err != nil {
t.Fatal(err)
}
if db == nil {
t.Log("db is nil!")
return
}

type args struct {
prepareSQL string
value string
quote bool
}
tests := []struct {
name string
args args
wantSQL string
}{
{"1", args{`SELECT ? AS HELLO FROM DUAL`, "Hi!", true}, `SELECT 'Hi!' AS HELLO FROM DUAL`},
{"2", args{`SELECT '?' AS HELLO FROM DUAL`, "Hi!", false}, `SELECT 'Hi!' AS HELLO FROM DUAL`},
{"3", args{`SELECT ? AS HELLO FROM DUAL`, "What's your name?", true}, `SELECT q'[What's your name?]' AS HELLO FROM DUAL`},
{"4", args{`SELECT '?' AS HELLO FROM DUAL`, "What's your name?", false}, `SELECT 'What''s your name?' AS HELLO FROM DUAL`},
{"5", args{`SELECT ? AS HELLO FROM DUAL`, "What's up]'?", true}, `SELECT q'{What's up]'?}' AS HELLO FROM DUAL`},
{"6", args{`SELECT ? AS HELLO FROM DUAL`, "What's up]'}'?", true}, `SELECT q'<What's up]'}'?>' AS HELLO FROM DUAL`},
{"7", args{`SELECT ? AS HELLO FROM DUAL`, "What's up]'}'>'?", true}, `SELECT q'(What's up]'}'>'?)' AS HELLO FROM DUAL`},
{"8", args{`SELECT ? AS HELLO FROM DUAL`, "What's up)'}'>'?", true}, `SELECT q'[What's up)'}'>'?]' AS HELLO FROM DUAL`},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotSQL := db.ToSQL(func(tx *gorm.DB) *gorm.DB {
return tx.Raw(tt.args.prepareSQL, GetStringExpr(tt.args.value, tt.args.quote))
})
if !reflect.DeepEqual(gotSQL, tt.wantSQL) {
t.Fatalf("ToSQL = %v, want %v", gotSQL, tt.wantSQL)
}
var results []map[string]interface{}
if err = db.Raw(gotSQL).Find(&results).Error; err != nil {
t.Fatalf("finds all records from raw sql got error: %v", err)
}
t.Log("result:", results)
})
}
}

0 comments on commit 1853e2e

Please sign in to comment.