forked from coocood/qbs
/
model_test.go
117 lines (105 loc) · 2.41 KB
/
model_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
package qbs
import (
"github.com/coocood/assrt"
"testing"
"time"
)
func TestParseTags(t *testing.T) {
assert := assrt.NewAssert(t)
m := parseTags(`fk`)
_, ok := m["fk"]
assert.True(ok)
m = parseTags(`notnull,default:'banana'`)
_, ok = m["notnull"]
assert.True(ok)
x, _ := m["default"]
assert.Equal("'banana'", x)
}
func TestFieldOmit(t *testing.T) {
assert := assrt.NewAssert(t)
type Schema struct {
A string `sql:"-"`
B string
}
m := structPtrToModel(&Schema{}, true)
assert.OneLen(m.Fields)
}
func TestInterfaceToModelWithReference(t *testing.T) {
assert := assrt.NewAssert(t)
type parent struct {
Id Id
Name string
Value string
}
type table struct {
ColPrimary Id
FatherId int64 `sql:"fk:Father"`
Father *parent
}
table1 := &table{
6, 3, &parent{3, "Mrs. A", "infinite"},
}
m := structPtrToModel(table1, true)
ref, ok := m.Refs["Father"]
assert.MustTrue(ok)
f := ref.Model.Fields[1]
x, ok := f.Value.(string)
assert.True(ok)
assert.Equal("Mrs. A", x)
}
type indexedTable struct {
ColPrimary Id
ColNotNull string `sql:"notnull,default:'banana'"`
ColVarChar string `sql:"size:64"`
ColTime time.Time
}
func (table *indexedTable) Indexes(indexes *Indexes) {
indexes.Add("col_primary", "col_time")
indexes.AddUnique("col_var_char", "col_time")
}
func TestInterfaceToModel(t *testing.T) {
assert := assrt.NewAssert(t)
now := time.Now()
table1 := &indexedTable{
ColPrimary: 6,
ColVarChar: "orange",
ColTime: now,
}
m := structPtrToModel(table1, true)
assert.Equal("col_primary", m.Pk.Name)
assert.Equal(4, len(m.Fields))
assert.Equal(2, len(m.Indexes))
assert.Equal("col_primary_col_time", m.Indexes[0].Name)
assert.True(!m.Indexes[0].Unique)
assert.Equal("col_var_char_col_time", m.Indexes[1].Name)
assert.True(m.Indexes[1].Unique)
f := m.Fields[0]
id, _ := f.Value.(Id)
assert.Equal(6, id)
assert.True(f.PrimaryKey())
f = m.Fields[1]
assert.Equal("'banana'", f.Default())
f = m.Fields[2]
str, _ := f.Value.(string)
assert.Equal("orange", str)
assert.Equal(64, f.Size())
f = m.Fields[3]
tm, _ := f.Value.(time.Time)
assert.Equal(now, tm)
}
func TestInterfaceToSubModel(t *testing.T) {
assert := assrt.NewAssert(t)
type User struct {
Id Id
Name string
}
type Post struct {
Id Id
AuthorId int64 `sql:"fk:Author"`
Author *User
Content string
}
pst := new(Post)
model := structPtrToModel(pst, true)
assert.OneLen(model.Refs)
}