Merge develop

This commit is contained in:
Ming Deng 2021-02-12 22:02:22 +08:00
commit 9da720d8ba
39 changed files with 800 additions and 1923 deletions

View File

@ -1,4 +1,6 @@
# developing # developing
- Error codes definition of cache module. [4493](https://github.com/beego/beego/pull/4493)
- Remove generateCommentRoute http hook. Using `bee generate routers` commands instead.[4486](https://github.com/beego/beego/pull/4486) [bee PR 762](https://github.com/beego/bee/pull/762)
- Fix: /abc.html/aaa match /abc/aaa. [4459](https://github.com/beego/beego/pull/4459) - Fix: /abc.html/aaa match /abc/aaa. [4459](https://github.com/beego/beego/pull/4459)
- ORM mock. [4407](https://github.com/beego/beego/pull/4407) - ORM mock. [4407](https://github.com/beego/beego/pull/4407)
- Add sonar check and ignore test. [4432](https://github.com/beego/beego/pull/4432) [4433](https://github.com/beego/beego/pull/4433) - Add sonar check and ignore test. [4432](https://github.com/beego/beego/pull/4432) [4433](https://github.com/beego/beego/pull/4433)
@ -25,3 +27,5 @@
## Fix Sonar ## Fix Sonar
- [4473](https://github.com/beego/beego/pull/4473) - [4473](https://github.com/beego/beego/pull/4473)
- [4474](https://github.com/beego/beego/pull/4474)
- [4479](https://github.com/beego/beego/pull/4479)

View File

@ -15,6 +15,8 @@ Beego is compos of four parts:
3. Client: including ORM module, httplib module, cache module; 3. Client: including ORM module, httplib module, cache module;
4. Server: including web module. We will support gRPC in the future; 4. Server: including web module. We will support gRPC in the future;
**Please use RELEASE version, or master branch which contains the latest bug fix**
## Quick Start ## Quick Start
[Officail website](http://beego.me) [Officail website](http://beego.me)

View File

@ -19,6 +19,8 @@ import (
"sync" "sync"
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert"
) )
const ( const (
@ -53,147 +55,95 @@ func TestCacheIncr(t *testing.T) {
func TestCache(t *testing.T) { func TestCache(t *testing.T) {
bm, err := NewCache("memory", `{"interval":20}`) bm, err := NewCache("memory", `{"interval":20}`)
if err != nil {
t.Error(initError)
}
timeoutDuration := 10 * time.Second
if err = bm.Put("astaxie", 1, timeoutDuration); err != nil {
t.Error(setError, err)
}
if !bm.IsExist("astaxie") {
t.Error(checkError)
}
if v := bm.Get("astaxie"); v.(int) != 1 { assert.Nil(t, err)
t.Error(getError)
}
time.Sleep(30 * time.Second) timeoutDuration := 5 * time.Second
err = bm.Put("astaxie", 1, timeoutDuration)
assert.Nil(t, err)
if bm.IsExist("astaxie") { assert.True(t, bm.IsExist("astaxie"))
t.Error(checkError)
}
if err = bm.Put("astaxie", 1, timeoutDuration); err != nil { assert.Equal(t, 1, bm.Get("astaxie"))
t.Error(setError, err)
}
if err = bm.Incr("astaxie"); err != nil { time.Sleep(10 * time.Second)
t.Error("Incr Error", err)
}
if v := bm.Get("astaxie"); v.(int) != 2 { assert.False(t, bm.IsExist("astaxie"))
t.Error(getError)
}
if err = bm.Decr("astaxie"); err != nil { err = bm.Put("astaxie", 1, timeoutDuration)
t.Error("Decr Error", err) assert.Nil(t, err)
}
if v := bm.Get("astaxie"); v.(int) != 1 { err = bm.Incr("astaxie")
t.Error(getError) assert.Nil(t, err)
}
bm.Delete("astaxie")
if bm.IsExist("astaxie") {
t.Error("delete err")
}
// test GetMulti assert.Equal(t, 2, bm.Get("astaxie"))
if err = bm.Put("astaxie", "author", timeoutDuration); err != nil {
t.Error(setError, err)
}
if !bm.IsExist("astaxie") {
t.Error(checkError)
}
if v := bm.Get("astaxie"); v.(string) != "author" {
t.Error(getError)
}
if err = bm.Put("astaxie1", "author1", timeoutDuration); err != nil { assert.Nil(t, bm.Decr("astaxie"))
t.Error(setError, err)
} assert.Equal(t, 1, bm.Get("astaxie"))
if !bm.IsExist("astaxie1") {
t.Error(checkError) assert.Nil(t, bm.Delete("astaxie"))
}
assert.False(t, bm.IsExist("astaxie"))
assert.Nil(t, bm.Put("astaxie", "author", timeoutDuration))
assert.True(t, bm.IsExist("astaxie"))
assert.Equal(t, "author", bm.Get("astaxie"))
assert.Nil(t, bm.Put("astaxie1", "author1", timeoutDuration))
assert.True(t, bm.IsExist("astaxie1"))
vv := bm.GetMulti([]string{"astaxie", "astaxie1"}) vv := bm.GetMulti([]string{"astaxie", "astaxie1"})
if len(vv) != 2 {
t.Error(getMultiError) assert.Equal(t, 2, len(vv))
}
if vv[0].(string) != "author" {
t.Error(getMultiError) assert.Equal(t, "author", vv[0])
}
if vv[1].(string) != "author1" { assert.Equal(t, "author1", vv[1])
t.Error(getMultiError)
}
} }
func TestFileCache(t *testing.T) { func TestFileCache(t *testing.T) {
bm, err := NewCache("file", `{"CachePath":"cache","FileSuffix":".bin","DirectoryLevel":"2","EmbedExpiry":"0"}`) bm, err := NewCache("file", `{"CachePath":"cache","FileSuffix":".bin","DirectoryLevel":"2","EmbedExpiry":"0"}`)
if err != nil {
t.Error(initError)
}
timeoutDuration := 10 * time.Second
if err = bm.Put("astaxie", 1, timeoutDuration); err != nil {
t.Error(setError, err)
}
if !bm.IsExist("astaxie") {
t.Error(checkError)
}
if v := bm.Get("astaxie"); v.(int) != 1 { assert.Nil(t, err)
t.Error(getError) timeoutDuration := 5 * time.Second
}
if err = bm.Incr("astaxie"); err != nil { assert.Nil(t, bm.Put("astaxie", 1, timeoutDuration))
t.Error("Incr Error", err)
}
if v := bm.Get("astaxie"); v.(int) != 2 { assert.True(t, bm.IsExist("astaxie"))
t.Error(getError)
}
if err = bm.Decr("astaxie"); err != nil { assert.Equal(t, 1, bm.Get("astaxie"))
t.Error("Decr Error", err)
}
if v := bm.Get("astaxie"); v.(int) != 1 { assert.Nil(t, bm.Incr("astaxie"))
t.Error(getError)
}
bm.Delete("astaxie")
if bm.IsExist("astaxie") {
t.Error("delete err")
}
// test string assert.Equal(t, 2, bm.Get("astaxie"))
if err = bm.Put("astaxie", "author", timeoutDuration); err != nil {
t.Error(setError, err)
}
if !bm.IsExist("astaxie") {
t.Error(checkError)
}
if v := bm.Get("astaxie"); v.(string) != "author" {
t.Error(getError)
}
// test GetMulti assert.Nil(t, bm.Decr("astaxie"))
if err = bm.Put("astaxie1", "author1", timeoutDuration); err != nil {
t.Error(setError, err) assert.Equal(t, 1, bm.Get("astaxie"))
} assert.Nil(t, bm.Delete("astaxie"))
if !bm.IsExist("astaxie1") {
t.Error(checkError) assert.False(t, bm.IsExist("astaxie"))
}
assert.Nil(t, bm.Put("astaxie", "author", timeoutDuration))
assert.True(t, bm.IsExist("astaxie"))
assert.Equal(t, "author", bm.Get("astaxie"))
assert.Nil(t, bm.Put("astaxie1", "author1", timeoutDuration))
assert.True(t, bm.IsExist("astaxie1"))
vv := bm.GetMulti([]string{"astaxie", "astaxie1"}) vv := bm.GetMulti([]string{"astaxie", "astaxie1"})
if len(vv) != 2 {
t.Error(getMultiError)
}
if vv[0].(string) != "author" {
t.Error(getMultiError)
}
if vv[1].(string) != "author1" {
t.Error(getMultiError)
}
os.RemoveAll("cache") assert.Equal(t, 2, len(vv))
assert.Equal(t, "author", vv[0])
assert.Equal(t, "author1", vv[1])
assert.Nil(t, os.RemoveAll("cache"))
} }

View File

@ -21,6 +21,8 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert"
"github.com/beego/beego/v2/adapter/cache" "github.com/beego/beego/v2/adapter/cache"
) )
@ -40,83 +42,52 @@ func TestMemcacheCache(t *testing.T) {
} }
bm, err := cache.NewCache("memcache", fmt.Sprintf(`{"conn": "%s"}`, addr)) bm, err := cache.NewCache("memcache", fmt.Sprintf(`{"conn": "%s"}`, addr))
if err != nil { assert.Nil(t, err)
t.Error(initError) timeoutDuration := 5 * time.Second
}
timeoutDuration := 10 * time.Second assert.Nil(t, bm.Put("astaxie", "1", timeoutDuration))
if err = bm.Put("astaxie", "1", timeoutDuration); err != nil {
t.Error(setError, err) assert.True(t, bm.IsExist("astaxie"))
}
if !bm.IsExist("astaxie") {
t.Error(checkError)
}
time.Sleep(11 * time.Second) time.Sleep(11 * time.Second)
if bm.IsExist("astaxie") { assert.False(t, bm.IsExist("astaxie"))
t.Error(checkError)
}
if err = bm.Put("astaxie", "1", timeoutDuration); err != nil {
t.Error(setError, err)
}
if v, err := strconv.Atoi(string(bm.Get("astaxie").([]byte))); err != nil || v != 1 { assert.Nil(t, bm.Put("astaxie", "1", timeoutDuration))
t.Error(getError) v, err := strconv.Atoi(string(bm.Get("astaxie").([]byte)))
} assert.Nil(t, err)
assert.Equal(t, 1, v)
if err = bm.Incr("astaxie"); err != nil { assert.Nil(t, bm.Incr("astaxie"))
t.Error("Incr Error", err)
}
if v, err := strconv.Atoi(string(bm.Get("astaxie").([]byte))); err != nil || v != 2 { v, err = strconv.Atoi(string(bm.Get("astaxie").([]byte)))
t.Error(getError) assert.Nil(t, err)
} assert.Equal(t, 2, v)
if err = bm.Decr("astaxie"); err != nil { assert.Nil(t, bm.Decr("astaxie"))
t.Error("Decr Error", err)
}
if v, err := strconv.Atoi(string(bm.Get("astaxie").([]byte))); err != nil || v != 1 { v, err = strconv.Atoi(string(bm.Get("astaxie").([]byte)))
t.Error(getError) assert.Nil(t, err)
} assert.Equal(t, 1, v)
bm.Delete("astaxie")
if bm.IsExist("astaxie") {
t.Error("delete err")
}
// test string assert.Nil(t, bm.Delete("astaxie"))
if err = bm.Put("astaxie", "author", timeoutDuration); err != nil {
t.Error(setError, err)
}
if !bm.IsExist("astaxie") {
t.Error(checkError)
}
if v := bm.Get("astaxie").([]byte); string(v) != "author" { assert.False(t, bm.IsExist("astaxie"))
t.Error(getError)
}
// test GetMulti assert.Nil(t, bm.Put("astaxie", "author", timeoutDuration))
if err = bm.Put("astaxie1", "author1", timeoutDuration); err != nil {
t.Error(setError, err) assert.True(t, bm.IsExist("astaxie"))
}
if !bm.IsExist("astaxie1") { assert.Equal(t, []byte("author"), bm.Get("astaxie"))
t.Error(checkError)
} assert.Nil(t, bm.Put("astaxie1", "author1", timeoutDuration))
assert.True(t, bm.IsExist("astaxie1"))
vv := bm.GetMulti([]string{"astaxie", "astaxie1"}) vv := bm.GetMulti([]string{"astaxie", "astaxie1"})
if len(vv) != 2 { assert.Equal(t, 2, len(vv))
t.Error(getMultiError) assert.Equal(t, []byte("author"), vv[0])
} assert.Equal(t, []byte("author1"), vv[1])
if string(vv[0].([]byte)) != "author" && string(vv[0].([]byte)) != "author1" {
t.Error(getMultiError)
}
if string(vv[1].([]byte)) != "author1" && string(vv[1].([]byte)) != "author" {
t.Error(getMultiError)
}
// test clear all assert.Nil(t, bm.ClearAll())
if err = bm.ClearAll(); err != nil {
t.Error("clear all err")
}
} }

View File

@ -21,6 +21,7 @@ import (
"time" "time"
"github.com/gomodule/redigo/redis" "github.com/gomodule/redigo/redis"
"github.com/stretchr/testify/assert"
"github.com/beego/beego/v2/adapter/cache" "github.com/beego/beego/v2/adapter/cache"
) )
@ -40,88 +41,69 @@ func TestRedisCache(t *testing.T) {
} }
bm, err := cache.NewCache("redis", fmt.Sprintf(`{"conn": "%s"}`, redisAddr)) bm, err := cache.NewCache("redis", fmt.Sprintf(`{"conn": "%s"}`, redisAddr))
if err != nil { assert.Nil(t, err)
t.Error(initError) timeoutDuration := 5 * time.Second
}
timeoutDuration := 10 * time.Second
if err = bm.Put("astaxie", 1, timeoutDuration); err != nil {
t.Error(setError, err)
}
if !bm.IsExist("astaxie") {
t.Error(checkError)
}
time.Sleep(11 * time.Second) assert.Nil(t, bm.Put("astaxie", 1, timeoutDuration))
if bm.IsExist("astaxie") { assert.True(t, bm.IsExist("astaxie"))
t.Error(checkError)
}
if err = bm.Put("astaxie", 1, timeoutDuration); err != nil {
t.Error(setError, err)
}
if v, _ := redis.Int(bm.Get("astaxie"), err); v != 1 { time.Sleep(7 * time.Second)
t.Error(getError)
}
if err = bm.Incr("astaxie"); err != nil { assert.False(t, bm.IsExist("astaxie"))
t.Error("Incr Error", err)
}
if v, _ := redis.Int(bm.Get("astaxie"), err); v != 2 { assert.Nil(t, bm.Put("astaxie", 1, timeoutDuration))
t.Error(getError)
}
if err = bm.Decr("astaxie"); err != nil { v, err := redis.Int(bm.Get("astaxie"), err)
t.Error("Decr Error", err) assert.Nil(t, err)
} assert.Equal(t, 1, v)
if v, _ := redis.Int(bm.Get("astaxie"), err); v != 1 { assert.Nil(t, bm.Incr("astaxie"))
t.Error(getError)
}
bm.Delete("astaxie")
if bm.IsExist("astaxie") {
t.Error("delete err")
}
// test string v, err = redis.Int(bm.Get("astaxie"), err)
if err = bm.Put("astaxie", "author", timeoutDuration); err != nil { assert.Nil(t, err)
t.Error(setError, err) assert.Equal(t, 2, v)
}
if !bm.IsExist("astaxie") {
t.Error(checkError)
}
if v, _ := redis.String(bm.Get("astaxie"), err); v != "author" { assert.Nil(t, bm.Decr("astaxie"))
t.Error(getError)
}
// test GetMulti v, err = redis.Int(bm.Get("astaxie"), err)
if err = bm.Put("astaxie1", "author1", timeoutDuration); err != nil { assert.Nil(t, err)
t.Error(setError, err) assert.Equal(t, 1, v)
}
if !bm.IsExist("astaxie1") { assert.Nil(t, bm.Delete("astaxie"))
t.Error(checkError)
} assert.False(t, bm.IsExist("astaxie"))
assert.Nil(t, bm.Put("astaxie", "author", timeoutDuration))
assert.True(t, bm.IsExist("astaxie"))
vs, err := redis.String(bm.Get("astaxie"), err)
assert.Nil(t, err)
assert.Equal(t, "author", vs)
assert.Nil(t, bm.Put("astaxie1", "author1", timeoutDuration))
assert.True(t, bm.IsExist("astaxie1"))
vv := bm.GetMulti([]string{"astaxie", "astaxie1"}) vv := bm.GetMulti([]string{"astaxie", "astaxie1"})
if len(vv) != 2 {
t.Error(getMultiError)
}
if v, _ := redis.String(vv[0], nil); v != "author" {
t.Error(getMultiError)
}
if v, _ := redis.String(vv[1], nil); v != "author1" {
t.Error(getMultiError)
}
assert.Equal(t, 2, len(vv))
vs, err = redis.String(vv[0], nil)
assert.Nil(t, err)
assert.Equal(t, "author", vs)
vs, err = redis.String(vv[1], nil)
assert.Nil(t, err)
assert.Equal(t, "author1", vs)
assert.Nil(t, bm.ClearAll())
// test clear all // test clear all
if err = bm.ClearAll(); err != nil {
t.Error("clear all err")
}
} }
func TestCache_Scan(t *testing.T) { func TestCacheScan(t *testing.T) {
timeoutDuration := 10 * time.Second timeoutDuration := 10 * time.Second
// init // init
bm, err := cache.NewCache("redis", `{"conn": "127.0.0.1:6379"}`) bm, err := cache.NewCache("redis", `{"conn": "127.0.0.1:6379"}`)

View File

@ -7,6 +7,8 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert"
"github.com/beego/beego/v2/adapter/cache" "github.com/beego/beego/v2/adapter/cache"
) )
@ -25,95 +27,59 @@ func TestSsdbcacheCache(t *testing.T) {
} }
ssdb, err := cache.NewCache("ssdb", fmt.Sprintf(`{"conn": "%s"}`, ssdbAddr)) ssdb, err := cache.NewCache("ssdb", fmt.Sprintf(`{"conn": "%s"}`, ssdbAddr))
if err != nil {
t.Error(initError)
}
assert.Nil(t, err)
assert.False(t, ssdb.IsExist("ssdb"))
// test put and exist // test put and exist
if ssdb.IsExist("ssdb") { timeoutDuration := 3 * time.Second
t.Error(checkError)
}
timeoutDuration := 10 * time.Second
// timeoutDuration := -10*time.Second if timeoutDuration is negtive,it means permanent // timeoutDuration := -10*time.Second if timeoutDuration is negtive,it means permanent
if err = ssdb.Put("ssdb", "ssdb", timeoutDuration); err != nil { assert.Nil(t, ssdb.Put("ssdb", "ssdb", timeoutDuration))
t.Error(setError, err) assert.True(t, ssdb.IsExist("ssdb"))
}
if !ssdb.IsExist("ssdb") {
t.Error(checkError)
}
// Get test done assert.Nil(t, ssdb.Put("ssdb", "ssdb", timeoutDuration))
if err = ssdb.Put("ssdb", "ssdb", timeoutDuration); err != nil {
t.Error(setError, err)
}
if v := ssdb.Get("ssdb"); v != "ssdb" { assert.Equal(t, "ssdb", ssdb.Get("ssdb"))
t.Error("get Error")
}
// inc/dec test done // inc/dec test done
if err = ssdb.Put("ssdb", "2", timeoutDuration); err != nil { assert.Nil(t, ssdb.Put("ssdb", "2", timeoutDuration))
t.Error(setError, err)
}
if err = ssdb.Incr("ssdb"); err != nil {
t.Error("incr Error", err)
}
if v, err := strconv.Atoi(ssdb.Get("ssdb").(string)); err != nil || v != 3 { assert.Nil(t, ssdb.Incr("ssdb"))
t.Error(getError)
}
if err = ssdb.Decr("ssdb"); err != nil { v, err := strconv.Atoi(ssdb.Get("ssdb").(string))
t.Error("decr error") assert.Nil(t, err)
} assert.Equal(t, 3, v)
assert.Nil(t, ssdb.Decr("ssdb"))
assert.Nil(t, ssdb.Put("ssdb", "3", timeoutDuration))
// test del // test del
if err = ssdb.Put("ssdb", "3", timeoutDuration); err != nil { v, err = strconv.Atoi(ssdb.Get("ssdb").(string))
t.Error(setError, err) assert.Nil(t, err)
} assert.Equal(t, 3, v)
if v, err := strconv.Atoi(ssdb.Get("ssdb").(string)); err != nil || v != 3 {
t.Error(getError) assert.Nil(t, ssdb.Delete("ssdb"))
} assert.False(t, ssdb.IsExist("ssdb"))
if err := ssdb.Delete("ssdb"); err == nil {
if ssdb.IsExist("ssdb") {
t.Error("delete err")
}
}
// test string // test string
if err = ssdb.Put("ssdb", "ssdb", -10*time.Second); err != nil { assert.Nil(t, ssdb.Put("ssdb", "ssdb", -10*time.Second))
t.Error(setError, err)
} assert.True(t, ssdb.IsExist("ssdb"))
if !ssdb.IsExist("ssdb") { assert.Equal(t, "ssdb", ssdb.Get("ssdb"))
t.Error(checkError)
}
if v := ssdb.Get("ssdb").(string); v != "ssdb" {
t.Error(getError)
}
// test GetMulti done // test GetMulti done
if err = ssdb.Put("ssdb1", "ssdb1", -10*time.Second); err != nil { assert.Nil(t, ssdb.Put("ssdb1", "ssdb1", -10*time.Second))
t.Error(setError, err) assert.True(t, ssdb.IsExist("ssdb1") )
}
if !ssdb.IsExist("ssdb1") {
t.Error(checkError)
}
vv := ssdb.GetMulti([]string{"ssdb", "ssdb1"})
if len(vv) != 2 {
t.Error(getMultiError)
}
if vv[0].(string) != "ssdb" {
t.Error(getMultiError)
}
if vv[1].(string) != "ssdb1" {
t.Error(getMultiError)
}
vv := ssdb.GetMulti([]string{"ssdb", "ssdb1"})
assert.Equal(t, 2, len(vv))
assert.Equal(t, "ssdb", vv[0])
assert.Equal(t, "ssdb1", vv[1])
assert.Nil(t, ssdb.ClearAll())
assert.False(t, ssdb.IsExist("ssdb"))
assert.False(t, ssdb.IsExist("ssdb1"))
// test clear all done // test clear all done
if err = ssdb.ClearAll(); err != nil {
t.Error("clear all err")
}
if ssdb.IsExist("ssdb") || ssdb.IsExist("ssdb1") {
t.Error(checkError)
}
} }

