diff --git a/CHANGELOG.md b/CHANGELOG.md index 1d0d390f..0548b40a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,4 +23,5 @@ ## Fix Sonar -- [4473](https://github.com/beego/beego/pull/4473) \ No newline at end of file +- [4473](https://github.com/beego/beego/pull/4473) +- [4474](https://github.com/beego/beego/pull/4474) \ No newline at end of file diff --git a/adapter/cache/cache_test.go b/adapter/cache/cache_test.go index 382a3743..261e1e5e 100644 --- a/adapter/cache/cache_test.go +++ b/adapter/cache/cache_test.go @@ -19,6 +19,8 @@ import ( "sync" "testing" "time" + + "github.com/stretchr/testify/assert" ) const ( @@ -53,147 +55,95 @@ func TestCacheIncr(t *testing.T) { func TestCache(t *testing.T) { 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 { - t.Error(getError) - } + assert.Nil(t, err) - time.Sleep(30 * time.Second) + timeoutDuration := 5 * time.Second + err = bm.Put("astaxie", 1, timeoutDuration) + assert.Nil(t, err) - if bm.IsExist("astaxie") { - t.Error(checkError) - } + assert.True(t, bm.IsExist("astaxie")) - if err = bm.Put("astaxie", 1, timeoutDuration); err != nil { - t.Error(setError, err) - } + assert.Equal(t, 1, bm.Get("astaxie")) - if err = bm.Incr("astaxie"); err != nil { - t.Error("Incr Error", err) - } + time.Sleep(10 * time.Second) - if v := bm.Get("astaxie"); v.(int) != 2 { - t.Error(getError) - } + assert.False(t, bm.IsExist("astaxie")) - if err = bm.Decr("astaxie"); err != nil { - t.Error("Decr Error", err) - } + err = bm.Put("astaxie", 1, timeoutDuration) + assert.Nil(t, err) - if v := bm.Get("astaxie"); v.(int) != 1 { - t.Error(getError) - } - bm.Delete("astaxie") - if bm.IsExist("astaxie") { - t.Error("delete err") - } + err = bm.Incr("astaxie") + assert.Nil(t, err) - // test GetMulti - 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) - } + assert.Equal(t, 2, bm.Get("astaxie")) - if err = bm.Put("astaxie1", "author1", timeoutDuration); err != nil { - t.Error(setError, err) - } - if !bm.IsExist("astaxie1") { - t.Error(checkError) - } + assert.Nil(t, bm.Decr("astaxie")) + + assert.Equal(t, 1, bm.Get("astaxie")) + + 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"}) - if len(vv) != 2 { - t.Error(getMultiError) - } - if vv[0].(string) != "author" { - t.Error(getMultiError) - } - if vv[1].(string) != "author1" { - t.Error(getMultiError) - } + + assert.Equal(t, 2, len(vv)) + + + assert.Equal(t, "author", vv[0]) + + assert.Equal(t, "author1", vv[1]) } func TestFileCache(t *testing.T) { 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 { - t.Error(getError) - } + assert.Nil(t, err) + timeoutDuration := 5 * time.Second - if err = bm.Incr("astaxie"); err != nil { - t.Error("Incr Error", err) - } + assert.Nil(t, bm.Put("astaxie", 1, timeoutDuration)) - if v := bm.Get("astaxie"); v.(int) != 2 { - t.Error(getError) - } + assert.True(t, bm.IsExist("astaxie")) - if err = bm.Decr("astaxie"); err != nil { - t.Error("Decr Error", err) - } + assert.Equal(t, 1, bm.Get("astaxie")) - if v := bm.Get("astaxie"); v.(int) != 1 { - t.Error(getError) - } - bm.Delete("astaxie") - if bm.IsExist("astaxie") { - t.Error("delete err") - } + assert.Nil(t, bm.Incr("astaxie")) - // test string - 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) - } + assert.Equal(t, 2, bm.Get("astaxie")) - // test GetMulti - if err = bm.Put("astaxie1", "author1", timeoutDuration); err != nil { - t.Error(setError, err) - } - if !bm.IsExist("astaxie1") { - t.Error(checkError) - } + assert.Nil(t, bm.Decr("astaxie")) + + assert.Equal(t, 1, bm.Get("astaxie")) + 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"}) - 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")) } diff --git a/adapter/cache/memcache/memcache_test.go b/adapter/cache/memcache/memcache_test.go index ae0c6df7..1660a4a6 100644 --- a/adapter/cache/memcache/memcache_test.go +++ b/adapter/cache/memcache/memcache_test.go @@ -21,6 +21,8 @@ import ( "testing" "time" + "github.com/stretchr/testify/assert" + "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)) - 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) - } + assert.Nil(t, err) + timeoutDuration := 5 * time.Second + + assert.Nil(t, bm.Put("astaxie", "1", timeoutDuration)) + + assert.True(t, bm.IsExist("astaxie")) time.Sleep(11 * time.Second) - if bm.IsExist("astaxie") { - t.Error(checkError) - } - if err = bm.Put("astaxie", "1", timeoutDuration); err != nil { - t.Error(setError, err) - } + assert.False(t, bm.IsExist("astaxie")) - if v, err := strconv.Atoi(string(bm.Get("astaxie").([]byte))); err != nil || v != 1 { - t.Error(getError) - } + assert.Nil(t, bm.Put("astaxie", "1", timeoutDuration)) + 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 { - t.Error("Incr Error", err) - } + assert.Nil(t, bm.Incr("astaxie")) - if v, err := strconv.Atoi(string(bm.Get("astaxie").([]byte))); err != nil || v != 2 { - t.Error(getError) - } + v, err = strconv.Atoi(string(bm.Get("astaxie").([]byte))) + assert.Nil(t, err) + assert.Equal(t, 2, v) - if err = bm.Decr("astaxie"); err != nil { - t.Error("Decr Error", err) - } + assert.Nil(t, bm.Decr("astaxie")) - if v, err := strconv.Atoi(string(bm.Get("astaxie").([]byte))); err != nil || v != 1 { - t.Error(getError) - } - bm.Delete("astaxie") - if bm.IsExist("astaxie") { - t.Error("delete err") - } + v, err = strconv.Atoi(string(bm.Get("astaxie").([]byte))) + assert.Nil(t, err) + assert.Equal(t, 1, v) - // test string - if err = bm.Put("astaxie", "author", timeoutDuration); err != nil { - t.Error(setError, err) - } - if !bm.IsExist("astaxie") { - t.Error(checkError) - } + assert.Nil(t, bm.Delete("astaxie")) - if v := bm.Get("astaxie").([]byte); string(v) != "author" { - t.Error(getError) - } + assert.False(t, bm.IsExist("astaxie")) - // test GetMulti - if err = bm.Put("astaxie1", "author1", timeoutDuration); err != nil { - t.Error(setError, err) - } - if !bm.IsExist("astaxie1") { - t.Error(checkError) - } + assert.Nil(t, bm.Put("astaxie", "author", timeoutDuration)) + + assert.True(t, bm.IsExist("astaxie")) + + assert.Equal(t, []byte("author"), bm.Get("astaxie")) + + assert.Nil(t, bm.Put("astaxie1", "author1", timeoutDuration)) + + assert.True(t, bm.IsExist("astaxie1")) vv := bm.GetMulti([]string{"astaxie", "astaxie1"}) - if len(vv) != 2 { - t.Error(getMultiError) - } - 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) - } + assert.Equal(t, 2, len(vv)) + assert.Equal(t, "author", vv[0]) + assert.Equal(t, "author1", vv[1]) - // test clear all - if err = bm.ClearAll(); err != nil { - t.Error("clear all err") - } + assert.Nil(t, bm.ClearAll()) } diff --git a/adapter/cache/redis/redis_test.go b/adapter/cache/redis/redis_test.go index 781489be..02c54790 100644 --- a/adapter/cache/redis/redis_test.go +++ b/adapter/cache/redis/redis_test.go @@ -21,6 +21,7 @@ import ( "time" "github.com/gomodule/redigo/redis" + "github.com/stretchr/testify/assert" "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)) - 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) - } + assert.Nil(t, err) + timeoutDuration := 5 * time.Second - time.Sleep(11 * time.Second) + assert.Nil(t, bm.Put("astaxie", 1, timeoutDuration)) - if bm.IsExist("astaxie") { - t.Error(checkError) - } - if err = bm.Put("astaxie", 1, timeoutDuration); err != nil { - t.Error(setError, err) - } + assert.True(t, bm.IsExist("astaxie")) - if v, _ := redis.Int(bm.Get("astaxie"), err); v != 1 { - t.Error(getError) - } + time.Sleep(7 * time.Second) - if err = bm.Incr("astaxie"); err != nil { - t.Error("Incr Error", err) - } + assert.False(t, bm.IsExist("astaxie")) - if v, _ := redis.Int(bm.Get("astaxie"), err); v != 2 { - t.Error(getError) - } + assert.Nil(t, bm.Put("astaxie", 1, timeoutDuration)) - if err = bm.Decr("astaxie"); err != nil { - t.Error("Decr Error", err) - } + v, err := redis.Int(bm.Get("astaxie"), err) + assert.Nil(t, err) + assert.Equal(t, 1, v) - if v, _ := redis.Int(bm.Get("astaxie"), err); v != 1 { - t.Error(getError) - } - bm.Delete("astaxie") - if bm.IsExist("astaxie") { - t.Error("delete err") - } + assert.Nil(t, bm.Incr("astaxie")) - // test string - if err = bm.Put("astaxie", "author", timeoutDuration); err != nil { - t.Error(setError, err) - } - if !bm.IsExist("astaxie") { - t.Error(checkError) - } + v, err = redis.Int(bm.Get("astaxie"), err) + assert.Nil(t, err) + assert.Equal(t, 2, v) - if v, _ := redis.String(bm.Get("astaxie"), err); v != "author" { - t.Error(getError) - } + assert.Nil(t, bm.Decr("astaxie")) - // test GetMulti - if err = bm.Put("astaxie1", "author1", timeoutDuration); err != nil { - t.Error(setError, err) - } - if !bm.IsExist("astaxie1") { - t.Error(checkError) - } + v, err = redis.Int(bm.Get("astaxie"), err) + assert.Nil(t, err) + assert.Equal(t, 1, v) + + 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")) + + 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.False(t, bm.IsExist("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 - 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 // init bm, err := cache.NewCache("redis", `{"conn": "127.0.0.1:6379"}`) diff --git a/adapter/cache/ssdb/ssdb_test.go b/adapter/cache/ssdb/ssdb_test.go index f2f72f81..a9c530de 100644 --- a/adapter/cache/ssdb/ssdb_test.go +++ b/adapter/cache/ssdb/ssdb_test.go @@ -7,6 +7,8 @@ import ( "testing" "time" + "github.com/stretchr/testify/assert" + "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)) - if err != nil { - t.Error(initError) - } + assert.Nil(t, err) + + assert.False(t, ssdb.IsExist("ssdb")) // test put and exist - if ssdb.IsExist("ssdb") { - t.Error(checkError) - } - timeoutDuration := 10 * time.Second + timeoutDuration := 3 * time.Second // timeoutDuration := -10*time.Second if timeoutDuration is negtive,it means permanent - if err = ssdb.Put("ssdb", "ssdb", timeoutDuration); err != nil { - t.Error(setError, err) - } - if !ssdb.IsExist("ssdb") { - t.Error(checkError) - } + assert.Nil(t, ssdb.Put("ssdb", "ssdb", timeoutDuration)) + assert.True(t, ssdb.IsExist("ssdb")) - // Get test done - if err = ssdb.Put("ssdb", "ssdb", timeoutDuration); err != nil { - t.Error(setError, err) - } + assert.NotNil(t, ssdb.Put("ssdb", "ssdb", timeoutDuration)) - if v := ssdb.Get("ssdb"); v != "ssdb" { - t.Error("get Error") - } + assert.Equal(t, "ssdb", ssdb.Get("ssdb")) // inc/dec test done - if err = ssdb.Put("ssdb", "2", timeoutDuration); err != nil { - t.Error(setError, err) - } - if err = ssdb.Incr("ssdb"); err != nil { - t.Error("incr Error", err) - } + assert.Nil(t, ssdb.Put("ssdb", "2", timeoutDuration)) - if v, err := strconv.Atoi(ssdb.Get("ssdb").(string)); err != nil || v != 3 { - t.Error(getError) - } + assert.Nil(t, ssdb.Incr("ssdb")) - if err = ssdb.Decr("ssdb"); err != nil { - t.Error("decr error") - } + v, err := strconv.Atoi(ssdb.Get("ssdb").(string)) + 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 - if err = ssdb.Put("ssdb", "3", timeoutDuration); err != nil { - t.Error(setError, err) - } - if v, err := strconv.Atoi(ssdb.Get("ssdb").(string)); err != nil || v != 3 { - t.Error(getError) - } - if err := ssdb.Delete("ssdb"); err == nil { - if ssdb.IsExist("ssdb") { - t.Error("delete err") - } - } + v, err = strconv.Atoi(ssdb.Get("ssdb").(string)) + assert.Nil(t, err) + assert.Equal(t, 3, v) + + assert.Nil(t, ssdb.Delete("ssdb")) + assert.False(t, ssdb.IsExist("ssdb")) // test string - if err = ssdb.Put("ssdb", "ssdb", -10*time.Second); err != nil { - t.Error(setError, err) - } - if !ssdb.IsExist("ssdb") { - t.Error(checkError) - } - if v := ssdb.Get("ssdb").(string); v != "ssdb" { - t.Error(getError) - } + assert.Nil(t, ssdb.Put("ssdb", "ssdb", -10*time.Second)) + + assert.True(t, ssdb.IsExist("ssdb")) + assert.Equal(t, "ssdb", ssdb.Get("ssdb")) // test GetMulti done - if err = ssdb.Put("ssdb1", "ssdb1", -10*time.Second); err != nil { - t.Error(setError, err) - } - 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) - } + assert.Nil(t, ssdb.Put("ssdb1", "ssdb1", -10*time.Second)) + assert.True(t, ssdb.IsExist("ssdb1") ) + 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 - if err = ssdb.ClearAll(); err != nil { - t.Error("clear all err") - } - if ssdb.IsExist("ssdb") || ssdb.IsExist("ssdb1") { - t.Error(checkError) - } } diff --git a/adapter/config/json_test.go b/adapter/config/json_test.go index b3c75dc1..f0076f2a 100644 --- a/adapter/config/json_test.go +++ b/adapter/config/json_test.go @@ -18,6 +18,8 @@ import ( "fmt" "os" "testing" + + "github.com/stretchr/testify/assert" ) func TestJsonStartsWithArray(t *testing.T) { @@ -169,56 +171,39 @@ func TestJson(t *testing.T) { default: 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) - } - } - if err = jsonconf.Set("name", "astaxie"); err != nil { - t.Fatal(err) - } - if jsonconf.String("name") != "astaxie" { - t.Fatal("get name error") + assert.Nil(t, err) + assert.Equal(t, fmt.Sprintf("%v", v), fmt.Sprintf("%v", value)) } - if db, err := jsonconf.DIY("database"); err != nil { - 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") - } - } + assert.Nil(t, jsonconf.Set("name", "astaxie")) - if _, err := jsonconf.Int("unknown"); err == nil { - t.Error("unknown keys should return an error when expecting an Int") - } + assert.Equal(t, "astaxie", jsonconf.String("name")) - if _, err := jsonconf.Int64("unknown"); err == nil { - t.Error("unknown keys should return an error when expecting an Int64") - } + db, err := jsonconf.DIY("database") + assert.Nil(t, err) - if _, err := jsonconf.Float("unknown"); err == nil { - t.Error("unknown keys should return an error when expecting a Float") - } + m, ok := db.(map[string]interface{}) + assert.True(t, ok) + assert.Equal(t,"host" , m["host"]) - if _, err := jsonconf.DIY("unknown"); err == nil { - t.Error("unknown keys should return an error when expecting an interface{}") - } + _, err = jsonconf.Int("unknown") + assert.NotNil(t, err) - if val := jsonconf.String("unknown"); val != "" { - t.Error("unknown keys should return an empty string when expecting a String") - } + _, err = jsonconf.Int64("unknown") + assert.NotNil(t, err) - if _, err := jsonconf.Bool("unknown"); err == nil { - t.Error("unknown keys should return an error when expecting a Bool") - } + _, err = jsonconf.Float("unknown") + assert.NotNil(t, err) - if !jsonconf.DefaultBool("unknown", true) { - t.Error("unknown keys with default value wrong") - } + _, err = jsonconf.DIY("unknown") + 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)) } diff --git a/adapter/context/param/methodparams_test.go b/adapter/context/param/methodparams_test.go index b240d087..9d5155bf 100644 --- a/adapter/context/param/methodparams_test.go +++ b/adapter/context/param/methodparams_test.go @@ -20,7 +20,7 @@ import ( "github.com/stretchr/testify/assert" ) -func TestMethodParam_String(t *testing.T) { +func TestMethodParamString(t *testing.T) { method := New("myName", IsRequired, InHeader, Default("abc")) s := method.String() assert.Equal(t, `param.New("myName", param.IsRequired, param.InHeader, param.Default("abc"))`, s) diff --git a/adapter/httplib/httplib_test.go b/adapter/httplib/httplib_test.go index e7605c87..350f716e 100644 --- a/adapter/httplib/httplib_test.go +++ b/adapter/httplib/httplib_test.go @@ -25,8 +25,11 @@ import ( "time" ) +const getUrl = "http://httpbin.org/get" +const ipUrl = "http://httpbin.org/ip" + func TestResponse(t *testing.T) { - req := Get("http://httpbin.org/get") + req := Get(getUrl) resp, err := req.Response() if err != nil { t.Fatal(err) @@ -63,7 +66,8 @@ func TestDoRequest(t *testing.T) { } func TestGet(t *testing.T) { - req := Get("http://httpbin.org/get") + + req := Get(getUrl) b, err := req.Bytes() if err != nil { t.Fatal(err) @@ -205,7 +209,7 @@ func TestWithSetting(t *testing.T) { setting.ReadWriteTimeout = 5 * time.Second SetDefaultSetting(setting) - str, err := Get("http://httpbin.org/get").String() + str, err := Get(getUrl).String() if err != nil { t.Fatal(err) } @@ -218,7 +222,8 @@ func TestWithSetting(t *testing.T) { } func TestToJson(t *testing.T) { - req := Get("http://httpbin.org/ip") + + req := Get(ipUrl) resp, err := req.Response() if err != nil { t.Fatal(err) @@ -249,7 +254,7 @@ func TestToJson(t *testing.T) { func TestToFile(t *testing.T) { f := "beego_testfile" - req := Get("http://httpbin.org/ip") + req := Get(ipUrl) err := req.ToFile(f) if err != nil { t.Fatal(err) @@ -263,7 +268,7 @@ func TestToFile(t *testing.T) { func TestToFileDir(t *testing.T) { f := "./files/beego_testfile" - req := Get("http://httpbin.org/ip") + req := Get(ipUrl) err := req.ToFile(f) if err != nil { t.Fatal(err) diff --git a/adapter/logs/logger_test.go b/adapter/logs/logger_test.go index 9f2cc5a5..42708fa5 100644 --- a/adapter/logs/logger_test.go +++ b/adapter/logs/logger_test.go @@ -18,7 +18,7 @@ import ( "testing" ) -func TestBeeLogger_Info(t *testing.T) { +func TestBeeLoggerInfo(t *testing.T) { log := NewLogger(1000) log.SetLogger("file", `{"net":"tcp","addr":":7020"}`) } diff --git a/adapter/metric/prometheus_test.go b/adapter/metric/prometheus_test.go index 53984845..72212dd4 100644 --- a/adapter/metric/prometheus_test.go +++ b/adapter/metric/prometheus_test.go @@ -15,6 +15,7 @@ package metric import ( + "fmt" "net/http" "net/url" "testing" @@ -26,7 +27,9 @@ import ( ) 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{} request := &http.Request{ URL: &url.URL{ diff --git a/adapter/orm/query_setter_adapter.go b/adapter/orm/query_setter_adapter.go index 7f506759..edea0a15 100644 --- a/adapter/orm/query_setter_adapter.go +++ b/adapter/orm/query_setter_adapter.go @@ -21,14 +21,16 @@ import ( type baseQuerySetter struct { } +const shouldNotInvoke = "you should not invoke this method." + 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 { - panic("you should not invoke this method.") + panic(shouldNotInvoke) } func (b *baseQuerySetter) IgnoreIndex(indexes ...string) orm.QuerySeter { - panic("you should not invoke this method.") + panic(shouldNotInvoke) } diff --git a/adapter/orm/utils_test.go b/adapter/orm/utils_test.go index 7d94cada..fbf8663e 100644 --- a/adapter/orm/utils_test.go +++ b/adapter/orm/utils_test.go @@ -16,6 +16,8 @@ package orm import ( "testing" + + "github.com/stretchr/testify/assert" ) func TestCamelString(t *testing.T) { @@ -29,9 +31,7 @@ func TestCamelString(t *testing.T) { for _, v := range snake { res := camelString(v) - if res != answer[v] { - t.Error("Unit Test Fail:", v, res, answer[v]) - } + assert.Equal(t, answer[v], res) } } @@ -46,9 +46,7 @@ func TestSnakeString(t *testing.T) { for _, v := range camel { res := snakeString(v) - if res != answer[v] { - t.Error("Unit Test Fail:", v, res, answer[v]) - } + assert.Equal(t, answer[v], res) } } @@ -63,8 +61,6 @@ func TestSnakeStringWithAcronym(t *testing.T) { for _, v := range camel { res := snakeStringWithAcronym(v) - if res != answer[v] { - t.Error("Unit Test Fail:", v, res, answer[v]) - } + assert.Equal(t, answer[v], res) } } diff --git a/adapter/plugins/authz/authz_test.go b/adapter/plugins/authz/authz_test.go index fa5410ca..4963ceab 100644 --- a/adapter/plugins/authz/authz_test.go +++ b/adapter/plugins/authz/authz_test.go @@ -26,6 +26,11 @@ import ( "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) { r, _ := http.NewRequest(method, path, nil) r.SetBasicAuth(user, "123") @@ -40,70 +45,79 @@ func testRequest(t *testing.T, handler *beego.ControllerRegister, user string, p func TestBasic(t *testing.T) { handler := beego.NewControllerRegister() - 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, auth.Basic("alice", "123")) + + _ = handler.InsertFilter("*", beego.BeforeRouter, NewAuthorizer(casbin.NewEnforcer(authCfg, authCsv))) handler.Any("*", func(ctx *context.Context) { ctx.Output.SetStatus(200) }) - testRequest(t, handler, "alice", "/dataset1/resource1", "GET", 200) - testRequest(t, handler, "alice", "/dataset1/resource1", "POST", 200) - testRequest(t, handler, "alice", "/dataset1/resource2", "GET", 200) - testRequest(t, handler, "alice", "/dataset1/resource2", "POST", 403) + const d1r1 = "/dataset1/resource1" + testRequest(t, handler, "alice", d1r1, "GET", 200) + testRequest(t, handler, "alice", d1r1, "POST", 200) + const d1r2 = "/dataset1/resource2" + testRequest(t, handler, "alice", d1r2, "GET", 200) + testRequest(t, handler, "alice", d1r2, "POST", 403) } func TestPathWildcard(t *testing.T) { handler := beego.NewControllerRegister() - 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, auth.Basic("bob", "123")) + _ = handler.InsertFilter("*", beego.BeforeRouter, NewAuthorizer(casbin.NewEnforcer(authCfg, authCsv))) handler.Any("*", func(ctx *context.Context) { ctx.Output.SetStatus(200) }) - testRequest(t, handler, "bob", "/dataset2/resource1", "GET", 200) - testRequest(t, handler, "bob", "/dataset2/resource1", "POST", 200) - testRequest(t, handler, "bob", "/dataset2/resource1", "DELETE", 200) - testRequest(t, handler, "bob", "/dataset2/resource2", "GET", 200) - testRequest(t, handler, "bob", "/dataset2/resource2", "POST", 403) - testRequest(t, handler, "bob", "/dataset2/resource2", "DELETE", 403) + const d2r1 = "/dataset2/resource1" + testRequest(t, handler, "bob", d2r1, "GET", 200) + testRequest(t, handler, "bob", d2r1, "POST", 200) + testRequest(t, handler, "bob", d2r1, "DELETE", 200) + const d2r2 = "/dataset2/resource2" + 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) - testRequest(t, handler, "bob", "/dataset2/folder1/item1", "POST", 200) - testRequest(t, handler, "bob", "/dataset2/folder1/item1", "DELETE", 403) - testRequest(t, handler, "bob", "/dataset2/folder1/item2", "GET", 403) - testRequest(t, handler, "bob", "/dataset2/folder1/item2", "POST", 200) - testRequest(t, handler, "bob", "/dataset2/folder1/item2", "DELETE", 403) + const item1 = "/dataset2/folder1/item1" + testRequest(t, handler, "bob", item1, "GET", 403) + testRequest(t, handler, "bob", item1, "POST", 200) + testRequest(t, handler, "bob", item1, "DELETE", 403) + const item2 = "/dataset2/folder1/item2" + 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) { handler := beego.NewControllerRegister() - handler.InsertFilter("*", beego.BeforeRouter, auth.Basic("cathy", "123")) - e := casbin.NewEnforcer("authz_model.conf", "authz_policy.csv") - handler.InsertFilter("*", beego.BeforeRouter, NewAuthorizer(e)) + _ = handler.InsertFilter("*", beego.BeforeRouter, auth.Basic("cathy", "123")) + e := casbin.NewEnforcer(authCfg, authCsv) + _ = handler.InsertFilter("*", beego.BeforeRouter, NewAuthorizer(e)) handler.Any("*", func(ctx *context.Context) { ctx.Output.SetStatus(200) }) // cathy can access all /dataset1/* resources via all methods because it has the dataset1_admin role. - testRequest(t, handler, "cathy", "/dataset1/item", "GET", 200) - testRequest(t, handler, "cathy", "/dataset1/item", "POST", 200) - testRequest(t, handler, "cathy", "/dataset1/item", "DELETE", 200) - testRequest(t, handler, "cathy", "/dataset2/item", "GET", 403) - testRequest(t, handler, "cathy", "/dataset2/item", "POST", 403) - testRequest(t, handler, "cathy", "/dataset2/item", "DELETE", 403) + const dataSet1 = "/dataset1/item" + testRequest(t, handler, "cathy", dataSet1, "GET", 200) + testRequest(t, handler, "cathy", dataSet1, "POST", 200) + testRequest(t, handler, "cathy", dataSet1, "DELETE", 200) + const dataSet2 = "/dataset2/item" + 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. e.DeleteRolesForUser("cathy") - testRequest(t, handler, "cathy", "/dataset1/item", "GET", 403) - testRequest(t, handler, "cathy", "/dataset1/item", "POST", 403) - testRequest(t, handler, "cathy", "/dataset1/item", "DELETE", 403) - testRequest(t, handler, "cathy", "/dataset2/item", "GET", 403) - testRequest(t, handler, "cathy", "/dataset2/item", "POST", 403) - testRequest(t, handler, "cathy", "/dataset2/item", "DELETE", 403) + testRequest(t, handler, "cathy", dataSet1, "GET", 403) + testRequest(t, handler, "cathy", dataSet1, "POST", 403) + testRequest(t, handler, "cathy", dataSet1, "DELETE", 403) + testRequest(t, handler, "cathy", dataSet2, "GET", 403) + testRequest(t, handler, "cathy", dataSet2, "POST", 403) + testRequest(t, handler, "cathy", dataSet2, "DELETE", 403) } diff --git a/adapter/session/redis_sentinel/sess_redis_sentinel_test.go b/adapter/session/redis_sentinel/sess_redis_sentinel_test.go index 0a6249ee..1b37afbd 100644 --- a/adapter/session/redis_sentinel/sess_redis_sentinel_test.go +++ b/adapter/session/redis_sentinel/sess_redis_sentinel_test.go @@ -5,6 +5,8 @@ import ( "net/http/httptest" "testing" + "github.com/stretchr/testify/assert" + "github.com/beego/beego/v2/adapter/session" ) @@ -19,71 +21,52 @@ func TestRedisSentinel(t *testing.T) { ProviderConfig: "127.0.0.1:6379,100,,0,master", } globalSessions, e := session.NewManager("redis_sentinel", sessionConfig) - if e != nil { - t.Log(e) - return - } - // todo test if e==nil + + assert.Nil(t, e) + go globalSessions.GC() r, _ := http.NewRequest("GET", "/", nil) w := httptest.NewRecorder() sess, err := globalSessions.SessionStart(w, r) - if err != nil { - t.Fatal("session start failed:", err) - } + assert.Nil(t, err) defer sess.SessionRelease(w) // SET AND GET err = sess.Set("username", "astaxie") - if err != nil { - t.Fatal("set username failed:", err) - } + assert.Nil(t, err) username := sess.Get("username") - if username != "astaxie" { - t.Fatal("get username failed") - } + assert.Equal(t, "astaxie", username) // DELETE err = sess.Delete("username") - if err != nil { - t.Fatal("delete username failed:", err) - } + assert.Nil(t, err) + username = sess.Get("username") - if username != nil { - t.Fatal("delete username failed") - } + assert.Nil(t, username) // FLUSH err = sess.Set("username", "astaxie") - if err != nil { - t.Fatal("set failed:", err) - } + assert.Nil(t, err) + err = sess.Set("password", "1qaz2wsx") - if err != nil { - t.Fatal("set failed:", err) - } + assert.Nil(t, err) + username = sess.Get("username") - if username != "astaxie" { - t.Fatal("get username failed") - } + assert.Equal(t, "astaxie", username) + password := sess.Get("password") - if password != "1qaz2wsx" { - t.Fatal("get password failed") - } + assert.Equal(t, "1qaz2wsx", password) + err = sess.Flush() - if err != nil { - t.Fatal("flush failed:", err) - } + assert.Nil(t, err) + username = sess.Get("username") - if username != nil { - t.Fatal("flush failed") - } + assert.Nil(t, username) + password = sess.Get("password") - if password != nil { - t.Fatal("flush failed") - } + assert.Nil(t, password) sess.SessionRelease(w)