Browse Source

update unit test

jflyfox 4 năm trước cách đây
mục cha
commit
b270a516a5

+ 1 - 1
example/sample2/config/config.toml → example/sample/config/config.toml

@@ -1,5 +1,5 @@
 [server]
-    Address        = "127.0.0.1:8082"
+    Address        = "127.0.0.1:8081"
     ServerAgent    = "gtoken-demo"
     LogPath        = "./example/sample1/logs"
 

+ 26 - 1
example/sample2/main.go → example/sample/main.go

@@ -14,7 +14,7 @@ var TestServerName string
 func main() {
 	glog.Info("########service start...")
 
-	g.Cfg().SetPath("example/sample2")
+	g.Cfg().SetPath("example/sample")
 	s := g.Server(TestServerName)
 	initRouter(s)
 
@@ -66,6 +66,31 @@ func initRouter(s *ghttp.Server) {
 		})
 	})
 
+	// 启动gtoken
+	gfAdminToken := &gtoken.GfToken{
+		ServerName: TestServerName,
+		//Timeout:         10 * 1000,
+		CacheMode:        g.Config().GetInt8("gtoken.cache-mode"),
+		LoginPath:        "/login",
+		LoginBeforeFunc:  loginFunc,
+		LogoutPath:       "/user/logout",
+		AuthExcludePaths: g.SliceStr{"/admin/user/info", "/admin/system/user/info"}, // 不拦截路径 /user/info,/system/user/info,/system/user,
+		MultiLogin:       g.Config().GetBool("gtoken.multi-login"),
+	}
+	s.Group("/admin", func(group *ghttp.RouterGroup) {
+		group.Middleware(CORS)
+		gfAdminToken.Middleware(group)
+
+		group.ALL("/system/user", func(r *ghttp.Request) {
+			r.Response.WriteJson(gtoken.Succ("system user"))
+		})
+		group.ALL("/user/info", func(r *ghttp.Request) {
+			r.Response.WriteJson(gtoken.Succ("user info"))
+		})
+		group.ALL("/system/user/info", func(r *ghttp.Request) {
+			r.Response.WriteJson(gtoken.Succ("system user info"))
+		})
+	})
 }
 
 func Login(r *ghttp.Request) (string, interface{}) {

+ 0 - 0
example/sample2/test/api.http → example/sample/test/api.http


+ 258 - 0
example/sample/test/api_admin_test.go

@@ -0,0 +1,258 @@
+package test
+
+import (
+	"encoding/json"
+	"github.com/goflyfox/gtoken/gtoken"
+	"github.com/gogf/gf/frame/g"
+	"github.com/gogf/gf/net/ghttp"
+	"testing"
+)
+
+const (
+	TestAdminURL string = "http://127.0.0.1:8081/admin"
+)
+
+var (
+	TokenAdmin    = g.MapStrStr{}
+	AdminUsername = "flyfox"
+)
+
+func TestAdminSystemUser(t *testing.T) {
+	// 未登录
+	t.Log("1. not login and visit user")
+	if r, e := ghttp.Post(TestAdminURL+"/system/user", "username="+AdminUsername); e != nil {
+		t.Error("error:", e)
+	} else {
+		defer r.Close()
+
+		content := string(r.ReadAll())
+		t.Log(content)
+
+		var respData gtoken.Resp
+		err := json.Unmarshal([]byte(content), &respData)
+		if err != nil {
+			t.Error("error:", err)
+		}
+		if respData.Success() {
+			t.Error("error:", respData.Json())
+		}
+	}
+
+	// 登录,访问用户信息
+	t.Log("2. execute login and visit user")
+	data := PostAdmin(t, "/system/user", "username="+AdminUsername)
+	if data.Success() {
+		t.Log(data.Json())
+	} else {
+		t.Error("error:", data.Json())
+	}
+
+	// 登出
+	t.Log("3. execute logout")
+	data = PostAdmin(t, "/user/logout", "username="+AdminUsername)
+	if data.Success() {
+		t.Log(data.Json())
+	} else {
+		t.Error("error:", data.Json())
+	}
+
+	// 登出访问用户信息
+	t.Log("4. visit user")
+	data = PostAdmin(t, "/system/user", "username="+AdminUsername)
+	if data.Success() {
+		t.Error("error:", data.Json())
+	} else {
+		t.Log(data.Json())
+	}
+}
+
+func TestAdminUserLoginFail(t *testing.T) {
+	// 登录失败
+	t.Log("1. login fail ")
+	if r, e := ghttp.Post(TestAdminURL+"/login", "username=&passwd="); e != nil {
+		t.Error("error:", e)
+	} else {
+		defer r.Close()
+
+		content := string(r.ReadAll())
+
+		var respData gtoken.Resp
+		err := json.Unmarshal([]byte(content), &respData)
+		if err != nil {
+			t.Error("error:", err)
+		}
+
+		if respData.Success() {
+			t.Error("error:", "login fail:"+respData.Json())
+		}
+	}
+
+}
+
+func TestAdminExclude(t *testing.T) {
+	// 未登录可以访问
+	t.Log("1. exclude user info")
+	if r, e := ghttp.Post(TestAdminURL+"/system/user/info", "username="+AdminUsername); e != nil {
+		t.Error("error:", e)
+	} else {
+		defer r.Close()
+
+		content := string(r.ReadAll())
+		t.Log(content)
+
+		var respData gtoken.Resp
+		err := json.Unmarshal([]byte(content), &respData)
+		if err != nil {
+			t.Error("error:", err)
+		}
+		if !respData.Success() {
+			t.Error("error:", respData.Json())
+		}
+	}
+
+	if r, e := ghttp.Post(TestAdminURL+"/user/info", "username="+AdminUsername); e != nil {
+		t.Error("error:", e)
+	} else {
+		defer r.Close()
+
+		content := string(r.ReadAll())
+		t.Log(content)
+
+		var respData gtoken.Resp
+		err := json.Unmarshal([]byte(content), &respData)
+		if err != nil {
+			t.Error("error:", err)
+		}
+		if !respData.Success() {
+			t.Error("error:", respData.Json())
+		}
+	}
+
+}
+
+func TestAdminLogin(t *testing.T) {
+	AdminUsername = "testLogin"
+	t.Log(" login first ")
+	token1 := getAdminToken(t)
+	t.Log("token:" + token1)
+	t.Log(" login second and same token ")
+	token2 := getAdminToken(t)
+	t.Log("token:" + token2)
+	if token1 != token2 {
+		t.Error("error:", "token not same ")
+	}
+	AdminUsername = "flyfox"
+}
+
+func TestAdminLogout(t *testing.T) {
+	AdminUsername = "testLogout"
+	t.Log(" logout test ")
+	data := PostAdmin(t, "/user/logout", "username="+AdminUsername)
+	if data.Success() {
+		t.Log(data.Json())
+	} else {
+		t.Error("error:", data.Json())
+	}
+	AdminUsername = "flyfox"
+}
+
+func TestAdminMultiLogin(t *testing.T) {
+	AdminUsername = "testLogin"
+	t.Log(" TestMultiLogin start... ")
+	var token1, token2 string
+	if r, e := ghttp.Post(TestAdminURL+"/login", "username="+AdminUsername+"&passwd=123456"); e != nil {
+		t.Error("error:", e)
+	} else {
+		defer r.Close()
+
+		content := string(r.ReadAll())
+		t.Log("token1 content:" + content)
+
+		var respData gtoken.Resp
+		err := json.Unmarshal([]byte(content), &respData)
+		if err != nil {
+			t.Error("error:", err)
+		}
+
+		if !respData.Success() {
+			t.Error("error:", "resp fail:"+respData.Json())
+		}
+
+		token1 = respData.GetString("token")
+	}
+	t.Log("token1:" + token1)
+
+	if r, e := ghttp.Post(TestAdminURL+"/login", "username="+AdminUsername+"&passwd=123456"); e != nil {
+		t.Error("error:", e)
+	} else {
+		defer r.Close()
+
+		content := string(r.ReadAll())
+		t.Log("token2 content:" + content)
+
+		var respData gtoken.Resp
+		err := json.Unmarshal([]byte(content), &respData)
+		if err != nil {
+			t.Error("error:", err)
+		}
+
+		if !respData.Success() {
+			t.Error("error:", "resp fail:"+respData.Json())
+		}
+
+		token2 = respData.GetString("token")
+	}
+
+	t.Log("token2:" + token2)
+
+	if g.Config().GetBool("gtoken.multi-login") {
+		if token1 != token2 {
+			t.Error("error:", "token not same ")
+		}
+	} else {
+		if token1 == token2 {
+			t.Error("error:", "token same ")
+		}
+	}
+
+	AdminUsername = "flyfox"
+}
+
+func PostAdmin(t *testing.T, urlPath string, data ...interface{}) gtoken.Resp {
+	client := ghttp.NewClient()
+	client.SetHeader("Authorization", "Bearer "+getAdminToken(t))
+	content := client.RequestContent("POST", TestAdminURL+urlPath, data...)
+	var respData gtoken.Resp
+	err := json.Unmarshal([]byte(content), &respData)
+	if err != nil {
+		t.Error("error:", err)
+	}
+	return respData
+}
+
+func getAdminToken(t *testing.T) string {
+	if TokenAdmin[AdminUsername] != "" {
+		return TokenAdmin[AdminUsername]
+	}
+
+	if r, e := ghttp.Post(TestAdminURL+"/login", "username="+AdminUsername+"&passwd=123456"); e != nil {
+		t.Error("error:", e)
+	} else {
+		defer r.Close()
+
+		content := string(r.ReadAll())
+
+		var respData gtoken.Resp
+		err := json.Unmarshal([]byte(content), &respData)
+		if err != nil {
+			t.Error("error:", err)
+		}
+
+		if !respData.Success() {
+			t.Error("error:", "resp fail:"+respData.Json())
+		}
+
+		TokenAdmin[AdminUsername] = respData.GetString("token")
+	}
+	return TokenAdmin[AdminUsername]
+}

+ 40 - 40
example/sample2/test/api_test.go → example/sample/test/api_test.go

@@ -9,7 +9,7 @@ import (
 )
 
 const (
-	TestURL string = "http://127.0.0.1:8082"
+	TestURL string = "http://127.0.0.1:8081"
 )
 
 var (
@@ -201,45 +201,6 @@ func TestLogout(t *testing.T) {
 	Username = "flyfox"
 }
 
-func Post(t *testing.T, urlPath string, data ...interface{}) gtoken.Resp {
-	client := ghttp.NewClient()
-	client.SetHeader("Authorization", "Bearer "+getToken(t))
-	content := client.RequestContent("POST", TestURL+urlPath, data...)
-	var respData gtoken.Resp
-	err := json.Unmarshal([]byte(content), &respData)
-	if err != nil {
-		t.Error("error:", err)
-	}
-	return respData
-}
-
-func getToken(t *testing.T) string {
-	if Token[Username] != "" {
-		return Token[Username]
-	}
-
-	if r, e := ghttp.Post(TestURL+"/login", "username="+Username+"&passwd=123456"); e != nil {
-		t.Error("error:", e)
-	} else {
-		defer r.Close()
-
-		content := string(r.ReadAll())
-
-		var respData gtoken.Resp
-		err := json.Unmarshal([]byte(content), &respData)
-		if err != nil {
-			t.Error("error:", err)
-		}
-
-		if !respData.Success() {
-			t.Error("error:", "resp fail:"+respData.Json())
-		}
-
-		Token[Username] = respData.GetString("token")
-	}
-	return Token[Username]
-}
-
 func TestMultiLogin(t *testing.T) {
 	Username = "testLogin"
 	t.Log(" TestMultiLogin start... ")
@@ -301,3 +262,42 @@ func TestMultiLogin(t *testing.T) {
 
 	Username = "flyfox"
 }
+
+func Post(t *testing.T, urlPath string, data ...interface{}) gtoken.Resp {
+	client := ghttp.NewClient()
+	client.SetHeader("Authorization", "Bearer "+getToken(t))
+	content := client.RequestContent("POST", TestURL+urlPath, data...)
+	var respData gtoken.Resp
+	err := json.Unmarshal([]byte(content), &respData)
+	if err != nil {
+		t.Error("error:", err)
+	}
+	return respData
+}
+
+func getToken(t *testing.T) string {
+	if Token[Username] != "" {
+		return Token[Username]
+	}
+
+	if r, e := ghttp.Post(TestURL+"/login", "username="+Username+"&passwd=123456"); e != nil {
+		t.Error("error:", e)
+	} else {
+		defer r.Close()
+
+		content := string(r.ReadAll())
+
+		var respData gtoken.Resp
+		err := json.Unmarshal([]byte(content), &respData)
+		if err != nil {
+			t.Error("error:", err)
+		}
+
+		if !respData.Success() {
+			t.Error("error:", "resp fail:"+respData.Json())
+		}
+
+		Token[Username] = respData.GetString("token")
+	}
+	return Token[Username]
+}

+ 0 - 0
example/sample1/test/cache_test.go → example/sample/test/cache_test.go


+ 0 - 0
example/sample1/test/time_test.go → example/sample/test/time_test.go


+ 1 - 1
example/sample1/config/config.toml

@@ -1,5 +1,5 @@
 [server]
-    Address        = "127.0.0.1:8081"
+    Address        = "127.0.0.1:8082"
     ServerAgent    = "gtoken-demo"
     LogPath        = "./example/sample1/logs"
 

+ 1 - 1
example/sample1/test/api_test.go

@@ -9,7 +9,7 @@ import (
 )
 
 const (
-	TestURL string = "http://127.0.0.1:8081"
+	TestURL string = "http://127.0.0.1:8082"
 )
 
 var (

+ 0 - 102
example/sample2/test/cache_test.go

@@ -1,102 +0,0 @@
-package test
-
-import (
-	"github.com/goflyfox/gtoken/gtoken"
-	"github.com/gogf/gf/encoding/gjson"
-	"github.com/gogf/gf/frame/g"
-	"github.com/gogf/gf/os/gcache"
-	"github.com/gogf/gf/util/gconv"
-	"testing"
-	"time"
-)
-
-func TestGCache(t *testing.T) {
-	t.Log("gcache test ")
-	userKey := "123123"
-	gcache.Set(userKey, "1", 10000)
-
-	value, err := gcache.Get(userKey)
-	if err != nil {
-		t.Error("cache set error," + err.Error())
-	}
-	if value.(string) == userKey {
-		t.Error("cache get error")
-	}
-
-	gcache.Remove(userKey)
-
-	value, err = gcache.Get(userKey)
-	if err != nil {
-		t.Error("cache set error," + err.Error())
-	}
-	if value != nil {
-		t.Error("cache remove error")
-	}
-
-}
-
-func TestRedisCache(t *testing.T) {
-	if g.Config().GetInt8("gtoken.cache-mode") != gtoken.CacheModeRedis {
-		t.Log("redis cache not test ")
-		return
-	}
-
-	t.Log("redis cache test ")
-	userKey := "test:a"
-	_, err := g.Redis().Do("SETEX", userKey, 10000, "1")
-	if err != nil {
-		t.Error("cache set error," + err.Error())
-	}
-
-	time.Sleep(1 * time.Second)
-	ttl, err2 := g.Redis().Do("TTL", userKey)
-	if err2 != nil {
-		t.Error("cache ttl error," + err.Error())
-	}
-	t.Log("ttl:" + gconv.String(ttl))
-	if gconv.Int(ttl) >= 10000 || gconv.Int(ttl) < 9000 {
-		t.Error("cache ttl error, ttl:" + gconv.String(ttl))
-	}
-
-	data, err3 := g.Redis().Do("GET", userKey)
-	if err3 != nil {
-		t.Error("cache get error," + err.Error())
-	}
-	t.Log("data:" + gconv.String(data))
-	if gconv.String(data) != "1" {
-		t.Error("cache get error, data:" + gconv.String(data))
-	}
-
-	g.Redis().Do("DEL", userKey)
-	data, err4 := g.Redis().Do("GET", userKey)
-	if err4 != nil {
-		t.Error("cache del get error," + err.Error())
-	}
-	if gconv.String(data) != "" {
-		t.Error("cache del error, data:" + gconv.String(data))
-	}
-}
-
-func TestJson(t *testing.T) {
-	t.Log("json test ")
-	cacheValue := g.Map{
-		"userKey": "123",
-		"uuid":    "abc",
-		"data":    "",
-	}
-
-	cacheValueJson, err1 := gjson.Encode(cacheValue)
-	if err1 != nil {
-		t.Error("cache json encode error:" + err1.Error())
-	}
-
-	var userCache g.Map
-	err2 := gjson.DecodeTo(cacheValueJson, &userCache)
-	if err2 != nil {
-		t.Error("cache get json error:" + err2.Error())
-	}
-
-	if gconv.Map(userCache)["userKey"] != "123" {
-		t.Error("cache get json  data error:" + gconv.String(userCache))
-	}
-}

+ 0 - 26
example/sample2/test/time_test.go

@@ -1,26 +0,0 @@
-package test
-
-import (
-	"github.com/gogf/gf/os/gtime"
-	"github.com/gogf/gf/util/gconv"
-	"testing"
-	"time"
-)
-
-func TestTime(t *testing.T) {
-	t.Log("time test ")
-	time1 := gtime.Now().TimestampMilli()
-	t.Log("time time1: ", time1)
-	time.Sleep(time.Second * 2)
-	time2 := gtime.Now().TimestampMilli()
-	if time2-time1 < 1 {
-		t.Error("time error:" + gconv.String(time2-time1))
-	}
-}
-
-func TestTime2(t *testing.T) {
-	t.Log("time test2")
-	time1 := 10 * 1000
-	t.Log("###", gconv.Duration(time1)*time.Millisecond)
-	t.Log("###", (gconv.Duration(time1) * time.Millisecond).Milliseconds())
-}