View File

@ -18,6 +18,8 @@ import (
"fmt" "fmt"
"os" "os"
"testing" "testing"
"github.com/stretchr/testify/assert"
) )
func TestJsonStartsWithArray(t *testing.T) { func TestJsonStartsWithArray(t *testing.T) {
@ -169,56 +171,39 @@ func TestJson(t *testing.T) {
default: default:
value, err = jsonconf.DIY(k) value, err = jsonconf.DIY(k)
} }
if err != nil {
t.Fatalf("get key %q value fatal,%v err %s", k, v, err)
} else if fmt.Sprintf("%v", v) != fmt.Sprintf("%v", value) {
t.Fatalf("get key %q value, want %v got %v .", k, v, value)
}
} assert.Nil(t, err)
if err = jsonconf.Set("name", "astaxie"); err != nil { assert.Equal(t, fmt.Sprintf("%v", v), fmt.Sprintf("%v", value))
t.Fatal(err)
}
if jsonconf.String("name") != "astaxie" {
t.Fatal("get name error")
} }
if db, err := jsonconf.DIY("database"); err != nil { assert.Nil(t, jsonconf.Set("name", "astaxie"))
t.Fatal(err)
} else if m, ok := db.(map[string]interface{}); !ok {
t.Log(db)
t.Fatal("db not map[string]interface{}")
} else {
if m["host"].(string) != "host" {
t.Fatal("get host err")
}
}
if _, err := jsonconf.Int("unknown"); err == nil { assert.Equal(t, "astaxie", jsonconf.String("name"))
t.Error("unknown keys should return an error when expecting an Int")
}
if _, err := jsonconf.Int64("unknown"); err == nil { db, err := jsonconf.DIY("database")
t.Error("unknown keys should return an error when expecting an Int64") assert.Nil(t, err)
}
if _, err := jsonconf.Float("unknown"); err == nil { m, ok := db.(map[string]interface{})
t.Error("unknown keys should return an error when expecting a Float") assert.True(t, ok)
} assert.Equal(t,"host" , m["host"])
if _, err := jsonconf.DIY("unknown"); err == nil { _, err = jsonconf.Int("unknown")
t.Error("unknown keys should return an error when expecting an interface{}") assert.NotNil(t, err)
}
if val := jsonconf.String("unknown"); val != "" { _, err = jsonconf.Int64("unknown")
t.Error("unknown keys should return an empty string when expecting a String") assert.NotNil(t, err)
}
if _, err := jsonconf.Bool("unknown"); err == nil { _, err = jsonconf.Float("unknown")
t.Error("unknown keys should return an error when expecting a Bool") assert.NotNil(t, err)
}
if !jsonconf.DefaultBool("unknown", true) { _, err = jsonconf.DIY("unknown")
t.Error("unknown keys with default value wrong") assert.NotNil(t, err)
}
val := jsonconf.String("unknown")
assert.Equal(t, "", val)
_, err = jsonconf.Bool("unknown")
assert.NotNil(t, err)
assert.True(t, jsonconf.DefaultBool("unknown", true))
} }

View File

