add Smap comment and modify testcase

This commit is contained in:
theoneLee 2019-10-15 11:38:35 +08:00
parent 6fe19d9611
commit d87621ff2c
2 changed files with 35 additions and 41 deletions

View File

@ -66,6 +66,7 @@ func ToColumnName(name string) string {
return TheNamingStrategy.ColumnName(name)
}
// mapping cache map
var Smap = newSafeMap()
func defaultNamer(name string) string {

View File

@ -32,45 +32,16 @@ func TestTheNamingStrategy(t *testing.T) {
func TestAddNamingStrategy(t *testing.T) {
// users can set their custom namer
custom := &gorm.NamingStrategy{
Column: CustomNamer,
}
gorm.AddNamingStrategy(custom)
// test
cases := []struct {
name string
namer gorm.Namer
expected string
}{
{name: "auth", expected: "auth", namer: gorm.TheNamingStrategy.DB},
{name: "userRestrictions", expected: "user_restrictions", namer: gorm.TheNamingStrategy.Table},
{name: "clientID", expected: "clientID", namer: gorm.TheNamingStrategy.Column},
{name: "Client0ID", expected: "client0ID", namer: gorm.TheNamingStrategy.Column},
{name: "_Client_ID_", expected: "_Client_ID_", namer: gorm.TheNamingStrategy.Column},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
result := c.namer(c.name)
if result != c.expected {
t.Errorf("error in naming strategy. expected: %v got :%v\n", c.expected, result)
}
})
}
}
func CustomNamer(name string) string {
// users can set their custom namer and use `Smap` to cache result
gorm.AddNamingStrategy(&gorm.NamingStrategy{
Column: func(name string) string {
// set `smap` public access and users can use it to cache
if v := gorm.Smap.Get(name); v != "" {
return v
}
const (
lower = false
//lower = false
upper = true
)
@ -93,6 +64,28 @@ func CustomNamer(name string) string {
gorm.Smap.Set(name, s)
return s
},
})
// test
cases := []struct {
name string
namer gorm.Namer
expected string
}{
{name: "Client0ID", expected: "client0ID", namer: gorm.TheNamingStrategy.Column},
{name: "_Client_ID_", expected: "_Client_ID_", namer: gorm.TheNamingStrategy.Column},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
result := c.namer(c.name)
if result != c.expected {
t.Errorf("error in naming strategy. expected: %v got :%v\n", c.expected, result)
}
})
}
}
func TestNamingStrategy(t *testing.T) {