-
-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathscanner_valuer_test.go
393 lines (322 loc) · 10.6 KB
/
scanner_valuer_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
package tests_test
import (
"context"
"database/sql"
"database/sql/driver"
"encoding/json"
"errors"
"fmt"
"reflect"
"regexp"
"strconv"
"testing"
"time"
"gorm.io/gorm"
"gorm.io/gorm/clause"
. "gorm.io/gorm/utils/tests"
)
func TestScannerValuer(t *testing.T) {
DB.Migrator().DropTable(&ScannerValuerStruct{})
if err := DB.Migrator().AutoMigrate(&ScannerValuerStruct{}); err != nil {
t.Fatalf("no error should happen when migrate scanner, valuer struct, got error %v", err)
}
data := ScannerValuerStruct{
Name: sql.NullString{String: "name", Valid: true},
Gender: &sql.NullString{String: "M", Valid: true},
Age: sql.NullInt64{Int64: 18, Valid: true},
Male: sql.NullBool{Bool: true, Valid: true},
Height: sql.NullFloat64{Float64: 1.8888, Valid: true},
Birthday: sql.NullTime{Time: time.Now(), Valid: true},
Allergen: NullString{sql.NullString{String: "Allergen", Valid: true}},
Password: EncryptedData("pass1"),
Bytes: []byte("byte"),
Num: 18,
Strings: StringsSlice{"a", "b", "c"},
Structs: StructsSlice{
{"name1", "value1"},
{"name2", "value2"},
},
Role: Role{Name: "admin"},
ExampleStruct: ExampleStruct{"name", "value1"},
ExampleStructPtr: &ExampleStruct{"name", "value2"},
}
if err := DB.Create(&data).Error; err != nil {
t.Fatalf("No error should happened when create scanner valuer struct, but got %v", err)
}
var result ScannerValuerStruct
if err := DB.Find(&result, "id = ?", data.ID).Error; err != nil {
t.Fatalf("no error should happen when query scanner, valuer struct, but got %v", err)
}
if result.ExampleStructPtr.Val != "value2" {
t.Errorf(`ExampleStructPtr.Val should equal to "value2", but got %v`, result.ExampleStructPtr.Val)
}
if result.ExampleStruct.Val != "value1" {
t.Errorf(`ExampleStruct.Val should equal to "value1", but got %#v`, result.ExampleStruct)
}
AssertObjEqual(t, data, result, "Name", "Gender", "Age", "Male", "Height", "Birthday", "Password", "Bytes", "Num", "Strings", "Structs")
}
func TestScannerValuerWithFirstOrCreate(t *testing.T) {
DB.Migrator().DropTable(&ScannerValuerStruct{})
if err := DB.Migrator().AutoMigrate(&ScannerValuerStruct{}); err != nil {
t.Errorf("no error should happen when migrate scanner, valuer struct")
}
data := ScannerValuerStruct{
Name: sql.NullString{String: "name", Valid: true},
Gender: &sql.NullString{String: "M", Valid: true},
Age: sql.NullInt64{Int64: 18, Valid: true},
ExampleStruct: ExampleStruct{"name", "value1"},
ExampleStructPtr: &ExampleStruct{"name", "value2"},
}
var result ScannerValuerStruct
tx := DB.Where(data).FirstOrCreate(&result)
if tx.RowsAffected != 1 {
t.Errorf("RowsAffected should be 1 after create some record")
}
if tx.Error != nil {
t.Errorf("Should not raise any error, but got %v", tx.Error)
}
AssertObjEqual(t, result, data, "Name", "Gender", "Age")
if err := DB.Where(data).Assign(ScannerValuerStruct{Age: sql.NullInt64{Int64: 18, Valid: true}}).FirstOrCreate(&result).Error; err != nil {
t.Errorf("Should not raise any error, but got %v", err)
}
if result.Age.Int64 != 18 {
t.Errorf("should update age to 18")
}
var result2 ScannerValuerStruct
if err := DB.First(&result2, result.ID).Error; err != nil {
t.Errorf("got error %v when query with %v", err, result.ID)
}
AssertObjEqual(t, result2, result, "ID", "CreatedAt", "UpdatedAt", "Name", "Gender", "Age")
}
func TestInvalidValuer(t *testing.T) {
DB.Migrator().DropTable(&ScannerValuerStruct{})
if err := DB.Migrator().AutoMigrate(&ScannerValuerStruct{}); err != nil {
t.Errorf("no error should happen when migrate scanner, valuer struct")
}
data := ScannerValuerStruct{
Password: EncryptedData("xpass1"),
ExampleStruct: ExampleStruct{"name", "value1"},
ExampleStructPtr: &ExampleStruct{"name", "value2"},
}
if err := DB.Create(&data).Error; err == nil {
t.Errorf("Should failed to create data with invalid data")
}
data.Password = EncryptedData("pass1")
if err := DB.Create(&data).Error; err != nil {
t.Errorf("Should got no error when creating data, but got %v", err)
}
if err := DB.Model(&data).Update("password", EncryptedData("xnewpass")).Error; err == nil {
t.Errorf("Should failed to update data with invalid data")
}
if err := DB.Model(&data).Update("password", EncryptedData("newpass")).Error; err != nil {
t.Errorf("Should got no error update data with valid data, but got %v", err)
}
AssertEqual(t, data.Password, EncryptedData("newpass"))
}
type ScannerValuerStruct struct {
gorm.Model
Name sql.NullString
Gender *sql.NullString
Age sql.NullInt64
Male sql.NullBool
Height sql.NullFloat64
Birthday sql.NullTime
Allergen NullString
Password EncryptedData
Bytes []byte
Num Num
Strings StringsSlice
Structs StructsSlice
Role Role
UserID *sql.NullInt64
User User
EmptyTime EmptyTime
ExampleStruct ExampleStruct
ExampleStructPtr *ExampleStruct
}
type EncryptedData []byte
func (data *EncryptedData) Scan(value interface{}) error {
if b, ok := value.([]byte); ok {
if len(b) < 3 || b[0] != '*' || b[1] != '*' || b[2] != '*' {
return errors.New("Too short")
}
*data = append((*data)[0:], b[3:]...)
return nil
} else if s, ok := value.(string); ok {
*data = []byte(s[3:])
return nil
}
return errors.New("Bytes expected")
}
func (data EncryptedData) Value() (driver.Value, error) {
if len(data) > 0 && data[0] == 'x' {
// needed to test failures
return nil, errors.New("Should not start with 'x'")
}
// prepend asterisks
return append([]byte("***"), data...), nil
}
type Num int64
func (i *Num) Scan(src interface{}) error {
switch s := src.(type) {
case []byte:
n, _ := strconv.Atoi(string(s))
*i = Num(n)
case int64:
*i = Num(s)
default:
return errors.New("Cannot scan NamedInt from " + reflect.ValueOf(src).String())
}
return nil
}
type StringsSlice []string
func (l StringsSlice) Value() (driver.Value, error) {
bytes, err := json.Marshal(l)
return string(bytes), err
}
func (l *StringsSlice) Scan(input interface{}) error {
switch value := input.(type) {
case string:
return json.Unmarshal([]byte(value), l)
case []byte:
return json.Unmarshal(value, l)
default:
return errors.New("not supported")
}
}
type ExampleStruct struct {
Name string
Val string
}
func (ExampleStruct) GormDataType() string {
return "bytes"
}
func (s ExampleStruct) Value() (driver.Value, error) {
if len(s.Name) == 0 {
return nil, nil
}
// for test, has no practical meaning
s.Name = ""
return json.Marshal(s)
}
func (s *ExampleStruct) Scan(src interface{}) error {
switch value := src.(type) {
case string:
return json.Unmarshal([]byte(value), s)
case []byte:
return json.Unmarshal(value, s)
default:
return errors.New("not supported")
}
}
type StructsSlice []ExampleStruct
func (l StructsSlice) Value() (driver.Value, error) {
bytes, err := json.Marshal(l)
return string(bytes), err
}
func (l *StructsSlice) Scan(input interface{}) error {
switch value := input.(type) {
case string:
return json.Unmarshal([]byte(value), l)
case []byte:
return json.Unmarshal(value, l)
default:
return errors.New("not supported")
}
}
type Role struct {
Name string `gorm:"size:256"`
}
func (role *Role) Scan(value interface{}) error {
if b, ok := value.([]uint8); ok {
role.Name = string(b)
} else {
role.Name = value.(string)
}
return nil
}
func (role Role) Value() (driver.Value, error) {
return role.Name, nil
}
func (role Role) IsAdmin() bool {
return role.Name == "admin"
}
type EmptyTime struct {
time.Time
}
func (t *EmptyTime) Scan(v interface{}) error {
nullTime := sql.NullTime{}
err := nullTime.Scan(v)
t.Time = nullTime.Time
return err
}
func (t EmptyTime) Value() (driver.Value, error) {
return time.Now() /* pass tests, mysql 8 doesn't support 0000-00-00 by default */, nil
}
type NullString struct {
sql.NullString
}
type Point struct {
X, Y int
}
func (point Point) GormDataType() string {
return "geo"
}
func (point Point) GormValue(ctx context.Context, db *gorm.DB) clause.Expr {
return clause.Expr{
SQL: "ST_PointFromText(?)",
Vars: []interface{}{fmt.Sprintf("POINT(%d %d)", point.X, point.Y)},
}
}
func TestGORMValuer(t *testing.T) {
type UserWithPoint struct {
Name string
Point Point
}
dryRunDB := DB.Session(&gorm.Session{DryRun: true})
stmt := dryRunDB.Create(&UserWithPoint{
Name: "jinzhu",
Point: Point{X: 100, Y: 100},
}).Statement
if stmt.SQL.String() == "" || len(stmt.Vars) != 2 {
t.Errorf("Failed to generate sql, got %v", stmt.SQL.String())
}
if !regexp.MustCompile(`INSERT INTO .user_with_points. \(.name.,.point.\) VALUES \(.+,ST_PointFromText\(.+\)\)`).MatchString(stmt.SQL.String()) {
t.Errorf("insert with sql.Expr, but got %v", stmt.SQL.String())
}
if !reflect.DeepEqual([]interface{}{"jinzhu", "POINT(100 100)"}, stmt.Vars) {
t.Errorf("generated vars is not equal, got %v", stmt.Vars)
}
stmt = dryRunDB.Model(UserWithPoint{}).Create(map[string]interface{}{
"Name": "jinzhu",
"Point": clause.Expr{SQL: "ST_PointFromText(?)", Vars: []interface{}{"POINT(100 100)"}},
}).Statement
if !regexp.MustCompile(`INSERT INTO .user_with_points. \(.name.,.point.\) VALUES \(.+,ST_PointFromText\(.+\)\)`).MatchString(stmt.SQL.String()) {
t.Errorf("insert with sql.Expr, but got %v", stmt.SQL.String())
}
if !reflect.DeepEqual([]interface{}{"jinzhu", "POINT(100 100)"}, stmt.Vars) {
t.Errorf("generated vars is not equal, got %v", stmt.Vars)
}
stmt = dryRunDB.Table("user_with_points").Create(&map[string]interface{}{
"Name": "jinzhu",
"Point": clause.Expr{SQL: "ST_PointFromText(?)", Vars: []interface{}{"POINT(100 100)"}},
}).Statement
if !regexp.MustCompile(`INSERT INTO .user_with_points. \(.Name.,.Point.\) VALUES \(.+,ST_PointFromText\(.+\)\)`).MatchString(stmt.SQL.String()) {
t.Errorf("insert with sql.Expr, but got %v", stmt.SQL.String())
}
if !reflect.DeepEqual([]interface{}{"jinzhu", "POINT(100 100)"}, stmt.Vars) {
t.Errorf("generated vars is not equal, got %v", stmt.Vars)
}
stmt = dryRunDB.Session(&gorm.Session{
AllowGlobalUpdate: true,
}).Model(&UserWithPoint{}).Updates(UserWithPoint{
Name: "jinzhu",
Point: Point{X: 100, Y: 100},
}).Statement
if !regexp.MustCompile(`UPDATE .user_with_points. SET .name.=.+,.point.=ST_PointFromText\(.+\)`).MatchString(stmt.SQL.String()) {
t.Errorf("update with sql.Expr, but got %v", stmt.SQL.String())
}
if !reflect.DeepEqual([]interface{}{"jinzhu", "POINT(100 100)"}, stmt.Vars) {
t.Errorf("generated vars is not equal, got %v", stmt.Vars)
}
}