@ -20,7 +20,7 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func TestMethodParam_String(t *testing.T) { func TestMethodParamString(t *testing.T) {
method := New("myName", IsRequired, InHeader, Default("abc")) method := New("myName", IsRequired, InHeader, Default("abc"))
s := method.String() s := method.String()
assert.Equal(t, `param.New("myName", param.IsRequired, param.InHeader, param.Default("abc"))`, s) assert.Equal(t, `param.New("myName", param.IsRequired, param.InHeader, param.Default("abc"))`, s)

View File

@ -25,8 +25,11 @@ import (
"time" "time"
) )
const getUrl = "http://httpbin.org/get"
const ipUrl = "http://httpbin.org/ip"
func TestResponse(t *testing.T) { func TestResponse(t *testing.T) {
req := Get("http://httpbin.org/get") req := Get(getUrl)
resp, err := req.Response() resp, err := req.Response()
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@ -63,7 +66,8 @@ func TestDoRequest(t *testing.T) {
} }
func TestGet(t *testing.T) { func TestGet(t *testing.T) {
req := Get("http://httpbin.org/get")
req := Get(getUrl)
b, err := req.Bytes() b, err := req.Bytes()
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@ -205,7 +209,7 @@ func TestWithSetting(t *testing.T) {
setting.ReadWriteTimeout = 5 * time.Second setting.ReadWriteTimeout = 5 * time.Second
SetDefaultSetting(setting) SetDefaultSetting(setting)
str, err := Get("http://httpbin.org/get").String() str, err := Get(getUrl).String()
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -218,7 +222,8 @@ func TestWithSetting(t *testing.T) {
} }
func TestToJson(t *testing.T) { func TestToJson(t *testing.T) {
req := Get("http://httpbin.org/ip")
req := Get(ipUrl)
resp, err := req.Response() resp, err := req.Response()
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@ -249,7 +254,7 @@ func TestToJson(t *testing.T) {
func TestToFile(t *testing.T) { func TestToFile(t *testing.T) {
f := "beego_testfile" f := "beego_testfile"
req := Get("http://httpbin.org/ip") req := Get(ipUrl)
err := req.ToFile(f) err := req.ToFile(f)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@ -263,7 +268,7 @@ func TestToFile(t *testing.T) {
func TestToFileDir(t *testing.T) { func TestToFileDir(t *testing.T) {
f := "./files/beego_testfile" f := "./files/beego_testfile"
req := Get("http://httpbin.org/ip") req := Get(ipUrl)
err := req.ToFile(f) err := req.ToFile(f)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)

View File

@ -18,7 +18,7 @@ import (
"testing" "testing"
) )
func TestBeeLogger_Info(t *testing.T) { func TestBeeLoggerInfo(t *testing.T) {
log := NewLogger(1000) log := NewLogger(1000)
log.SetLogger("file", `{"net":"tcp","addr":":7020"}`) log.SetLogger("file", `{"net":"tcp","addr":":7020"}`)
} }

View File

@ -15,6 +15,7 @@
package metric package metric
import ( import (
"fmt"
"net/http" "net/http"
"net/url" "net/url"
"testing" "testing"
@ -26,7 +27,9 @@ import (
) )
func TestPrometheusMiddleWare(t *testing.T) { func TestPrometheusMiddleWare(t *testing.T) {
middleware := PrometheusMiddleWare(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) middleware := PrometheusMiddleWare(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
fmt.Print("you are coming")
}))
writer := &context.Response{} writer := &context.Response{}
request := &http.Request{ request := &http.Request{
URL: &url.URL{ URL: &url.URL{

View File

@ -21,14 +21,16 @@ import (
type baseQuerySetter struct { type baseQuerySetter struct {
} }
const shouldNotInvoke = "you should not invoke this method."
func (b *baseQuerySetter) ForceIndex(indexes ...string) orm.QuerySeter { func (b *baseQuerySetter) ForceIndex(indexes ...string) orm.QuerySeter {
panic("you should not invoke this method.") panic(shouldNotInvoke)
} }
func (b *baseQuerySetter) UseIndex(indexes ...string) orm.QuerySeter { func (b *baseQuerySetter) UseIndex(indexes ...string) orm.QuerySeter {
panic("you should not invoke this method.") panic(shouldNotInvoke)
} }
func (b *baseQuerySetter) IgnoreIndex(indexes ...string) orm.QuerySeter { func (b *baseQuerySetter) IgnoreIndex(indexes ...string) orm.QuerySeter {
panic("you should not invoke this method.") panic(shouldNotInvoke)
} }

View File

@ -16,6 +16,8 @@ package orm
import ( import (
"testing" "testing"
"github.com/stretchr/testify/assert"
) )
func TestCamelString(t *testing.T) { func TestCamelString(t *testing.T) {
@ -29,9 +31,7 @@ func TestCamelString(t *testing.T) {
for _, v := range snake { for _, v := range snake {
res := camelString(v) res := camelString(v)
if res != answer[v] { assert.Equal(t, answer[v], res)
t.Error("Unit Test Fail:", v, res, answer[v])
}
} }
} }
@ -46,9 +46,7 @@ func TestSnakeString(t *testing.T) {
for _, v := range camel { for _, v := range camel {
res := snakeString(v) res := snakeString(v)
if res != answer[v] { assert.Equal(t, answer[v], res)
t.Error("Unit Test Fail:", v, res, answer[v])
}
} }
} }
@ -63,8 +61,6 @@ func TestSnakeStringWithAcronym(t *testing.T) {
for _, v := range camel { for _, v := range camel {
res := snakeStringWithAcronym(v) res := snakeStringWithAcronym(v)
if res != answer[v] { assert.Equal(t, answer[v], res)
t.Error("Unit Test Fail:", v, res, answer[v])
}
} }
} }

View File

@ -26,6 +26,11 @@ import (
"github.com/beego/beego/v2/adapter/plugins/auth" "github.com/beego/beego/v2/adapter/plugins/auth"
) )
const (
authCfg = "authz_model.conf"
authCsv = "authz_policy.csv"
)
func testRequest(t *testing.T, handler *beego.ControllerRegister, user string, path string, method string, code int) { func testRequest(t *testing.T, handler *beego.ControllerRegister, user string, path string, method string, code int) {
r, _ := http.NewRequest(method, path, nil) r, _ := http.NewRequest(method, path, nil)
r.SetBasicAuth(user, "123") r.SetBasicAuth(user, "123")
@ -40,70 +45,79 @@ func testRequest(t *testing.T, handler *beego.ControllerRegister, user string, p
func TestBasic(t *testing.T) { func TestBasic(t *testing.T) {
handler := beego.NewControllerRegister() handler := beego.NewControllerRegister()
handler.InsertFilter("*", beego.BeforeRouter, auth.Basic("alice", "123")) _ = handler.InsertFilter("*", beego.BeforeRouter, auth.Basic("alice", "123"))
handler.InsertFilter("*", beego.BeforeRouter, NewAuthorizer(casbin.NewEnforcer("authz_model.conf", "authz_policy.csv")))
_ = handler.InsertFilter("*", beego.BeforeRouter, NewAuthorizer(casbin.NewEnforcer(authCfg, authCsv)))
handler.Any("*", func(ctx *context.Context) { handler.Any("*", func(ctx *context.Context) {
ctx.Output.SetStatus(200) ctx.Output.SetStatus(200)
}) })
testRequest(t, handler, "alice", "/dataset1/resource1", "GET", 200) const d1r1 = "/dataset1/resource1"
testRequest(t, handler, "alice", "/dataset1/resource1", "POST", 200) testRequest(t, handler, "alice", d1r1, "GET", 200)
testRequest(t, handler, "alice", "/dataset1/resource2", "GET", 200) testRequest(t, handler, "alice", d1r1, "POST", 200)
testRequest(t, handler, "alice", "/dataset1/resource2", "POST", 403) const d1r2 = "/dataset1/resource2"
testRequest(t, handler, "alice", d1r2, "GET", 200)
testRequest(t, handler, "alice", d1r2, "POST", 403)
} }
func TestPathWildcard(t *testing.T) { func TestPathWildcard(t *testing.T) {
handler := beego.NewControllerRegister() handler := beego.NewControllerRegister()
handler.InsertFilter("*", beego.BeforeRouter, auth.Basic("bob", "123")) _ = handler.InsertFilter("*", beego.BeforeRouter, auth.Basic("bob", "123"))
handler.InsertFilter("*", beego.BeforeRouter, NewAuthorizer(casbin.NewEnforcer("authz_model.conf", "authz_policy.csv"))) _ = handler.InsertFilter("*", beego.BeforeRouter, NewAuthorizer(casbin.NewEnforcer(authCfg, authCsv)))
handler.Any("*", func(ctx *context.Context) { handler.Any("*", func(ctx *context.Context) {
ctx.Output.SetStatus(200) ctx.Output.SetStatus(200)
}) })
testRequest(t, handler, "bob", "/dataset2/resource1", "GET", 200) const d2r1 = "/dataset2/resource1"
testRequest(t, handler, "bob", "/dataset2/resource1", "POST", 200) testRequest(t, handler, "bob", d2r1, "GET", 200)
testRequest(t, handler, "bob", "/dataset2/resource1", "DELETE", 200) testRequest(t, handler, "bob", d2r1, "POST", 200)
testRequest(t, handler, "bob", "/dataset2/resource2", "GET", 200) testRequest(t, handler, "bob", d2r1, "DELETE", 200)
testRequest(t, handler, "bob", "/dataset2/resource2", "POST", 403) const d2r2 = "/dataset2/resource2"
testRequest(t, handler, "bob", "/dataset2/resource2", "DELETE", 403) testRequest(t, handler, "bob", d2r2, "GET", 200)
testRequest(t, handler, "bob", d2r2, "POST", 403)
testRequest(t, handler, "bob", d2r2, "DELETE", 403)
testRequest(t, handler, "bob", "/dataset2/folder1/item1", "GET", 403) const item1 = "/dataset2/folder1/item1"
testRequest(t, handler, "bob", "/dataset2/folder1/item1", "POST", 200) testRequest(t, handler, "bob", item1, "GET", 403)
testRequest(t, handler, "bob", "/dataset2/folder1/item1", "DELETE", 403) testRequest(t, handler, "bob", item1, "POST", 200)
testRequest(t, handler, "bob", "/dataset2/folder1/item2", "GET", 403) testRequest(t, handler, "bob", item1, "DELETE", 403)
testRequest(t, handler, "bob", "/dataset2/folder1/item2", "POST", 200) const item2 = "/dataset2/folder1/item2"
testRequest(t, handler, "bob", "/dataset2/folder1/item2", "DELETE", 403) testRequest(t, handler, "bob", item2, "GET", 403)
testRequest(t, handler, "bob", item2, "POST", 200)
testRequest(t, handler, "bob", item2, "DELETE", 403)
} }
func TestRBAC(t *testing.T) { func TestRBAC(t *testing.T) {
handler := beego.NewControllerRegister() handler := beego.NewControllerRegister()
handler.InsertFilter("*", beego.BeforeRouter, auth.Basic("cathy", "123")) _ = handler.InsertFilter("*", beego.BeforeRouter, auth.Basic("cathy", "123"))
e := casbin.NewEnforcer("authz_model.conf", "authz_policy.csv") e := casbin.NewEnforcer(authCfg, authCsv)
handler.InsertFilter("*", beego.BeforeRouter, NewAuthorizer(e)) _ = handler.InsertFilter("*", beego.BeforeRouter, NewAuthorizer(e))
handler.Any("*", func(ctx *context.Context) { handler.Any("*", func(ctx *context.Context) {
ctx.Output.SetStatus(200) ctx.Output.SetStatus(200)
}) })
// cathy can access all /dataset1/* resources via all methods because it has the dataset1_admin role. // cathy can access all /dataset1/* resources via all methods because it has the dataset1_admin role.
testRequest(t, handler, "cathy", "/dataset1/item", "GET", 200) const dataSet1 = "/dataset1/item"
testRequest(t, handler, "cathy", "/dataset1/item", "POST", 200) testRequest(t, handler, "cathy", dataSet1, "GET", 200)
testRequest(t, handler, "cathy", "/dataset1/item", "DELETE", 200) testRequest(t, handler, "cathy", dataSet1, "POST", 200)
testRequest(t, handler, "cathy", "/dataset2/item", "GET", 403) testRequest(t, handler, "cathy", dataSet1, "DELETE", 200)
testRequest(t, handler, "cathy", "/dataset2/item", "POST", 403) const dataSet2 = "/dataset2/item"
testRequest(t, handler, "cathy", "/dataset2/item", "DELETE", 403) testRequest(t, handler, "cathy", dataSet2, "GET", 403)
testRequest(t, handler, "cathy", dataSet2, "POST", 403)
testRequest(t, handler, "cathy", dataSet2, "DELETE", 403)
// delete all roles on user cathy, so cathy cannot access any resources now. // delete all roles on user cathy, so cathy cannot access any resources now.
e.DeleteRolesForUser("cathy") e.DeleteRolesForUser("cathy")
testRequest(t, handler, "cathy", "/dataset1/item", "GET", 403) testRequest(t, handler, "cathy", dataSet1, "GET", 403)
testRequest(t, handler, "cathy", "/dataset1/item", "POST", 403) testRequest(t, handler, "cathy", dataSet1, "POST", 403)
testRequest(t, handler, "cathy", "/dataset1/item", "DELETE", 403) testRequest(t, handler, "cathy", dataSet1, "DELETE", 403)
testRequest(t, handler, "cathy", "/dataset2/item", "GET", 403) testRequest(t, handler, "cathy", dataSet2, "GET", 403)
testRequest(t, handler, "cathy", "/dataset2/item", "POST", 403) testRequest(t, handler, "cathy", dataSet2, "POST", 403)
testRequest(t, handler, "cathy", "/dataset2/item", "DELETE", 403) testRequest(t, handler, "cathy", dataSet2, "DELETE", 403)
} }

View File

@ -5,6 +5,8 @@ import (
"net/http/httptest" "net/http/httptest"
"testing" "testing"
"github.com/stretchr/testify/assert"
"github.com/beego/beego/v2/adapter/session" "github.com/beego/beego/v2/adapter/session"
) )
@ -19,71 +21,55 @@ func TestRedisSentinel(t *testing.T) {
ProviderConfig: "127.0.0.1:6379,100,,0,master", ProviderConfig: "127.0.0.1:6379,100,,0,master",
} }
globalSessions, e := session.NewManager("redis_sentinel", sessionConfig) globalSessions, e := session.NewManager("redis_sentinel", sessionConfig)
if e != nil { if e != nil {
t.Log(e) t.Log(e)
return return
} }
// todo test if e==nil
go globalSessions.GC() go globalSessions.GC()
r, _ := http.NewRequest("GET", "/", nil) r, _ := http.NewRequest("GET", "/", nil)
w := httptest.NewRecorder() w := httptest.NewRecorder()
sess, err := globalSessions.SessionStart(w, r) sess, err := globalSessions.SessionStart(w, r)
if err != nil { assert.Nil(t, err)
t.Fatal("session start failed:", err)
}
defer sess.SessionRelease(w) defer sess.SessionRelease(w)
// SET AND GET // SET AND GET
err = sess.Set("username", "astaxie") err = sess.Set("username", "astaxie")
if err != nil { assert.Nil(t, err)
t.Fatal("set username failed:", err)
}
username := sess.Get("username") username := sess.Get("username")
if username != "astaxie" { assert.Equal(t, "astaxie", username)
t.Fatal("get username failed")
}
// DELETE // DELETE
err = sess.Delete("username") err = sess.Delete("username")
if err != nil { assert.Nil(t, err)
t.Fatal("delete username failed:", err)
}
username = sess.Get("username") username = sess.Get("username")
if username != nil { assert.Nil(t, username)
t.Fatal("delete username failed")
}
// FLUSH // FLUSH
err = sess.Set("username", "astaxie") err = sess.Set("username", "astaxie")
if err != nil { assert.Nil(t, err)
t.Fatal("set failed:", err)
}
err = sess.Set("password", "1qaz2wsx") err = sess.Set("password", "1qaz2wsx")
if err != nil { assert.Nil(t, err)
t.Fatal("set failed:", err)
}
username = sess.Get("username") username = sess.Get("username")
if username != "astaxie" { assert.Equal(t, "astaxie", username)
t.Fatal("get username failed")
}
password := sess.Get("password") password := sess.Get("password")
if password != "1qaz2wsx" { assert.Equal(t, "1qaz2wsx", password)
t.Fatal("get password failed")
}
err = sess.Flush() err = sess.Flush()
if err != nil { assert.Nil(t, err)
t.Fatal("flush failed:", err)
}
username = sess.Get("username") username = sess.Get("username")
if username != nil { assert.Nil(t, username)
t.Fatal("flush failed")
}
password = sess.Get("password") password = sess.Get("password")
if password != nil { assert.Nil(t, password)
t.Fatal("flush failed")
}
sess.SessionRelease(w) sess.SessionRelease(w)

View File

@ -22,6 +22,8 @@ import (
"testing" "testing"
) )
const setCookieKey = "Set-Cookie"
func TestCookie(t *testing.T) { func TestCookie(t *testing.T) {
config := `{"cookieName":"gosessionid","enableSetCookie":false,"gclifetime":3600,"ProviderConfig":"{\"cookieName\":\"gosessionid\",\"securityKey\":\"beegocookiehashkey\"}"}` config := `{"cookieName":"gosessionid","enableSetCookie":false,"gclifetime":3600,"ProviderConfig":"{\"cookieName\":\"gosessionid\",\"securityKey\":\"beegocookiehashkey\"}"}`
conf := new(ManagerConfig) conf := new(ManagerConfig)
@ -46,7 +48,8 @@ func TestCookie(t *testing.T) {
t.Fatal("get username error") t.Fatal("get username error")
} }
sess.SessionRelease(w) sess.SessionRelease(w)
if cookiestr := w.Header().Get("Set-Cookie"); cookiestr == "" {
if cookiestr := w.Header().Get(setCookieKey); cookiestr == "" {
t.Fatal("setcookie error") t.Fatal("setcookie error")
} else { } else {
parts := strings.Split(strings.TrimSpace(cookiestr), ";") parts := strings.Split(strings.TrimSpace(cookiestr), ";")
@ -79,7 +82,7 @@ func TestDestorySessionCookie(t *testing.T) {
// request again ,will get same sesssion id . // request again ,will get same sesssion id .
r1, _ := http.NewRequest("GET", "/", nil) r1, _ := http.NewRequest("GET", "/", nil)
r1.Header.Set("Cookie", w.Header().Get("Set-Cookie")) r1.Header.Set("Cookie", w.Header().Get(setCookieKey))
w = httptest.NewRecorder() w = httptest.NewRecorder()
newSession, err := globalSessions.SessionStart(w, r1) newSession, err := globalSessions.SessionStart(w, r1)
if err != nil { if err != nil {
@ -92,7 +95,7 @@ func TestDestorySessionCookie(t *testing.T) {
// After destroy session , will get a new session id . // After destroy session , will get a new session id .
globalSessions.SessionDestroy(w, r1) globalSessions.SessionDestroy(w, r1)
r2, _ := http.NewRequest("GET", "/", nil) r2, _ := http.NewRequest("GET", "/", nil)
r2.Header.Set("Cookie", w.Header().Get("Set-Cookie")) r2.Header.Set("Cookie", w.Header().Get(setCookieKey))
w = httptest.NewRecorder() w = httptest.NewRecorder()
newSession, err = globalSessions.SessionStart(w, r2) newSession, err = globalSessions.SessionStart(w, r2)

View File

@ -19,19 +19,15 @@ import (
"net/url" "net/url"
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert"
) )
func TestSubstr(t *testing.T) { func TestSubstr(t *testing.T) {
s := `012345` s := `012345`
if Substr(s, 0, 2) != "01" { assert.Equal(t, "01", Substr(s, 0, 2))
t.Error("should be equal") assert.Equal(t, "012345", Substr(s, 0, 100))
} assert.Equal(t, "012345", Substr(s, 12, 100))
if Substr(s, 0, 100) != "012345" {
t.Error("should be equal")
}
if Substr(s, 12, 100) != "012345" {
t.Error("should be equal")
}
} }
func TestHtml2str(t *testing.T) { func TestHtml2str(t *testing.T) {
@ -39,73 +35,51 @@ func TestHtml2str(t *testing.T) {
\n` \n`
if HTML2str(h) != "123\\n\n\\n" { assert.Equal(t, "123\\n\n\\n", HTML2str(h))
t.Error("should be equal")
}
} }
func TestDateFormat(t *testing.T) { func TestDateFormat(t *testing.T) {
ts := "Mon, 01 Jul 2013 13:27:42 CST" ts := "Mon, 01 Jul 2013 13:27:42 CST"
tt, _ := time.Parse(time.RFC1123, ts) tt, _ := time.Parse(time.RFC1123, ts)
if ss := DateFormat(tt, "2006-01-02 15:04:05"); ss != "2013-07-01 13:27:42" { assert.Equal(t, "2013-07-01 13:27:42", DateFormat(tt, "2006-01-02 15:04:05"))
t.Errorf("2013-07-01 13:27:42 does not equal %v", ss)
}
} }
func TestDate(t *testing.T) { func TestDate(t *testing.T) {
ts := "Mon, 01 Jul 2013 13:27:42 CST" ts := "Mon, 01 Jul 2013 13:27:42 CST"
tt, _ := time.Parse(time.RFC1123, ts) tt, _ := time.Parse(time.RFC1123, ts)
if ss := Date(tt, "Y-m-d H:i:s"); ss != "2013-07-01 13:27:42" { assert.Equal(t, "2013-07-01 13:27:42", Date(tt, "Y-m-d H:i:s"))
t.Errorf("2013-07-01 13:27:42 does not equal %v", ss)
} assert.Equal(t, "13-7-1 01:27:42 PM", Date(tt, "y-n-j h:i:s A"))
if ss := Date(tt, "y-n-j h:i:s A"); ss != "13-7-1 01:27:42 PM" { assert.Equal(t, "Mon, 01 Jul 2013 1:27:42 pm", Date(tt, "D, d M Y g:i:s a"))
t.Errorf("13-7-1 01:27:42 PM does not equal %v", ss) assert.Equal(t, "Monday, 01 July 2013 13:27:42", Date(tt, "l, d F Y G:i:s"))
}
if ss := Date(tt, "D, d M Y g:i:s a"); ss != "Mon, 01 Jul 2013 1:27:42 pm" {
t.Errorf("Mon, 01 Jul 2013 1:27:42 pm does not equal %v", ss)
}
if ss := Date(tt, "l, d F Y G:i:s"); ss != "Monday, 01 July 2013 13:27:42" {
t.Errorf("Monday, 01 July 2013 13:27:42 does not equal %v", ss)
}
} }
func TestCompareRelated(t *testing.T) { func TestCompareRelated(t *testing.T) {
if !Compare("abc", "abc") { assert.True(t, Compare("abc", "abc"))
t.Error("should be equal")
} assert.False(t, Compare("abc", "aBc"))
if Compare("abc", "aBc") {
t.Error("should be not equal") assert.True(t, Compare("1", 1))
}
if !Compare("1", 1) { assert.False(t, CompareNot("abc", "abc"))
t.Error("should be equal")
} assert.True(t, CompareNot("abc", "aBc"))
if CompareNot("abc", "abc") { assert.True(t, NotNil("a string"))
t.Error("should be equal")
}
if !CompareNot("abc", "aBc") {
t.Error("should be not equal")
}
if !NotNil("a string") {
t.Error("should not be nil")
}
} }
func TestHtmlquote(t *testing.T) { func TestHtmlquote(t *testing.T) {
h := `<' ”“&">` h := `<' ”“&">`
s := `<' ”“&">` s := `<' ”“&">`
if Htmlquote(s) != h { assert.Equal(t, h, Htmlquote(s))
t.Error("should be equal")
}
} }
func TestHtmlunquote(t *testing.T) { func TestHtmlunquote(t *testing.T) {
h := `&lt;&#39;&nbsp;&rdquo;&ldquo;&amp;&#34;&gt;` h := `&lt;&#39;&nbsp;&rdquo;&ldquo;&amp;&#34;&gt;`
s := `<' ”“&">` s := `<' ”“&">`
if Htmlunquote(h) != s { assert.Equal(t, s, Htmlunquote(h))
t.Error("should be equal")
}
} }
func TestParseForm(t *testing.T) { func TestParseForm(t *testing.T) {
@ -148,55 +122,42 @@ func TestParseForm(t *testing.T) {
"hobby": []string{"", "Basketball", "Football"}, "hobby": []string{"", "Basketball", "Football"},
"memo": []string{"nothing"}, "memo": []string{"nothing"},
} }
if err := ParseForm(form, u); err == nil {
t.Fatal("nothing will be changed") assert.NotNil(t, ParseForm(form, u))
}
if err := ParseForm(form, &u); err != nil { assert.Nil(t, ParseForm(form, &u))
t.Fatal(err)
} assert.Equal(t, 0, u.ID)
if u.ID != 0 {
t.Errorf("ID should equal 0 but got %v", u.ID) assert.Equal(t, 0, len(u.tag))
}
if len(u.tag) != 0 { assert.Equal(t, "test", u.Name)
t.Errorf("tag's length should equal 0 but got %v", len(u.tag))
} assert.Equal(t, 40, u.Age)
if u.Name.(string) != "test" {
t.Errorf("Name should equal `test` but got `%v`", u.Name.(string)) assert.Equal(t, "test@gmail.com", u.Email)
}
if u.Age != 40 { assert.Equal(t, "I am an engineer!", u.Intro)
t.Errorf("Age should equal 40 but got %v", u.Age)
} assert.True(t, u.StrBool)
if u.Email != "test@gmail.com" {
t.Errorf("Email should equal `test@gmail.com` but got `%v`", u.Email)
}
if u.Intro != "I am an engineer!" {
t.Errorf("Intro should equal `I am an engineer!` but got `%v`", u.Intro)
}
if !u.StrBool {
t.Errorf("strboll should equal `true`, but got `%v`", u.StrBool)
}
y, m, d := u.Date.Date() y, m, d := u.Date.Date()
if y != 2014 || m.String() != "November" || d != 12 {
t.Errorf("Date should equal `2014-11-12`, but got `%v`", u.Date.String()) assert.Equal(t, 2014, y)
} assert.Equal(t, "November", m.String())
if u.Organization != "beego" { assert.Equal(t, 12, d)
t.Errorf("Organization should equal `beego`, but got `%v`", u.Organization)
} assert.Equal(t, "beego", u.Organization)
if u.Title != "CXO" {
t.Errorf("Title should equal `CXO`, but got `%v`", u.Title) assert.Equal(t, "CXO", u.Title)
}
if u.Hobby[0] != "" { assert.Equal(t, "", u.Hobby[0])
t.Errorf("Hobby should equal ``, but got `%v`", u.Hobby[0])
} assert.Equal(t, "Basketball", u.Hobby[1])
if u.Hobby[1] != "Basketball" {
t.Errorf("Hobby should equal `Basketball`, but got `%v`", u.Hobby[1]) assert.Equal(t, "Football", u.Hobby[2])
}
if u.Hobby[2] != "Football" { assert.Equal(t, 0, len(u.Memo))
t.Errorf("Hobby should equal `Football`, but got `%v`", u.Hobby[2])
}
if len(u.Memo) != 0 {
t.Errorf("Memo's length should equal 0 but got %v", len(u.Memo))
}
} }
func TestRenderForm(t *testing.T) { func TestRenderForm(t *testing.T) {
@ -212,18 +173,14 @@ func TestRenderForm(t *testing.T) {
u := user{Name: "test", Intro: "Some Text"} u := user{Name: "test", Intro: "Some Text"}
output := RenderForm(u) output := RenderForm(u)
if output != template.HTML("") { assert.Equal(t, template.HTML(""), output)
t.Errorf("output should be empty but got %v", output)
}
output = RenderForm(&u) output = RenderForm(&u)
result := template.HTML( result := template.HTML(
`Name: <input name="username" type="text" value="test"></br>` + `Name: <input name="username" type="text" value="test"></br>` +
`年龄:<input name="age" type="text" value="0"></br>` + `年龄:<input name="age" type="text" value="0"></br>` +
`Sex: <input name="Sex" type="text" value=""></br>` + `Sex: <input name="Sex" type="text" value=""></br>` +
`Intro: <textarea name="Intro">Some Text</textarea>`) `Intro: <textarea name="Intro">Some Text</textarea>`)
if output != result { assert.Equal(t, result, output)
t.Errorf("output should equal `%v` but got `%v`", result, output)
}
} }
func TestMapGet(t *testing.T) { func TestMapGet(t *testing.T) {
@ -233,29 +190,18 @@ func TestMapGet(t *testing.T) {
"1": 2, "1": 2,
} }
if res, err := MapGet(m1, "a"); err == nil { res, err := MapGet(m1, "a")
if res.(int64) != 1 { assert.Nil(t, err)
t.Errorf("Should return 1, but return %v", res) assert.Equal(t, int64(1), res)
}
} else {
t.Errorf("Error happens %v", err)
}
if res, err := MapGet(m1, "1"); err == nil { res, err = MapGet(m1, "1")
if res.(int64) != 2 { assert.Nil(t, err)
t.Errorf("Should return 2, but return %v", res) assert.Equal(t, int64(2), res)
}
} else {
t.Errorf("Error happens %v", err)
}
if res, err := MapGet(m1, 1); err == nil {
if res.(int64) != 2 { res, err = MapGet(m1, 1)
t.Errorf("Should return 2, but return %v", res) assert.Nil(t, err)
} assert.Equal(t, int64(2), res)
} else {
t.Errorf("Error happens %v", err)
}
// test 2 level map // test 2 level map
m2 := M{ m2 := M{
@ -264,13 +210,9 @@ func TestMapGet(t *testing.T) {
}, },
} }
if res, err := MapGet(m2, 1, 2); err == nil { res, err = MapGet(m2, 1, 2)
if res.(float64) != 3.5 { assert.Nil(t, err)
t.Errorf("Should return 3.5, but return %v", res) assert.Equal(t, 3.5, res)
}
} else {
t.Errorf("Error happens %v", err)
}
// test 5 level map // test 5 level map
m5 := M{ m5 := M{
@ -285,20 +227,13 @@ func TestMapGet(t *testing.T) {
}, },
} }
if res, err := MapGet(m5, 1, 2, 3, 4, 5); err == nil { res, err = MapGet(m5, 1, 2, 3, 4, 5)
if res.(float64) != 1.2 { assert.Nil(t, err)
t.Errorf("Should return 1.2, but return %v", res) assert.Equal(t, 1.2, res)
}
} else {
t.Errorf("Error happens %v", err)
}
// check whether element not exists in map // check whether element not exists in map
if res, err := MapGet(m5, 5, 4, 3, 2, 1); err == nil { res, err = MapGet(m5, 5, 4, 3, 2, 1)
if res != nil { assert.Nil(t, err)
t.Errorf("Should return nil, but return %v", res) assert.Nil(t, res)
}
} else {
t.Errorf("Error happens %v", err)
}
} }

View File

@ -21,13 +21,16 @@ import (
) )
func TestStatics(t *testing.T) { func TestStatics(t *testing.T) {
StatisticsMap.AddStatistics("POST", "/api/user", "&admin.user", time.Duration(2000)) userApi := "/api/user"
StatisticsMap.AddStatistics("POST", "/api/user", "&admin.user", time.Duration(120000)) post := "POST"
StatisticsMap.AddStatistics("GET", "/api/user", "&admin.user", time.Duration(13000)) adminUser := "&admin.user"
StatisticsMap.AddStatistics("POST", "/api/admin", "&admin.user", time.Duration(14000)) StatisticsMap.AddStatistics(post, userApi, adminUser, time.Duration(2000))
StatisticsMap.AddStatistics("POST", "/api/user/astaxie", "&admin.user", time.Duration(12000)) StatisticsMap.AddStatistics(post, userApi, adminUser, time.Duration(120000))
StatisticsMap.AddStatistics("POST", "/api/user/xiemengjun", "&admin.user", time.Duration(13000)) StatisticsMap.AddStatistics("GET", userApi, adminUser, time.Duration(13000))
StatisticsMap.AddStatistics("DELETE", "/api/user", "&admin.user", time.Duration(1400)) StatisticsMap.AddStatistics(post, "/api/admin", adminUser, time.Duration(14000))
StatisticsMap.AddStatistics(post, "/api/user/astaxie", adminUser, time.Duration(12000))
StatisticsMap.AddStatistics(post, "/api/user/xiemengjun", adminUser, time.Duration(13000))
StatisticsMap.AddStatistics("DELETE", userApi, adminUser, time.Duration(1400))
t.Log(StatisticsMap.GetMap()) t.Log(StatisticsMap.GetMap())
data := StatisticsMap.GetMapData() data := StatisticsMap.GetMapData()

View File

@ -16,7 +16,7 @@ package utils
import "testing" import "testing"
func TestRand_01(t *testing.T) { func TestRand01(t *testing.T) {
bs0 := RandomCreateBytes(16) bs0 := RandomCreateBytes(16)
bs1 := RandomCreateBytes(16) bs1 := RandomCreateBytes(16)

View File

@ -18,131 +18,83 @@ import (
"regexp" "regexp"
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert"
) )
func TestRequired(t *testing.T) { func TestRequired(t *testing.T) {
valid := Validation{} valid := Validation{}
if valid.Required(nil, "nil").Ok { assert.False(t, valid.Required(nil, "nil").Ok)
t.Error("nil object should be false") assert.True(t, valid.Required(true, "bool").Ok)
}
if !valid.Required(true, "bool").Ok { assert.True(t, valid.Required(false, "bool").Ok)
t.Error("Bool value should always return true") assert.False(t, valid.Required("", "string").Ok)
} assert.False(t, valid.Required(" ", "string").Ok)
if !valid.Required(false, "bool").Ok { assert.False(t, valid.Required("\n", "string").Ok)
t.Error("Bool value should always return true")
} assert.True(t, valid.Required("astaxie", "string").Ok)
if valid.Required("", "string").Ok { assert.False(t, valid.Required(0, "zero").Ok)
t.Error("\"'\" string should be false")
} assert.True(t, valid.Required(1, "int").Ok)
if valid.Required(" ", "string").Ok {
t.Error("\" \" string should be false") // For #2361 assert.True(t, valid.Required(time.Now(), "time").Ok)
}
if valid.Required("\n", "string").Ok { assert.False(t, valid.Required([]string{}, "emptySlice").Ok)
t.Error("new line string should be false") // For #2361
} assert.True(t, valid.Required([]interface{}{"ok"}, "slice").Ok)
if !valid.Required("astaxie", "string").Ok {
t.Error("string should be true")
}
if valid.Required(0, "zero").Ok {
t.Error("Integer should not be equal 0")
}
if !valid.Required(1, "int").Ok {
t.Error("Integer except 0 should be true")
}
if !valid.Required(time.Now(), "time").Ok {
t.Error("time should be true")
}
if valid.Required([]string{}, "emptySlice").Ok {
t.Error("empty slice should be false")
}
if !valid.Required([]interface{}{"ok"}, "slice").Ok {
t.Error("slice should be true")
}
} }
func TestMin(t *testing.T) { func TestMin(t *testing.T) {
valid := Validation{} valid := Validation{}
if valid.Min(-1, 0, "min0").Ok { assert.False(t, valid.Min(-1, 0, "min0").Ok)
t.Error("-1 is less than the minimum value of 0 should be false") assert.True(t, valid.Min(1, 0, "min0").Ok)
}
if !valid.Min(1, 0, "min0").Ok {
t.Error("1 is greater or equal than the minimum value of 0 should be true")
}
} }
func TestMax(t *testing.T) { func TestMax(t *testing.T) {
valid := Validation{} valid := Validation{}
if valid.Max(1, 0, "max0").Ok { assert.False(t, valid.Max(1, 0, "max0").Ok)
t.Error("1 is greater than the minimum value of 0 should be false") assert.True(t, valid.Max(-1, 0, "max0").Ok)
}
if !valid.Max(-1, 0, "max0").Ok {
t.Error("-1 is less or equal than the maximum value of 0 should be true")
}
} }
func TestRange(t *testing.T) { func TestRange(t *testing.T) {
valid := Validation{} valid := Validation{}
if valid.Range(-1, 0, 1, "range0_1").Ok { assert.False(t, valid.Range(-1, 0, 1, "range0_1").Ok)
t.Error("-1 is between 0 and 1 should be false")
} assert.True(t, valid.Range(1, 0, 1, "range0_1").Ok)
if !valid.Range(1, 0, 1, "range0_1").Ok {
t.Error("1 is between 0 and 1 should be true")
}
} }
func TestMinSize(t *testing.T) { func TestMinSize(t *testing.T) {
valid := Validation{} valid := Validation{}
if valid.MinSize("", 1, "minSize1").Ok { assert.False(t, valid.MinSize("", 1, "minSize1").Ok)
t.Error("the length of \"\" is less than the minimum value of 1 should be false")
} assert.True(t, valid.MinSize("ok", 1, "minSize1").Ok)
if !valid.MinSize("ok", 1, "minSize1").Ok { assert.False(t, valid.MinSize([]string{}, 1, "minSize1").Ok)
t.Error("the length of \"ok\" is greater or equal than the minimum value of 1 should be true") assert.True(t, valid.MinSize([]interface{}{"ok"}, 1, "minSize1").Ok)
}
if valid.MinSize([]string{}, 1, "minSize1").Ok {
t.Error("the length of empty slice is less than the minimum value of 1 should be false")
}
if !valid.MinSize([]interface{}{"ok"}, 1, "minSize1").Ok {
t.Error("the length of [\"ok\"] is greater or equal than the minimum value of 1 should be true")
}
} }
func TestMaxSize(t *testing.T) { func TestMaxSize(t *testing.T) {
valid := Validation{} valid := Validation{}
if valid.MaxSize("ok", 1, "maxSize1").Ok { assert.False(t, valid.MaxSize("ok", 1, "maxSize1").Ok)
t.Error("the length of \"ok\" is greater than the maximum value of 1 should be false") assert.True(t, valid.MaxSize("", 1, "maxSize1").Ok)
} assert.False(t, valid.MaxSize([]interface{}{"ok", false}, 1, "maxSize1").Ok)
if !valid.MaxSize("", 1, "maxSize1").Ok { assert.True(t, valid.MaxSize([]string{}, 1, "maxSize1").Ok)
t.Error("the length of \"\" is less or equal than the maximum value of 1 should be true")
}
if valid.MaxSize([]interface{}{"ok", false}, 1, "maxSize1").Ok {
t.Error("the length of [\"ok\", false] is greater than the maximum value of 1 should be false")
}
if !valid.MaxSize([]string{}, 1, "maxSize1").Ok {
t.Error("the length of empty slice is less or equal than the maximum value of 1 should be true")
}
} }
func TestLength(t *testing.T) { func TestLength(t *testing.T) {
valid := Validation{} valid := Validation{}
if valid.Length("", 1, "length1").Ok { assert.False(t, valid.Length("", 1, "length1").Ok)
t.Error("the length of \"\" must equal 1 should be false") assert.True(t, valid.Length("1", 1, "length1").Ok)
}
if !valid.Length("1", 1, "length1").Ok { assert.False(t, valid.Length([]string{}, 1, "length1").Ok)
t.Error("the length of \"1\" must equal 1 should be true") assert.True(t, valid.Length([]interface{}{"ok"}, 1, "length1").Ok)
}
if valid.Length([]string{}, 1, "length1").Ok {
t.Error("the length of empty slice must equal 1 should be false")
}
if !valid.Length([]interface{}{"ok"}, 1, "length1").Ok {
t.Error("the length of [\"ok\"] must equal 1 should be true")
}
} }
func TestAlpha(t *testing.T) { func TestAlpha(t *testing.T) {
@ -178,13 +130,16 @@ func TestAlphaNumeric(t *testing.T) {
} }
} }
const email = "suchuangji@gmail.com"
func TestMatch(t *testing.T) { func TestMatch(t *testing.T) {
valid := Validation{} valid := Validation{}
if valid.Match("suchuangji@gmail", regexp.MustCompile(`^\w+@\w+\.\w+$`), "match").Ok { if valid.Match("suchuangji@gmail", regexp.MustCompile(`^\w+@\w+\.\w+$`), "match").Ok {
t.Error("\"suchuangji@gmail\" match \"^\\w+@\\w+\\.\\w+$\" should be false") t.Error("\"suchuangji@gmail\" match \"^\\w+@\\w+\\.\\w+$\" should be false")
} }
if !valid.Match("suchuangji@gmail.com", regexp.MustCompile(`^\w+@\w+\.\w+$`), "match").Ok {
if !valid.Match(email, regexp.MustCompile(`^\w+@\w+\.\w+$`), "match").Ok {
t.Error("\"suchuangji@gmail\" match \"^\\w+@\\w+\\.\\w+$\" should be true") t.Error("\"suchuangji@gmail\" match \"^\\w+@\\w+\\.\\w+$\" should be true")
} }
} }
@ -217,7 +172,7 @@ func TestEmail(t *testing.T) {
if valid.Email("not@a email", "email").Ok { if valid.Email("not@a email", "email").Ok {
t.Error("\"not@a email\" is a valid email address should be false") t.Error("\"not@a email\" is a valid email address should be false")
} }
if !valid.Email("suchuangji@gmail.com", "email").Ok { if !valid.Email(email, "email").Ok {
t.Error("\"suchuangji@gmail.com\" is a valid email address should be true") t.Error("\"suchuangji@gmail.com\" is a valid email address should be true")
} }
if valid.Email("@suchuangji@gmail.com", "email").Ok { if valid.Email("@suchuangji@gmail.com", "email").Ok {
@ -242,7 +197,7 @@ func TestIP(t *testing.T) {
func TestBase64(t *testing.T) { func TestBase64(t *testing.T) {
valid := Validation{} valid := Validation{}
if valid.Base64("suchuangji@gmail.com", "base64").Ok { if valid.Base64(email, "base64").Ok {
t.Error("\"suchuangji@gmail.com\" are a valid base64 characters should be false") t.Error("\"suchuangji@gmail.com\" are a valid base64 characters should be false")
} }
if !valid.Base64("c3VjaHVhbmdqaUBnbWFpbC5jb20=", "base64").Ok { if !valid.Base64("c3VjaHVhbmdqaUBnbWFpbC5jb20=", "base64").Ok {
@ -370,44 +325,25 @@ func TestValid(t *testing.T) {
u := user{Name: "test@/test/;com", Age: 40} u := user{Name: "test@/test/;com", Age: 40}
b, err := valid.Valid(u) b, err := valid.Valid(u)
if err != nil { assert.Nil(t, err)
t.Fatal(err) assert.True(t, b)
}
if !b {
t.Error("validation should be passed")
}
uptr := &user{Name: "test", Age: 40} uptr := &user{Name: "test", Age: 40}
valid.Clear() valid.Clear()
b, err = valid.Valid(uptr) b, err = valid.Valid(uptr)
if err != nil {
t.Fatal(err) assert.Nil(t, err)
} assert.False(t, b)
if b { assert.Equal(t, 1, len(valid.Errors))
t.Error("validation should not be passed") assert.Equal(t, "Name.Match", valid.Errors[0].Key)
}
if len(valid.Errors) != 1 {
t.Fatalf("valid errors len should be 1 but got %d", len(valid.Errors))
}
if valid.Errors[0].Key != "Name.Match" {
t.Errorf("Message key should be `Name.Match` but got %s", valid.Errors[0].Key)
}
u = user{Name: "test@/test/;com", Age: 180} u = user{Name: "test@/test/;com", Age: 180}
valid.Clear() valid.Clear()
b, err = valid.Valid(u) b, err = valid.Valid(u)
if err != nil { assert.Nil(t, err)
t.Fatal(err) assert.False(t, b)
} assert.Equal(t, 1, len(valid.Errors))
if b { assert.Equal(t, "Age.Range.", valid.Errors[0].Key)
t.Error("validation should not be passed")
}
if len(valid.Errors) != 1 {
t.Fatalf("valid errors len should be 1 but got %d", len(valid.Errors))
}
if valid.Errors[0].Key != "Age.Range." {
t.Errorf("Message key should be `Age.Range` but got %s", valid.Errors[0].Key)
}
} }
func TestRecursiveValid(t *testing.T) { func TestRecursiveValid(t *testing.T) {
@ -432,12 +368,8 @@ func TestRecursiveValid(t *testing.T) {
u := Account{Password: "abc123_", U: User{}} u := Account{Password: "abc123_", U: User{}}
b, err := valid.RecursiveValid(u) b, err := valid.RecursiveValid(u)
if err != nil { assert.Nil(t, err)
t.Fatal(err) assert.False(t, b)
}
if b {
t.Error("validation should not be passed")
}
} }
func TestSkipValid(t *testing.T) { func TestSkipValid(t *testing.T) {
@ -474,21 +406,13 @@ func TestSkipValid(t *testing.T) {
valid := Validation{} valid := Validation{}
b, err := valid.Valid(u) b, err := valid.Valid(u)
if err != nil { assert.Nil(t, err)
t.Fatal(err) assert.False(t, b)
}
if b {
t.Fatal("validation should not be passed")
}
valid = Validation{RequiredFirst: true} valid = Validation{RequiredFirst: true}
b, err = valid.Valid(u) b, err = valid.Valid(u)
if err != nil { assert.Nil(t, err)
t.Fatal(err) assert.True(t, b)
}
if !b {
t.Fatal("validation should be passed")
}
} }
func TestPointer(t *testing.T) { func TestPointer(t *testing.T) {
@ -506,12 +430,8 @@ func TestPointer(t *testing.T) {
valid := Validation{} valid := Validation{}
b, err := valid.Valid(u) b, err := valid.Valid(u)
if err != nil { assert.Nil(t, err)
t.Fatal(err) assert.False(t, b)
}
if b {
t.Fatal("validation should not be passed")
}
validEmail := "a@a.com" validEmail := "a@a.com"
u = User{ u = User{
@ -521,12 +441,8 @@ func TestPointer(t *testing.T) {
valid = Validation{RequiredFirst: true} valid = Validation{RequiredFirst: true}
b, err = valid.Valid(u) b, err = valid.Valid(u)
if err != nil { assert.Nil(t, err)
t.Fatal(err) assert.True(t, b)
}
if !b {
t.Fatal("validation should be passed")
}
u = User{ u = User{
ReqEmail: &validEmail, ReqEmail: &validEmail,
@ -535,12 +451,8 @@ func TestPointer(t *testing.T) {
valid = Validation{} valid = Validation{}
b, err = valid.Valid(u) b, err = valid.Valid(u)
if err != nil { assert.Nil(t, err)
t.Fatal(err) assert.False(t, b)
}
if b {
t.Fatal("validation should not be passed")
}
invalidEmail := "a@a" invalidEmail := "a@a"
u = User{ u = User{
@ -550,12 +462,8 @@ func TestPointer(t *testing.T) {
valid = Validation{RequiredFirst: true} valid = Validation{RequiredFirst: true}
b, err = valid.Valid(u) b, err = valid.Valid(u)
if err != nil { assert.Nil(t, err)
t.Fatal(err) assert.False(t, b)
}
if b {
t.Fatal("validation should not be passed")
}
u = User{ u = User{
ReqEmail: &validEmail, ReqEmail: &validEmail,
@ -564,12 +472,8 @@ func TestPointer(t *testing.T) {
valid = Validation{} valid = Validation{}
b, err = valid.Valid(u) b, err = valid.Valid(u)
if err != nil { assert.Nil(t, err)
t.Fatal(err) assert.False(t, b)
}
if b {
t.Fatal("validation should not be passed")
}
} }
func TestCanSkipAlso(t *testing.T) { func TestCanSkipAlso(t *testing.T) {
@ -589,21 +493,14 @@ func TestCanSkipAlso(t *testing.T) {
valid := Validation{RequiredFirst: true} valid := Validation{RequiredFirst: true}
b, err := valid.Valid(u) b, err := valid.Valid(u)
if err != nil { assert.Nil(t, err)
t.Fatal(err) assert.False(t, b)
}
if b {
t.Fatal("validation should not be passed")
}
valid = Validation{RequiredFirst: true} valid = Validation{RequiredFirst: true}
valid.CanSkipAlso("Range") valid.CanSkipAlso("Range")
b, err = valid.Valid(u) b, err = valid.Valid(u)
if err != nil {
t.Fatal(err) assert.Nil(t, err)
} assert.True(t, b)
if !b {
t.Fatal("validation should be passed")
}
} }

View File

@ -18,16 +18,17 @@ import (
"context" "context"
"math" "math"
"os" "os"
"strings"
"sync" "sync"
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert"
) )
func TestCacheIncr(t *testing.T) { func TestCacheIncr(t *testing.T) {
bm, err := NewCache("memory", `{"interval":20}`) bm, err := NewCache("memory", `{"interval":20}`)
if err != nil { assert.Nil(t, err)
t.Error("init err")
}
// timeoutDuration := 10 * time.Second // timeoutDuration := 10 * time.Second
bm.Put(context.Background(), "edwardhey", 0, time.Second*20) bm.Put(context.Background(), "edwardhey", 0, time.Second*20)
@ -48,9 +49,7 @@ func TestCacheIncr(t *testing.T) {
func TestCache(t *testing.T) { func TestCache(t *testing.T) {
bm, err := NewCache("memory", `{"interval":1}`) bm, err := NewCache("memory", `{"interval":1}`)
if err != nil { assert.Nil(t, err)
t.Error("init err")
}
timeoutDuration := 5 * time.Second timeoutDuration := 5 * time.Second
if err = bm.Put(context.Background(), "astaxie", 1, timeoutDuration); err != nil { if err = bm.Put(context.Background(), "astaxie", 1, timeoutDuration); err != nil {
t.Error("set Error", err) t.Error("set Error", err)
@ -81,70 +80,48 @@ func TestCache(t *testing.T) {
testDecrOverFlow(t, bm, timeoutDuration) testDecrOverFlow(t, bm, timeoutDuration)
bm.Delete(context.Background(), "astaxie") bm.Delete(context.Background(), "astaxie")
if res, _ := bm.IsExist(context.Background(), "astaxie"); res { res, _ := bm.IsExist(context.Background(), "astaxie")
t.Error("delete err") assert.False(t, res)
}
// test GetMulti assert.Nil(t, bm.Put(context.Background(), "astaxie", "author", timeoutDuration))
if err = bm.Put(context.Background(), "astaxie", "author", timeoutDuration); err != nil {
t.Error("set Error", err)
}
if res, _ := bm.IsExist(context.Background(), "astaxie"); !res {
t.Error("check err")
}
if v, _ := bm.Get(context.Background(), "astaxie"); v.(string) != "author" {
t.Error("get err")
}
if err = bm.Put(context.Background(), "astaxie1", "author1", timeoutDuration); err != nil { res, _ = bm.IsExist(context.Background(), "astaxie")
t.Error("set Error", err) assert.True(t, res)
}
if res, _ := bm.IsExist(context.Background(), "astaxie1"); !res { v, _ := bm.Get(context.Background(), "astaxie")
t.Error("check err") assert.Equal(t, "author", v)
}
assert.Nil(t, bm.Put(context.Background(), "astaxie1", "author1", timeoutDuration))
res, _ = bm.IsExist(context.Background(), "astaxie1")
assert.True(t, res)
vv, _ := bm.GetMulti(context.Background(), []string{"astaxie", "astaxie1"}) vv, _ := bm.GetMulti(context.Background(), []string{"astaxie", "astaxie1"})
if len(vv) != 2 { assert.Equal(t, 2, len(vv))
t.Error("GetMulti ERROR") assert.Equal(t, "author", vv[0])
} assert.Equal(t,"author1", vv[1])
if vv[0].(string) != "author" {
t.Error("GetMulti ERROR")
}
if vv[1].(string) != "author1" {
t.Error("GetMulti ERROR")
}
vv, err = bm.GetMulti(context.Background(), []string{"astaxie0", "astaxie1"}) vv, err = bm.GetMulti(context.Background(), []string{"astaxie0", "astaxie1"})
if len(vv) != 2 { assert.Equal(t, 2, len(vv))
t.Error("GetMulti ERROR") assert.Nil(t, vv[0])
} assert.Equal(t, "author1", vv[1])
if vv[0] != nil {
t.Error("GetMulti ERROR") assert.NotNil(t, err)
} assert.True(t, strings.Contains(err.Error(), "key isn't exist"))
if vv[1].(string) != "author1" {
t.Error("GetMulti ERROR")
}
if err != nil && err.Error() != "key [astaxie0] error: the key isn't exist" {
t.Error("GetMulti ERROR")
}
} }
func TestFileCache(t *testing.T) { func TestFileCache(t *testing.T) {
bm, err := NewCache("file", `{"CachePath":"cache","FileSuffix":".bin","DirectoryLevel":"2","EmbedExpiry":"0"}`) bm, err := NewCache("file", `{"CachePath":"cache","FileSuffix":".bin","DirectoryLevel":"2","EmbedExpiry":"0"}`)
if err != nil { assert.Nil(t, err)
t.Error("init err")
}
timeoutDuration := 10 * time.Second timeoutDuration := 10 * time.Second
if err = bm.Put(context.Background(), "astaxie", 1, timeoutDuration); err != nil { assert.Nil(t, bm.Put(context.Background(), "astaxie", 1, timeoutDuration))
t.Error("set Error", err)
}
if res, _ := bm.IsExist(context.Background(), "astaxie"); !res {
t.Error("check err")
}
if v, _ := bm.Get(context.Background(), "astaxie"); v.(int) != 1 { res, _ := bm.IsExist(context.Background(), "astaxie")
t.Error("get err") assert.True(t, res)
} v, _ := bm.Get(context.Background(), "astaxie")
assert.Equal(t, 1, v)
// test different integer type for incr & decr // test different integer type for incr & decr
testMultiTypeIncrDecr(t, bm, timeoutDuration) testMultiTypeIncrDecr(t, bm, timeoutDuration)
@ -154,54 +131,35 @@ func TestFileCache(t *testing.T) {
testDecrOverFlow(t, bm, timeoutDuration) testDecrOverFlow(t, bm, timeoutDuration)
bm.Delete(context.Background(), "astaxie") bm.Delete(context.Background(), "astaxie")
if res, _ := bm.IsExist(context.Background(), "astaxie"); res { res, _ = bm.IsExist(context.Background(), "astaxie")
t.Error("delete err") assert.False(t, res)
}
// test string // test string
if err = bm.Put(context.Background(), "astaxie", "author", timeoutDuration); err != nil { assert.Nil(t, bm.Put(context.Background(), "astaxie", "author", timeoutDuration))
t.Error("set Error", err) res, _ = bm.IsExist(context.Background(), "astaxie")
} assert.True(t, res)
if res, _ := bm.IsExist(context.Background(), "astaxie"); !res {
t.Error("check err") v, _ = bm.Get(context.Background(), "astaxie")
} assert.Equal(t, "author", v)
if v, _ := bm.Get(context.Background(), "astaxie"); v.(string) != "author" {
t.Error("get err")
}
// test GetMulti // test GetMulti
if err = bm.Put(context.Background(), "astaxie1", "author1", timeoutDuration); err != nil { assert.Nil(t, bm.Put(context.Background(), "astaxie1", "author1", timeoutDuration))
t.Error("set Error", err)
} res, _ = bm.IsExist(context.Background(), "astaxie1")
if res, _ := bm.IsExist(context.Background(), "astaxie1"); !res { assert.True(t, res)
t.Error("check err")
}
vv, _ := bm.GetMulti(context.Background(), []string{"astaxie", "astaxie1"}) vv, _ := bm.GetMulti(context.Background(), []string{"astaxie", "astaxie1"})
if len(vv) != 2 { assert.Equal(t, 2, len(vv))
t.Error("GetMulti ERROR") assert.Equal(t, "author", vv[0])
} assert.Equal(t, "author1", vv[1])
if vv[0].(string) != "author" {
t.Error("GetMulti ERROR")
}
if vv[1].(string) != "author1" {
t.Error("GetMulti ERROR")
}
vv, err = bm.GetMulti(context.Background(), []string{"astaxie0", "astaxie1"}) vv, err = bm.GetMulti(context.Background(), []string{"astaxie0", "astaxie1"})
if len(vv) != 2 { assert.Equal(t, 2, len(vv))
t.Error("GetMulti ERROR")
}
if vv[0] != nil {
t.Error("GetMulti ERROR")
}
if vv[1].(string) != "author1" {
t.Error("GetMulti ERROR")
}
if err == nil {
t.Error("GetMulti ERROR")
}
assert.Nil(t, vv[0])
assert.Equal(t, "author1", vv[1])
assert.NotNil(t, err)
os.RemoveAll("cache") os.RemoveAll("cache")
} }
@ -215,53 +173,33 @@ func testMultiTypeIncrDecr(t *testing.T, c Cache, timeout time.Duration) {
} }
func testIncrDecr(t *testing.T, c Cache, beforeIncr interface{}, afterIncr interface{}, timeout time.Duration) { func testIncrDecr(t *testing.T, c Cache, beforeIncr interface{}, afterIncr interface{}, timeout time.Duration) {
var err error
ctx := context.Background() ctx := context.Background()
key := "incDecKey" key := "incDecKey"
if err = c.Put(ctx, key, beforeIncr, timeout); err != nil {
t.Error("Get Error", err)
}
if err = c.Incr(ctx, key); err != nil { assert.Nil(t, c.Put(ctx, key, beforeIncr, timeout))
t.Error("Incr Error", err) assert.Nil(t, c.Incr(ctx, key))
}
if v, _ := c.Get(ctx, key); v != afterIncr {
t.Error("Get Error")
}
if err = c.Decr(ctx, key); err != nil { v, _ := c.Get(ctx, key)
t.Error("Decr Error", err) assert.Equal(t, afterIncr, v)
}
if v, _ := c.Get(ctx, key); v != beforeIncr { assert.Nil(t, c.Decr(ctx, key))
t.Error("Get Error")
}
if err := c.Delete(ctx, key); err != nil { v, _ = c.Get(ctx, key)
t.Error("Delete Error") assert.Equal(t, v, beforeIncr)
} assert.Nil(t, c.Delete(ctx, key))
} }
func testIncrOverFlow(t *testing.T, c Cache, timeout time.Duration) { func testIncrOverFlow(t *testing.T, c Cache, timeout time.Duration) {
var err error
ctx := context.Background() ctx := context.Background()
key := "incKey" key := "incKey"
assert.Nil(t, c.Put(ctx, key, int64(math.MaxInt64), timeout))
// int64 // int64
if err = c.Put(ctx, key, int64(math.MaxInt64), timeout); err != nil {
t.Error("Put Error: ", err.Error())
return
}
defer func() { defer func() {
if err = c.Delete(ctx, key); err != nil { assert.Nil(t, c.Delete(ctx, key))
t.Errorf("Delete error: %s", err.Error())
}
}() }()
if err = c.Incr(ctx, key); err == nil { assert.NotNil(t, c.Incr(ctx, key))
t.Error("Incr error")
return
}
} }
func testDecrOverFlow(t *testing.T, c Cache, timeout time.Duration) { func testDecrOverFlow(t *testing.T, c Cache, timeout time.Duration) {

View File

@ -16,128 +16,74 @@ package cache
import ( import (
"testing" "testing"
"github.com/stretchr/testify/assert"
) )
func TestGetString(t *testing.T) { func TestGetString(t *testing.T) {
var t1 = "test1" var t1 = "test1"
if "test1" != GetString(t1) {
t.Error("get string from string error")
}
var t2 = []byte("test2")
if "test2" != GetString(t2) {
t.Error("get string from byte array error")
}
var t3 = 1
if "1" != GetString(t3) {
t.Error("get string from int error")
}
var t4 int64 = 1
if "1" != GetString(t4) {
t.Error("get string from int64 error")
}
var t5 = 1.1
if "1.1" != GetString(t5) {
t.Error("get string from float64 error")
}
if "" != GetString(nil) { assert.Equal(t, "test1", GetString(t1))
t.Error("get string from nil error") var t2 = []byte("test2")
} assert.Equal(t, "test2", GetString(t2))
var t3 = 1
assert.Equal(t, "1", GetString(t3))
var t4 int64 = 1
assert.Equal(t, "1", GetString(t4))
var t5 = 1.1
assert.Equal(t, "1.1", GetString(t5))
assert.Equal(t, "", GetString(nil))
} }
func TestGetInt(t *testing.T) { func TestGetInt(t *testing.T) {
var t1 = 1 var t1 = 1
if 1 != GetInt(t1) { assert.Equal(t, 1, GetInt(t1))
t.Error("get int from int error")
}
var t2 int32 = 32 var t2 int32 = 32
if 32 != GetInt(t2) { assert.Equal(t, 32, GetInt(t2))
t.Error("get int from int32 error")
}
var t3 int64 = 64 var t3 int64 = 64
if 64 != GetInt(t3) { assert.Equal(t, 64, GetInt(t3))
t.Error("get int from int64 error")
}
var t4 = "128" var t4 = "128"
if 128 != GetInt(t4) {
t.Error("get int from num string error") assert.Equal(t, 128, GetInt(t4))
} assert.Equal(t, 0, GetInt(nil))
if 0 != GetInt(nil) {
t.Error("get int from nil error")
}
} }
func TestGetInt64(t *testing.T) { func TestGetInt64(t *testing.T) {
var i int64 = 1 var i int64 = 1
var t1 = 1 var t1 = 1
if i != GetInt64(t1) { assert.Equal(t, i, GetInt64(t1))
t.Error("get int64 from int error")
}
var t2 int32 = 1 var t2 int32 = 1
if i != GetInt64(t2) {
t.Error("get int64 from int32 error") assert.Equal(t, i, GetInt64(t2))
}
var t3 int64 = 1 var t3 int64 = 1
if i != GetInt64(t3) { assert.Equal(t, i, GetInt64(t3))
t.Error("get int64 from int64 error")
}
var t4 = "1" var t4 = "1"
if i != GetInt64(t4) { assert.Equal(t, i, GetInt64(t4))
t.Error("get int64 from num string error") assert.Equal(t, int64(0), GetInt64(nil))
}
if 0 != GetInt64(nil) {
t.Error("get int64 from nil")
}
} }
func TestGetFloat64(t *testing.T) { func TestGetFloat64(t *testing.T) {
var f = 1.11 var f = 1.11
var t1 float32 = 1.11 var t1 float32 = 1.11
if f != GetFloat64(t1) { assert.Equal(t, f, GetFloat64(t1))
t.Error("get float64 from float32 error")
}
var t2 = 1.11 var t2 = 1.11
if f != GetFloat64(t2) { assert.Equal(t, f, GetFloat64(t2))
t.Error("get float64 from float64 error")
}
var t3 = "1.11" var t3 = "1.11"
if f != GetFloat64(t3) { assert.Equal(t, f, GetFloat64(t3))
t.Error("get float64 from string error")
}
var f2 float64 = 1 var f2 float64 = 1
var t4 = 1 var t4 = 1
if f2 != GetFloat64(t4) { assert.Equal(t, f2, GetFloat64(t4))
t.Error("get float64 from int error")
}
if 0 != GetFloat64(nil) { assert.Equal(t, float64(0), GetFloat64(nil))
t.Error("get float64 from nil error")
}
} }
func TestGetBool(t *testing.T) { func TestGetBool(t *testing.T) {
var t1 = true var t1 = true
if !GetBool(t1) { assert.True(t, GetBool(t1))
t.Error("get bool from bool error")
}
var t2 = "true" var t2 = "true"
if !GetBool(t2) { assert.True(t, GetBool(t2))
t.Error("get bool from string error")
}
if GetBool(nil) {
t.Error("get bool from nil error")
}
}
func byteArrayEquals(a []byte, b []byte) bool { assert.False(t, GetBool(nil))
if len(a) != len(b) {
return false
}
for i, v := range a {
if v != b[i] {
return false
}
}
return true
} }

View File

@ -42,6 +42,7 @@ func TestFileCacheStartAndGC(t *testing.T) {
str := getTestCacheFilePath() str := getTestCacheFilePath()
err = fc.StartAndGC(fmt.Sprintf(`{"CachePath":"%s","FileSuffix":".bin","DirectoryLevel":"2","EmbedExpiry":"0"}`, str)) err = fc.StartAndGC(fmt.Sprintf(`{"CachePath":"%s","FileSuffix":".bin","DirectoryLevel":"2","EmbedExpiry":"0"}`, str))
assert.Nil(t, err)
assert.Equal(t, fc.CachePath, str) assert.Equal(t, fc.CachePath, str)
assert.Equal(t, fc.DirectoryLevel, 2) assert.Equal(t, fc.DirectoryLevel, 2)
assert.Equal(t, fc.EmbedExpiry, 0) assert.Equal(t, fc.EmbedExpiry, 0)
@ -65,22 +66,24 @@ func TestFileCacheInit(t *testing.T) {
} }
func TestFileGetContents(t *testing.T) { func TestFileGetContents(t *testing.T) {
data, err := FileGetContents("/bin/aaa") _, err := FileGetContents("/bin/aaa")
assert.NotNil(t, err) assert.NotNil(t, err)
fn := filepath.Join(os.TempDir(), "fileCache.txt") fn := filepath.Join(os.TempDir(), "fileCache.txt")
f, err := os.Create(fn) f, err := os.Create(fn)
assert.Nil(t, err) assert.Nil(t, err)
_, err = f.WriteString("text") _, err = f.WriteString("text")
assert.Nil(t, err) assert.Nil(t, err)
data, err = FileGetContents(fn) data, err := FileGetContents(fn)
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, "text", string(data)) assert.Equal(t, "text", string(data))
} }
func TestGobEncodeDecode(t *testing.T) { func TestGobEncodeDecode(t *testing.T) {
data, err := GobEncode(func() {}) _, err := GobEncode(func() {
fmt.Print("test func")
})
assert.NotNil(t, err) assert.NotNil(t, err)
data, err = GobEncode(&FileCacheItem{ data, err := GobEncode(&FileCacheItem{
Data: "hello", Data: "hello",
}) })
assert.Nil(t, err) assert.Nil(t, err)

View File

@ -79,7 +79,7 @@ func (rc *Cache) GetMulti(ctx context.Context, keys []string) ([]interface{}, er
keysErr := make([]string, 0) keysErr := make([]string, 0)
for i, ki := range keys { for i, ki := range keys {
if _, ok := mv[ki]; !ok { if _, ok := mv[ki]; !ok {
keysErr = append(keysErr, fmt.Sprintf("key [%s] error: %s", ki, "the key isn't exist")) keysErr = append(keysErr, fmt.Sprintf("key [%s] error: %s", ki, "key not exist"))
continue continue
} }
rv[i] = mv[ki].Value rv[i] = mv[ki].Value
@ -100,7 +100,7 @@ func (rc *Cache) Put(ctx context.Context, key string, val interface{}, timeout t
item.Value = []byte(str) item.Value = []byte(str)
} else { } else {
return berror.Errorf(cache.InvalidMemCacheValue, return berror.Errorf(cache.InvalidMemCacheValue,
"the value must be string or byte[]. key: %s, value:%V", key, val) "the value must be string or byte[]. key: %s, value:%v", key, val)
} }
return berror.Wrapf(rc.conn.Set(&item), cache.MemCacheCurdFailed, return berror.Wrapf(rc.conn.Set(&item), cache.MemCacheCurdFailed,
"could not put key-value to memcache, key: %s", key) "could not put key-value to memcache, key: %s", key)

View File

@ -19,10 +19,12 @@ import (
"fmt" "fmt"
"os" "os"
"strconv" "strconv"
"strings"
"testing" "testing"
"time" "time"
_ "github.com/bradfitz/gomemcache/memcache" _ "github.com/bradfitz/gomemcache/memcache"
"github.com/stretchr/testify/assert"
"github.com/beego/beego/v2/client/cache" "github.com/beego/beego/v2/client/cache"
) )
@ -34,78 +36,63 @@ func TestMemcacheCache(t *testing.T) {
} }
bm, err := cache.NewCache("memcache", fmt.Sprintf(`{"conn": "%s"}`, addr)) bm, err := cache.NewCache("memcache", fmt.Sprintf(`{"conn": "%s"}`, addr))
if err != nil { assert.Nil(t, err)
t.Error("init err")
}
timeoutDuration := 10 * time.Second timeoutDuration := 10 * time.Second
if err = bm.Put(context.Background(), "astaxie", "1", timeoutDuration); err != nil {
t.Error("set Error", err) assert.Nil(t, bm.Put(context.Background(), "astaxie", "1", timeoutDuration))
} res, _ := bm.IsExist(context.Background(), "astaxie")
if res, _ := bm.IsExist(context.Background(), "astaxie"); !res { assert.True(t, res)
t.Error("check err")
}
time.Sleep(11 * time.Second) time.Sleep(11 * time.Second)
if res, _ := bm.IsExist(context.Background(), "astaxie"); res { res, _ = bm.IsExist(context.Background(), "astaxie")
t.Error("check err") assert.False(t, res)
}
if err = bm.Put(context.Background(), "astaxie", "1", timeoutDuration); err != nil { assert.Nil(t, bm.Put(context.Background(), "astaxie", "1", timeoutDuration))
t.Error("set Error", err)
}
val, _ := bm.Get(context.Background(), "astaxie") val, _ := bm.Get(context.Background(), "astaxie")
if v, err := strconv.Atoi(string(val.([]byte))); err != nil || v != 1 { v, err := strconv.Atoi(string(val.([]byte)))
t.Error("get err") assert.Nil(t, err)
} assert.Equal(t, 1, v)
if err = bm.Incr(context.Background(), "astaxie"); err != nil { assert.Nil(t, bm.Incr(context.Background(), "astaxie"))
t.Error("Incr Error", err)
}
val, _ = bm.Get(context.Background(), "astaxie") val, _ = bm.Get(context.Background(), "astaxie")
if v, err := strconv.Atoi(string(val.([]byte))); err != nil || v != 2 { v, err = strconv.Atoi(string(val.([]byte)))
t.Error("get err") assert.Nil(t, err)
} assert.Equal(t, 2, v)
if err = bm.Decr(context.Background(), "astaxie"); err != nil { assert.Nil(t, bm.Decr(context.Background(), "astaxie"))
t.Error("Decr Error", err)
}
val, _ = bm.Get(context.Background(), "astaxie") val, _ = bm.Get(context.Background(), "astaxie")
if v, err := strconv.Atoi(string(val.([]byte))); err != nil || v != 1 { v, err = strconv.Atoi(string(val.([]byte)))
t.Error("get err") assert.Nil(t, err)
} assert.Equal(t, 1, v)
bm.Delete(context.Background(), "astaxie") bm.Delete(context.Background(), "astaxie")
if res, _ := bm.IsExist(context.Background(), "astaxie"); res {
t.Error("delete err")
}
res, _ = bm.IsExist(context.Background(), "astaxie")
assert.False(t, res)
assert.Nil(t,bm.Put(context.Background(), "astaxie", "author", timeoutDuration) )
// test string // test string
if err = bm.Put(context.Background(), "astaxie", "author", timeoutDuration); err != nil { res, _ = bm.IsExist(context.Background(), "astaxie")
t.Error("set Error", err) assert.True(t, res)
}
if res, _ := bm.IsExist(context.Background(), "astaxie"); !res {
t.Error("check err")
}
val, _ = bm.Get(context.Background(), "astaxie") val, _ = bm.Get(context.Background(), "astaxie")
if v := val.([]byte); string(v) != "author" { vs := val.([]byte)
t.Error("get err") assert.Equal(t, "author", string(vs))
}
// test GetMulti // test GetMulti
if err = bm.Put(context.Background(), "astaxie1", "author1", timeoutDuration); err != nil { assert.Nil(t, bm.Put(context.Background(), "astaxie1", "author1", timeoutDuration))
t.Error("set Error", err)
}
if res, _ := bm.IsExist(context.Background(), "astaxie1"); !res { res, _ = bm.IsExist(context.Background(), "astaxie1")
t.Error("check err") assert.True(t, res)
}
vv, _ := bm.GetMulti(context.Background(), []string{"astaxie", "astaxie1"}) vv, _ := bm.GetMulti(context.Background(), []string{"astaxie", "astaxie1"})
if len(vv) != 2 { assert.Equal(t, 2, len(vv))
t.Error("GetMulti ERROR")
}
if string(vv[0].([]byte)) != "author" && string(vv[0].([]byte)) != "author1" { if string(vv[0].([]byte)) != "author" && string(vv[0].([]byte)) != "author1" {
t.Error("GetMulti ERROR") t.Error("GetMulti ERROR")
} }
@ -114,21 +101,14 @@ func TestMemcacheCache(t *testing.T) {
} }
vv, err = bm.GetMulti(context.Background(), []string{"astaxie0", "astaxie1"}) vv, err = bm.GetMulti(context.Background(), []string{"astaxie0", "astaxie1"})
if len(vv) != 2 { assert.Equal(t, 2, len(vv))
t.Error("GetMulti ERROR") assert.Nil(t, vv[0])
}
if vv[0] != nil {
t.Error("GetMulti ERROR")
}
if string(vv[1].([]byte)) != "author1" {
t.Error("GetMulti ERROR")
}
if err != nil && err.Error() == "key [astaxie0] error: key isn't exist" {
t.Error("GetMulti ERROR")
}
assert.Equal(t, "author1", string(vv[1].([]byte)))
assert.NotNil(t, err)
assert.True(t, strings.Contains(err.Error(), "key not exist"))
assert.Nil(t, bm.ClearAll(context.Background()))
// test clear all // test clear all
if err = bm.ClearAll(context.Background()); err != nil {
t.Error("clear all err")
}
} }

View File

@ -207,7 +207,7 @@ func (rc *Cache) StartAndGC(config string) error {
cf["key"] = DefaultKey cf["key"] = DefaultKey
} }
if _, ok := cf["conn"]; !ok { if _, ok := cf["conn"]; !ok {
return berror.Wrapf(err, cache.InvalidRedisCacheCfg, "config missing conn field. ", config) return berror.Wrapf(err, cache.InvalidRedisCacheCfg, "config missing conn field: %s", config)
} }
// Format redis://<password>@<host>:<port> // Format redis://<password>@<host>:<port>

View File

@ -35,96 +35,74 @@ func TestRedisCache(t *testing.T) {
} }
bm, err := cache.NewCache("redis", fmt.Sprintf(`{"conn": "%s"}`, redisAddr)) bm, err := cache.NewCache("redis", fmt.Sprintf(`{"conn": "%s"}`, redisAddr))
if err != nil { assert.Nil(t, err)
t.Error("init err") timeoutDuration := 3 * time.Second
}
timeoutDuration := 10 * time.Second
if err = bm.Put(context.Background(), "astaxie", 1, timeoutDuration); err != nil {
t.Error("set Error", err)
}
if res, _ := bm.IsExist(context.Background(), "astaxie"); !res {
t.Error("check err")
}
time.Sleep(11 * time.Second) assert.Nil(t, bm.Put(context.Background(), "astaxie", 1, timeoutDuration))
res, _ := bm.IsExist(context.Background(), "astaxie")
assert.True(t, res)
time.Sleep(5 * time.Second)
res, _ = bm.IsExist(context.Background(), "astaxie")
assert.False(t, res)
assert.Nil(t, bm.Put(context.Background(), "astaxie", 1, timeoutDuration))
if res, _ := bm.IsExist(context.Background(), "astaxie"); res {
t.Error("check err")
}
if err = bm.Put(context.Background(), "astaxie", 1, timeoutDuration); err != nil {
t.Error("set Error", err)
}
val, _ := bm.Get(context.Background(), "astaxie") val, _ := bm.Get(context.Background(), "astaxie")
if v, _ := redis.Int(val, err); v != 1 { v, _ := redis.Int(val, err)
t.Error("get err") assert.Equal(t, 1, v)
}
if err = bm.Incr(context.Background(), "astaxie"); err != nil { assert.Nil(t, bm.Incr(context.Background(), "astaxie"))
t.Error("Incr Error", err)
}
val, _ = bm.Get(context.Background(), "astaxie") val, _ = bm.Get(context.Background(), "astaxie")
if v, _ := redis.Int(val, err); v != 2 { v, _ = redis.Int(val, err)
t.Error("get err") assert.Equal(t, 2, v)
}
if err = bm.Decr(context.Background(), "astaxie"); err != nil { assert.Nil(t, bm.Decr(context.Background(), "astaxie"))
t.Error("Decr Error", err)
}
val, _ = bm.Get(context.Background(), "astaxie") val, _ = bm.Get(context.Background(), "astaxie")
if v, _ := redis.Int(val, err); v != 1 { v, _ = redis.Int(val, err)
t.Error("get err") assert.Equal(t, 1, v)
}
bm.Delete(context.Background(), "astaxie") bm.Delete(context.Background(), "astaxie")
if res, _ := bm.IsExist(context.Background(), "astaxie"); res {
t.Error("delete err")
}
res, _ = bm.IsExist(context.Background(), "astaxie")
assert.False(t, res)
assert.Nil(t, bm.Put(context.Background(), "astaxie", "author", timeoutDuration))
// test string // test string
if err = bm.Put(context.Background(), "astaxie", "author", timeoutDuration); err != nil {
t.Error("set Error", err) res, _ = bm.IsExist(context.Background(), "astaxie")
} assert.True(t, res)
if res, _ := bm.IsExist(context.Background(), "astaxie"); !res {
t.Error("check err")
}
val, _ = bm.Get(context.Background(), "astaxie") val, _ = bm.Get(context.Background(), "astaxie")
if v, _ := redis.String(val, err); v != "author" { vs, _ := redis.String(val, err)
t.Error("get err") assert.Equal(t, "author", vs)
}
// test GetMulti // test GetMulti
if err = bm.Put(context.Background(), "astaxie1", "author1", timeoutDuration); err != nil { assert.Nil(t, bm.Put(context.Background(), "astaxie1", "author1", timeoutDuration))
t.Error("set Error", err)
} res, _ = bm.IsExist(context.Background(), "astaxie1")
if res, _ := bm.IsExist(context.Background(), "astaxie1"); !res { assert.True(t, res)
t.Error("check err")
}
vv, _ := bm.GetMulti(context.Background(), []string{"astaxie", "astaxie1"}) vv, _ := bm.GetMulti(context.Background(), []string{"astaxie", "astaxie1"})
if len(vv) != 2 { assert.Equal(t, 2, len(vv))
t.Error("GetMulti ERROR") vs, _ = redis.String(vv[0], nil)
} assert.Equal(t, "author", vs)
if v, _ := redis.String(vv[0], nil); v != "author" {
t.Error("GetMulti ERROR") vs, _ = redis.String(vv[1], nil)
} assert.Equal(t, "author1", vs)
if v, _ := redis.String(vv[1], nil); v != "author1" {
t.Error("GetMulti ERROR")
}
vv, _ = bm.GetMulti(context.Background(), []string{"astaxie0", "astaxie1"}) vv, _ = bm.GetMulti(context.Background(), []string{"astaxie0", "astaxie1"})
if vv[0] != nil { assert.Nil(t, vv[0])
t.Error("GetMulti ERROR")
} vs, _ = redis.String(vv[1], nil)
if v, _ := redis.String(vv[1], nil); v != "author1" { assert.Equal(t, "author1", vs)
t.Error("GetMulti ERROR")
}
// test clear all // test clear all
if err = bm.ClearAll(context.Background()); err != nil { assert.Nil(t, bm.ClearAll(context.Background()))
t.Error("clear all err")
}
} }
func TestCache_Scan(t *testing.T) { func TestCache_Scan(t *testing.T) {
@ -137,35 +115,24 @@ func TestCache_Scan(t *testing.T) {
// init // init
bm, err := cache.NewCache("redis", fmt.Sprintf(`{"conn": "%s"}`, addr)) bm, err := cache.NewCache("redis", fmt.Sprintf(`{"conn": "%s"}`, addr))
if err != nil {
t.Error("init err") assert.Nil(t, err)
}
// insert all // insert all
for i := 0; i < 100; i++ { for i := 0; i < 100; i++ {
if err = bm.Put(context.Background(), fmt.Sprintf("astaxie%d", i), fmt.Sprintf("author%d", i), timeoutDuration); err != nil { assert.Nil(t, bm.Put(context.Background(), fmt.Sprintf("astaxie%d", i), fmt.Sprintf("author%d", i), timeoutDuration))
t.Error("set Error", err)
}
} }
time.Sleep(time.Second) time.Sleep(time.Second)
// scan all for the first time // scan all for the first time
keys, err := bm.(*Cache).Scan(DefaultKey + ":*") keys, err := bm.(*Cache).Scan(DefaultKey + ":*")
if err != nil { assert.Nil(t, err)
t.Error("scan Error", err)
}
assert.Equal(t, 100, len(keys), "scan all error") assert.Equal(t, 100, len(keys), "scan all error")
// clear all // clear all
if err = bm.ClearAll(context.Background()); err != nil { assert.Nil(t, bm.ClearAll(context.Background()))
t.Error("clear all err")
}
// scan all for the second time // scan all for the second time
keys, err = bm.(*Cache).Scan(DefaultKey + ":*") keys, err = bm.(*Cache).Scan(DefaultKey + ":*")
if err != nil { assert.Nil(t, err)
t.Error("scan Error", err) assert.Equal(t, 0, len(keys))
}
if len(keys) != 0 {
t.Error("scan all err")
}
} }

View File

@ -53,7 +53,7 @@ func (rc *Cache) GetMulti(ctx context.Context, keys []string) ([]interface{}, er
keysErr := make([]string, 0) keysErr := make([]string, 0)
for i, ki := range keys { for i, ki := range keys {
if _, ok := keyIdx[ki]; !ok { if _, ok := keyIdx[ki]; !ok {
keysErr = append(keysErr, fmt.Sprintf("key [%s] error: %s", ki, "the key isn't exist")) keysErr = append(keysErr, fmt.Sprintf("key [%s] error: %s", ki, "key not exist"))
continue continue
} }
values[i] = res[keyIdx[ki]+1] values[i] = res[keyIdx[ki]+1]

View File

@ -5,9 +5,12 @@ import (
"fmt" "fmt"
"os" "os"
"strconv" "strconv"
"strings"
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert"
"github.com/beego/beego/v2/client/cache" "github.com/beego/beego/v2/client/cache"
) )
@ -19,114 +22,80 @@ func TestSsdbcacheCache(t *testing.T) {
} }
ssdb, err := cache.NewCache("ssdb", fmt.Sprintf(`{"conn": "%s"}`, ssdbAddr)) ssdb, err := cache.NewCache("ssdb", fmt.Sprintf(`{"conn": "%s"}`, ssdbAddr))
if err != nil { assert.Nil(t, err)
t.Error("init err")
}
// test put and exist // test put and exist
if res, _ := ssdb.IsExist(context.Background(), "ssdb"); res { res, _ := ssdb.IsExist(context.Background(), "ssdb")
t.Error("check err") assert.False(t, res)
} timeoutDuration := 3 * time.Second
timeoutDuration := 10 * time.Second
// timeoutDuration := -10*time.Second if timeoutDuration is negtive,it means permanent // timeoutDuration := -10*time.Second if timeoutDuration is negtive,it means permanent
if err = ssdb.Put(context.Background(), "ssdb", "ssdb", timeoutDuration); err != nil {
t.Error("set Error", err) assert.Nil(t, ssdb.Put(context.Background(), "ssdb", "ssdb", timeoutDuration))
}
if res, _ := ssdb.IsExist(context.Background(), "ssdb"); !res { res, _ = ssdb.IsExist(context.Background(), "ssdb")
t.Error("check err") assert.True(t, res)
}
// Get test done // Get test done
if err = ssdb.Put(context.Background(), "ssdb", "ssdb", timeoutDuration); err != nil { assert.Nil(t, ssdb.Put(context.Background(), "ssdb", "ssdb", timeoutDuration))
t.Error("set Error", err)
}
if v, _ := ssdb.Get(context.Background(), "ssdb"); v != "ssdb" { v, _ := ssdb.Get(context.Background(), "ssdb")
t.Error("get Error") assert.Equal(t, "ssdb", v)
}
// inc/dec test done // inc/dec test done
if err = ssdb.Put(context.Background(), "ssdb", "2", timeoutDuration); err != nil { assert.Nil(t, ssdb.Put(context.Background(), "ssdb", "2", timeoutDuration))
t.Error("set Error", err)
} assert.Nil(t, ssdb.Incr(context.Background(), "ssdb"))
if err = ssdb.Incr(context.Background(), "ssdb"); err != nil {
t.Error("incr Error", err)
}
val, _ := ssdb.Get(context.Background(), "ssdb") val, _ := ssdb.Get(context.Background(), "ssdb")
if v, err := strconv.Atoi(val.(string)); err != nil || v != 3 { v, err = strconv.Atoi(val.(string))
t.Error("get err") assert.Nil(t, err)
} assert.Equal(t, 3, v)
if err = ssdb.Decr(context.Background(), "ssdb"); err != nil { assert.Nil(t, ssdb.Decr(context.Background(), "ssdb"))
t.Error("decr error")
}
// test del // test del
if err = ssdb.Put(context.Background(), "ssdb", "3", timeoutDuration); err != nil { assert.Nil(t, ssdb.Put(context.Background(), "ssdb", "3", timeoutDuration))
t.Error("set Error", err)
}
val, _ = ssdb.Get(context.Background(), "ssdb") val, _ = ssdb.Get(context.Background(), "ssdb")
if v, err := strconv.Atoi(val.(string)); err != nil || v != 3 { v, err = strconv.Atoi(val.(string))
t.Error("get err") assert.Equal(t, 3, v)
} assert.Nil(t, err)
if err := ssdb.Delete(context.Background(), "ssdb"); err == nil {
if e, _ := ssdb.IsExist(context.Background(), "ssdb"); e {
t.Error("delete err")
}
}
assert.Nil(t, ssdb.Delete(context.Background(), "ssdb"))
assert.Nil(t, ssdb.Put(context.Background(), "ssdb", "ssdb", -10*time.Second))
// test string // test string
if err = ssdb.Put(context.Background(), "ssdb", "ssdb", -10*time.Second); err != nil {
t.Error("set Error", err) res, _ = ssdb.IsExist(context.Background(), "ssdb")
} assert.True(t, res)
if res, _ := ssdb.IsExist(context.Background(), "ssdb"); !res {
t.Error("check err") v, _ = ssdb.Get(context.Background(), "ssdb")
} assert.Equal(t, "ssdb", v.(string))
if v, _ := ssdb.Get(context.Background(), "ssdb"); v.(string) != "ssdb" {
t.Error("get err")
}
// test GetMulti done // test GetMulti done
if err = ssdb.Put(context.Background(), "ssdb1", "ssdb1", -10*time.Second); err != nil { assert.Nil(t, ssdb.Put(context.Background(), "ssdb1", "ssdb1", -10*time.Second))
t.Error("set Error", err)
} res, _ = ssdb.IsExist(context.Background(), "ssdb1")
if res, _ := ssdb.IsExist(context.Background(), "ssdb1"); !res { assert.True(t, res)
t.Error("check err")
}
vv, _ := ssdb.GetMulti(context.Background(), []string{"ssdb", "ssdb1"}) vv, _ := ssdb.GetMulti(context.Background(), []string{"ssdb", "ssdb1"})
if len(vv) != 2 { assert.Equal(t, 2, len(vv))
t.Error("getmulti error")
} assert.Equal(t, "ssdb", vv[0])
if vv[0].(string) != "ssdb" { assert.Equal(t, "ssdb1", vv[1])
t.Error("getmulti error")
}
if vv[1].(string) != "ssdb1" {
t.Error("getmulti error")
}
vv, err = ssdb.GetMulti(context.Background(), []string{"ssdb", "ssdb11"}) vv, err = ssdb.GetMulti(context.Background(), []string{"ssdb", "ssdb11"})
if len(vv) != 2 {
t.Error("getmulti error") assert.Equal(t, 2, len(vv))
}
if vv[0].(string) != "ssdb" { assert.Equal(t, "ssdb", vv[0])
t.Error("getmulti error") assert.Nil(t, vv[1])
}
if vv[1] != nil { assert.NotNil(t, err)
t.Error("getmulti error") assert.True(t, strings.Contains(err.Error(), "key not exist"))
}
if err != nil && err.Error() != "key [ssdb11] error: the key isn't exist" {
t.Error("getmulti error")
}
// test clear all done // test clear all done
if err = ssdb.ClearAll(context.Background()); err != nil { assert.Nil(t, ssdb.ClearAll(context.Background()))
t.Error("clear all err")
}
e1, _ := ssdb.IsExist(context.Background(), "ssdb") e1, _ := ssdb.IsExist(context.Background(), "ssdb")
e2, _ := ssdb.IsExist(context.Background(), "ssdb1") e2, _ := ssdb.IsExist(context.Background(), "ssdb1")
if e1 || e2 { assert.False(t, e1)
t.Error("check err") assert.False(t, e2)
}
} }

View File

@ -26,7 +26,7 @@ import (
"github.com/beego/beego/v2/client/httplib" "github.com/beego/beego/v2/client/httplib"
) )
func TestFilterChainBuilder_FilterChain(t *testing.T) { func TestFilterChainBuilderFilterChain(t *testing.T) {
next := func(ctx context.Context, req *httplib.BeegoHTTPRequest) (*http.Response, error) { next := func(ctx context.Context, req *httplib.BeegoHTTPRequest) (*http.Response, error) {
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
return &http.Response{ return &http.Response{

View File

@ -25,7 +25,7 @@ import (
"github.com/beego/beego/v2/client/httplib" "github.com/beego/beego/v2/client/httplib"
) )
func TestFilterChainBuilder_FilterChain(t *testing.T) { func TestFilterChainBuilderFilterChain(t *testing.T) {
next := func(ctx context.Context, req *httplib.BeegoHTTPRequest) (*http.Response, error) { next := func(ctx context.Context, req *httplib.BeegoHTTPRequest) (*http.Response, error) {
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
return &http.Response{ return &http.Response{

View File

@ -55,6 +55,7 @@ import (
"github.com/beego/beego/v2/core/logs" "github.com/beego/beego/v2/core/logs"
) )
const contentTypeKey = "Content-Type"
// it will be the last filter and execute request.Do // it will be the last filter and execute request.Do
var doRequestFilter = func(ctx context.Context, req *BeegoHTTPRequest) (*http.Response, error) { var doRequestFilter = func(ctx context.Context, req *BeegoHTTPRequest) (*http.Response, error) {
return req.doRequest(ctx) return req.doRequest(ctx)
@ -311,7 +312,7 @@ func (b *BeegoHTTPRequest) XMLBody(obj interface{}) (*BeegoHTTPRequest, error) {
return ioutil.NopCloser(bytes.NewReader(byts)), nil return ioutil.NopCloser(bytes.NewReader(byts)), nil
} }
b.req.ContentLength = int64(len(byts)) b.req.ContentLength = int64(len(byts))
b.req.Header.Set("Content-Type", "application/xml") b.req.Header.Set(contentTypeKey, "application/xml")
} }
return b, nil return b, nil
} }
@ -325,7 +326,7 @@ func (b *BeegoHTTPRequest) YAMLBody(obj interface{}) (*BeegoHTTPRequest, error)
} }
b.req.Body = ioutil.NopCloser(bytes.NewReader(byts)) b.req.Body = ioutil.NopCloser(bytes.NewReader(byts))
b.req.ContentLength = int64(len(byts)) b.req.ContentLength = int64(len(byts))
b.req.Header.Set("Content-Type", "application/x+yaml") b.req.Header.Set(contentTypeKey, "application/x+yaml")
} }
return b, nil return b, nil
} }
@ -339,7 +340,7 @@ func (b *BeegoHTTPRequest) JSONBody(obj interface{}) (*BeegoHTTPRequest, error)
} }
b.req.Body = ioutil.NopCloser(bytes.NewReader(byts)) b.req.Body = ioutil.NopCloser(bytes.NewReader(byts))
b.req.ContentLength = int64(len(byts)) b.req.ContentLength = int64(len(byts))
b.req.Header.Set("Content-Type", "application/json") b.req.Header.Set(contentTypeKey, "application/json")
} }
return b, nil return b, nil
} }
@ -359,34 +360,38 @@ func (b *BeegoHTTPRequest) buildURL(paramBody string) {
if (b.req.Method == "POST" || b.req.Method == "PUT" || b.req.Method == "PATCH" || b.req.Method == "DELETE") && b.req.Body == nil { if (b.req.Method == "POST" || b.req.Method == "PUT" || b.req.Method == "PATCH" || b.req.Method == "DELETE") && b.req.Body == nil {
// with files // with files
if len(b.files) > 0 { if len(b.files) > 0 {
pr, pw := io.Pipe() b.handleFiles()
bodyWriter := multipart.NewWriter(pw)
go func() {
for formname, filename := range b.files {
b.handleFileToBody(bodyWriter, formname, filename)
}
for k, v := range b.params {
for _, vv := range v {
_ = bodyWriter.WriteField(k, vv)
}
}
_ = bodyWriter.Close()
_ = pw.Close()
}()
b.Header("Content-Type", bodyWriter.FormDataContentType())
b.req.Body = ioutil.NopCloser(pr)
b.Header("Transfer-Encoding", "chunked")
return return
} }
// with params // with params
if len(paramBody) > 0 { if len(paramBody) > 0 {
b.Header("Content-Type", "application/x-www-form-urlencoded") b.Header(contentTypeKey, "application/x-www-form-urlencoded")
b.Body(paramBody) b.Body(paramBody)
} }
} }
} }
func (b *BeegoHTTPRequest) handleFiles() {
pr, pw := io.Pipe()
bodyWriter := multipart.NewWriter(pw)
go func() {
for formname, filename := range b.files {
b.handleFileToBody(bodyWriter, formname, filename)
}
for k, v := range b.params {
for _, vv := range v {
_ = bodyWriter.WriteField(k, vv)
}
}
_ = bodyWriter.Close()
_ = pw.Close()
}()
b.Header(contentTypeKey, bodyWriter.FormDataContentType())
b.req.Body = ioutil.NopCloser(pr)
b.Header("Transfer-Encoding", "chunked")
}
func (b *BeegoHTTPRequest) handleFileToBody(bodyWriter *multipart.Writer, formname string, filename string) { func (b *BeegoHTTPRequest) handleFileToBody(bodyWriter *multipart.Writer, formname string, filename string) {
fileWriter, err := bodyWriter.CreateFormFile(formname, filename) fileWriter, err := bodyWriter.CreateFormFile(formname, filename)
const errFmt = "Httplib: %+v" const errFmt = "Httplib: %+v"

View File

@ -37,7 +37,7 @@ func (lm *LogMsg) OldStyleFormat() string {
msg := lm.Msg msg := lm.Msg
if len(lm.Args) > 0 { if len(lm.Args) > 0 {
lm.Msg = fmt.Sprintf(lm.Msg, lm.Args...) msg = fmt.Sprintf(lm.Msg, lm.Args...)
} }
msg = lm.Prefix + " " + msg msg = lm.Prefix + " " + msg

View File

@ -41,4 +41,8 @@ func TestLogMsg_OldStyleFormat(t *testing.T) {
res = lg.OldStyleFormat() res = lg.OldStyleFormat()
assert.Equal(t, "[D] [/user/home/main.go:13] Cus Hello, world", res) assert.Equal(t, "[D] [/user/home/main.go:13] Cus Hello, world", res)
lg.Msg = "hello, %s"
lg.Args = []interface{}{"world"}
assert.Equal(t, "[D] [/user/home/main.go:13] Cus hello, world", lg.OldStyleFormat())
} }

View File

@ -18,9 +18,10 @@ import (
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func TestBeeLogger_DelLogger(t *testing.T) { func TestBeeLoggerDelLogger(t *testing.T) {
prefix := "My-Cus" prefix := "My-Cus"
l := GetLogger(prefix) l := GetLogger(prefix)
assert.NotNil(t, l) assert.NotNil(t, l)

View File

@ -75,7 +75,7 @@ func initBeforeHTTPRun() {
registerTemplate, registerTemplate,
registerAdmin, registerAdmin,
registerGzip, registerGzip,
registerCommentRouter, // registerCommentRouter,
) )
for _, hk := range hooks { for _, hk := range hooks {

View File

@ -6,8 +6,6 @@ import (
"net/http" "net/http"
"path/filepath" "path/filepath"
"github.com/coreos/etcd/pkg/fileutil"
"github.com/beego/beego/v2/core/logs" "github.com/beego/beego/v2/core/logs"
"github.com/beego/beego/v2/server/web/context" "github.com/beego/beego/v2/server/web/context"
"github.com/beego/beego/v2/server/web/session" "github.com/beego/beego/v2/server/web/session"
@ -98,18 +96,3 @@ func registerGzip() error {
} }
return nil return nil
} }
func registerCommentRouter() error {
if BConfig.RunMode == DEV {
ctrlDir := filepath.Join(WorkPath, BConfig.WebConfig.CommentRouterPath)
if !fileutil.Exist(ctrlDir) {
logs.Warn("controller package not found, won't generate router: ", ctrlDir)
return nil
}
if err := parserPkg(ctrlDir); err != nil {
return err
}
}
return nil
}

View File

@ -1,589 +0,0 @@
// Copyright 2014 beego Author. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package web
import (
"encoding/json"
"errors"
"fmt"
"go/ast"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"unicode"
"golang.org/x/tools/go/packages"
"github.com/beego/beego/v2/core/logs"
"github.com/beego/beego/v2/core/utils"
"github.com/beego/beego/v2/server/web/context/param"
)
var globalRouterTemplate = `package {{.routersDir}}
import (
beego "github.com/beego/beego/v2/server/web"
"github.com/beego/beego/v2/server/web/context/param"{{.globalimport}}
)
func init() {
{{.globalinfo}}
}
`
var (
lastupdateFilename = "lastupdate.tmp"
pkgLastupdate map[string]int64
genInfoList map[string][]ControllerComments
routerHooks = map[string]int{
"beego.BeforeStatic": BeforeStatic,
"beego.BeforeRouter": BeforeRouter,
"beego.BeforeExec": BeforeExec,
"beego.AfterExec": AfterExec,
"beego.FinishRouter": FinishRouter,
}
routerHooksMapping = map[int]string{
BeforeStatic: "beego.BeforeStatic",
BeforeRouter: "beego.BeforeRouter",
BeforeExec: "beego.BeforeExec",
AfterExec: "beego.AfterExec",
FinishRouter: "beego.FinishRouter",
}
)
const commentFilename = "commentsRouter.go"
func init() {
pkgLastupdate = make(map[string]int64)
}
func parserPkg(pkgRealpath string) error {
if !compareFile(pkgRealpath) {
logs.Info(pkgRealpath + " no changed")
return nil
}
genInfoList = make(map[string][]ControllerComments)
pkgs, err := packages.Load(&packages.Config{
Mode: packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedSyntax,
Dir: pkgRealpath,
}, "./...")
if err != nil {
return err
}
for _, pkg := range pkgs {
for _, fl := range pkg.Syntax {
for _, d := range fl.Decls {
switch specDecl := d.(type) {
case *ast.FuncDecl:
if specDecl.Recv != nil {
exp, ok := specDecl.Recv.List[0].Type.(*ast.StarExpr) // Check that the type is correct first beforing throwing to parser
if ok {
err = parserComments(specDecl, fmt.Sprint(exp.X), pkg.PkgPath)
if err != nil {
return err
}
}
}
}
}
}
}
genRouterCode(pkgRealpath)
savetoFile(pkgRealpath)
return nil
}
type parsedComment struct {
routerPath string
methods []string
params map[string]parsedParam
filters []parsedFilter
imports []parsedImport
}
type parsedImport struct {
importPath string
importAlias string
}
type parsedFilter struct {
pattern string
pos int
filter string
params []bool
}
type parsedParam struct {
name string
datatype string
location string
defValue string
required bool
}
func parserComments(f *ast.FuncDecl, controllerName, pkgpath string) error {
if f.Doc != nil {
parsedComments, err := parseComment(f.Doc.List)
if err != nil {
return err
}
for _, parsedComment := range parsedComments {
if parsedComment.routerPath != "" {
key := pkgpath + ":" + controllerName
cc := ControllerComments{}
cc.Method = f.Name.String()
cc.Router = parsedComment.routerPath
cc.AllowHTTPMethods = parsedComment.methods
cc.MethodParams = buildMethodParams(f.Type.Params.List, parsedComment)
cc.FilterComments = buildFilters(parsedComment.filters)
cc.ImportComments = buildImports(parsedComment.imports)
genInfoList[key] = append(genInfoList[key], cc)
}
}
}
return nil
}
func buildImports(pis []parsedImport) []*ControllerImportComments {
var importComments []*ControllerImportComments
for _, pi := range pis {
importComments = append(importComments, &ControllerImportComments{
ImportPath: pi.importPath,
ImportAlias: pi.importAlias,
})
}
return importComments
}
func buildFilters(pfs []parsedFilter) []*ControllerFilterComments {
var filterComments []*ControllerFilterComments
for _, pf := range pfs {
var (
returnOnOutput bool
resetParams bool
)
if len(pf.params) >= 1 {
returnOnOutput = pf.params[0]
}
if len(pf.params) >= 2 {
resetParams = pf.params[1]
}
filterComments = append(filterComments, &ControllerFilterComments{
Filter: pf.filter,
Pattern: pf.pattern,
Pos: pf.pos,
ReturnOnOutput: returnOnOutput,
ResetParams: resetParams,
})
}
return filterComments
}
func buildMethodParams(funcParams []*ast.Field, pc *parsedComment) []*param.MethodParam {
result := make([]*param.MethodParam, 0, len(funcParams))
for _, fparam := range funcParams {
for _, pName := range fparam.Names {
methodParam := buildMethodParam(fparam, pName.Name, pc)
result = append(result, methodParam)
}
}
return result
}
func buildMethodParam(fparam *ast.Field, name string, pc *parsedComment) *param.MethodParam {
options := []param.MethodParamOption{}
if cparam, ok := pc.params[name]; ok {
// Build param from comment info
name = cparam.name
if cparam.required {
options = append(options, param.IsRequired)
}
switch cparam.location {
case "body":
options = append(options, param.InBody)
case "header":
options = append(options, param.InHeader)
case "path":
options = append(options, param.InPath)
}
if cparam.defValue != "" {
options = append(options, param.Default(cparam.defValue))
}
} else {
if paramInPath(name, pc.routerPath) {
options = append(options, param.InPath)
}
}
return param.New(name, options...)
}
func paramInPath(name, route string) bool {
return strings.HasSuffix(route, ":"+name) ||
strings.Contains(route, ":"+name+"/")
}
var routeRegex = regexp.MustCompile(`@router\s+(\S+)(?:\s+\[(\S+)\])?`)
func parseComment(lines []*ast.Comment) (pcs []*parsedComment, err error) {
pcs = []*parsedComment{}
params := map[string]parsedParam{}
filters := []parsedFilter{}
imports := []parsedImport{}
for _, c := range lines {
t := strings.TrimSpace(strings.TrimLeft(c.Text, "//"))
if strings.HasPrefix(t, "@Param") {
pv := getparams(strings.TrimSpace(strings.TrimLeft(t, "@Param")))
if len(pv) < 4 {
logs.Error("Invalid @Param format. Needs at least 4 parameters")
}
p := parsedParam{}
names := strings.SplitN(pv[0], "=>", 2)
p.name = names[0]
funcParamName := p.name
if len(names) > 1 {
funcParamName = names[1]
}
p.location = pv[1]
p.datatype = pv[2]
switch len(pv) {
case 5:
p.required, _ = strconv.ParseBool(pv[3])
case 6:
p.defValue = pv[3]
p.required, _ = strconv.ParseBool(pv[4])
}
params[funcParamName] = p
}
}
for _, c := range lines {
t := strings.TrimSpace(strings.TrimLeft(c.Text, "//"))
if strings.HasPrefix(t, "@Import") {
iv := getparams(strings.TrimSpace(strings.TrimLeft(t, "@Import")))
if len(iv) == 0 || len(iv) > 2 {
logs.Error("Invalid @Import format. Only accepts 1 or 2 parameters")
continue
}
p := parsedImport{}
p.importPath = iv[0]
if len(iv) == 2 {
p.importAlias = iv[1]
}
imports = append(imports, p)
}
}
filterLoop:
for _, c := range lines {
t := strings.TrimSpace(strings.TrimLeft(c.Text, "//"))
if strings.HasPrefix(t, "@Filter") {
fv := getparams(strings.TrimSpace(strings.TrimLeft(t, "@Filter")))
if len(fv) < 3 {
logs.Error("Invalid @Filter format. Needs at least 3 parameters")
continue filterLoop
}
p := parsedFilter{}
p.pattern = fv[0]
posName := fv[1]
if pos, exists := routerHooks[posName]; exists {
p.pos = pos
} else {
logs.Error("Invalid @Filter pos: ", posName)
continue filterLoop
}
p.filter = fv[2]
fvParams := fv[3:]
for _, fvParam := range fvParams {
switch fvParam {
case "true":
p.params = append(p.params, true)
case "false":
p.params = append(p.params, false)
default:
logs.Error("Invalid @Filter param: ", fvParam)
continue filterLoop
}
}
filters = append(filters, p)
}
}
for _, c := range lines {
var pc = &parsedComment{}
pc.params = params
pc.filters = filters
pc.imports = imports
t := strings.TrimSpace(strings.TrimLeft(c.Text, "//"))
if strings.HasPrefix(t, "@router") {
t := strings.TrimSpace(strings.TrimLeft(c.Text, "//"))
matches := routeRegex.FindStringSubmatch(t)
if len(matches) == 3 {
pc.routerPath = matches[1]
methods := matches[2]
if methods == "" {
pc.methods = []string{"get"}
// pc.hasGet = true
} else {
pc.methods = strings.Split(methods, ",")
// pc.hasGet = strings.Contains(methods, "get")
}
pcs = append(pcs, pc)
} else {
return nil, errors.New("Router information is missing")
}
}
}
return
}
// direct copy from bee\g_docs.go
// analysis params return []string
// @Param query form string true "The email for login"
// [query form string true "The email for login"]
func getparams(str string) []string {
var s []rune
var j int
var start bool
var r []string
var quoted int8
for _, c := range str {
if unicode.IsSpace(c) && quoted == 0 {
if !start {
continue
} else {
start = false
j++
r = append(r, string(s))
s = make([]rune, 0)
continue
}
}
start = true
if c == '"' {
quoted ^= 1
continue
}
s = append(s, c)
}
if len(s) > 0 {
r = append(r, string(s))
}
return r
}
func genRouterCode(pkgRealpath string) {
os.Mkdir(getRouterDir(pkgRealpath), 0755)
logs.Info("generate router from comments")
var (
globalinfo string
globalimport string
sortKey []string
)
for k := range genInfoList {
sortKey = append(sortKey, k)
}
sort.Strings(sortKey)
for _, k := range sortKey {
cList := genInfoList[k]
sort.Sort(ControllerCommentsSlice(cList))
for _, c := range cList {
allmethod := "nil"
if len(c.AllowHTTPMethods) > 0 {
allmethod = "[]string{"
for _, m := range c.AllowHTTPMethods {
allmethod += `"` + m + `",`
}
allmethod = strings.TrimRight(allmethod, ",") + "}"
}
params := "nil"
if len(c.Params) > 0 {
params = "[]map[string]string{"
for _, p := range c.Params {
for k, v := range p {
params = params + `map[string]string{` + k + `:"` + v + `"},`
}
}
params = strings.TrimRight(params, ",") + "}"
}
methodParams := "param.Make("
if len(c.MethodParams) > 0 {
lines := make([]string, 0, len(c.MethodParams))
for _, m := range c.MethodParams {
lines = append(lines, fmt.Sprint(m))
}
methodParams += "\n " +
strings.Join(lines, ",\n ") +
",\n "
}
methodParams += ")"
imports := ""
if len(c.ImportComments) > 0 {
for _, i := range c.ImportComments {
var s string
if i.ImportAlias != "" {
s = fmt.Sprintf(`
%s "%s"`, i.ImportAlias, i.ImportPath)
} else {
s = fmt.Sprintf(`
"%s"`, i.ImportPath)
}
if !strings.Contains(globalimport, s) {
imports += s
}
}
}
filters := ""
if len(c.FilterComments) > 0 {
for _, f := range c.FilterComments {
filters += fmt.Sprintf(` &beego.ControllerFilter{
Pattern: "%s",
Pos: %s,
Filter: %s,
ReturnOnOutput: %v,
ResetParams: %v,
},`, f.Pattern, routerHooksMapping[f.Pos], f.Filter, f.ReturnOnOutput, f.ResetParams)
}
}
if filters == "" {
filters = "nil"
} else {
filters = fmt.Sprintf(`[]*beego.ControllerFilter{
%s
}`, filters)
}
globalimport += imports
globalinfo = globalinfo + `
beego.GlobalControllerRouter["` + k + `"] = append(beego.GlobalControllerRouter["` + k + `"],
beego.ControllerComments{
Method: "` + strings.TrimSpace(c.Method) + `",
` + "Router: `" + c.Router + "`" + `,
AllowHTTPMethods: ` + allmethod + `,
MethodParams: ` + methodParams + `,
Filters: ` + filters + `,
Params: ` + params + `})
`
}
}
if globalinfo != "" {
f, err := os.Create(filepath.Join(getRouterDir(pkgRealpath), commentFilename))
if err != nil {
panic(err)
}
defer f.Close()
routersDir := AppConfig.DefaultString("routersdir", "routers")
content := strings.Replace(globalRouterTemplate, "{{.globalinfo}}", globalinfo, -1)
content = strings.Replace(content, "{{.routersDir}}", routersDir, -1)
content = strings.Replace(content, "{{.globalimport}}", globalimport, -1)
f.WriteString(content)
}
}
func compareFile(pkgRealpath string) bool {
if !utils.FileExists(filepath.Join(getRouterDir(pkgRealpath), commentFilename)) {
return true
}
if utils.FileExists(lastupdateFilename) {
content, err := ioutil.ReadFile(lastupdateFilename)
if err != nil {
return true
}
json.Unmarshal(content, &pkgLastupdate)
lastupdate, err := getpathTime(pkgRealpath)
if err != nil {
return true
}
if v, ok := pkgLastupdate[pkgRealpath]; ok {
if lastupdate <= v {
return false
}
}
}
return true
}
func savetoFile(pkgRealpath string) {
lastupdate, err := getpathTime(pkgRealpath)
if err != nil {
return
}
pkgLastupdate[pkgRealpath] = lastupdate
d, err := json.Marshal(pkgLastupdate)
if err != nil {
return
}
ioutil.WriteFile(lastupdateFilename, d, os.ModePerm)
}
func getpathTime(pkgRealpath string) (lastupdate int64, err error) {
fl, err := ioutil.ReadDir(pkgRealpath)
if err != nil {
return lastupdate, err
}
for _, f := range fl {
var t int64
if f.IsDir() {
t, err = getpathTime(filepath.Join(pkgRealpath, f.Name()))
if err != nil {
return lastupdate, err
}
} else {
t = f.ModTime().UnixNano()
}
if lastupdate < t {
lastupdate = t
}
}
return lastupdate, nil
}
func getRouterDir(pkgRealpath string) string {
dir := filepath.Dir(pkgRealpath)
routersDir := AppConfig.DefaultString("routersdir", "routers")
return filepath.Join(dir, routersDir)
}

View File

@ -1,34 +0,0 @@
// Copyright 2020 beego
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package web
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
)
func Test_getRouterDir(t *testing.T) {
pkg := filepath.Dir(os.TempDir())
res := getRouterDir(pkg)
assert.Equal(t, filepath.Join(pkg, "routers"), res)
AppConfig.Set("routersdir", "cus_routers")
res = getRouterDir(pkg)
assert.Equal(t, filepath.Join(pkg, "cus_routers"), res)
}