v3 - main to cut out

This commit is contained in:
Xinwei Xiong(cubxxw-openim)
2023-06-29 22:35:31 +08:00
commit 6d499032fa
293 changed files with 57778 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
package utils
+68
View File
@@ -0,0 +1,68 @@
package utils
import (
"Open_IM/pkg/utils"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)
func init() {
gin.SetMode(gin.TestMode)
}
func performRequest(r http.Handler, method, origin string) *httptest.ResponseRecorder {
return performRequestWithHeaders(r, method, origin, http.Header{})
}
func performRequestWithHeaders(r http.Handler, method, origin string, header http.Header) *httptest.ResponseRecorder {
req, _ := http.NewRequest(method, "/", nil)
// From go/net/http/request.go:
// For incoming requests, the Host header is promoted to the
// Request.Host field and removed from the Header map.
req.Host = header.Get("Host")
header.Del("Host")
if len(origin) > 0 {
header.Set("Origin", origin)
}
req.Header = header
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
func newTestRouter() *gin.Engine {
router := gin.New()
router.Use(utils.CorsHandler())
router.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "get")
})
router.POST("/", func(c *gin.Context) {
c.String(http.StatusOK, "post")
})
router.PATCH("/", func(c *gin.Context) {
c.String(http.StatusOK, "patch")
})
return router
}
func Test_CorsHandler(t *testing.T) {
router := newTestRouter()
// no CORS request, origin == ""
w := performRequest(router, "GET", "")
assert.Equal(t, "get", w.Body.String())
assert.Equal(t, w.Header().Get("Access-Control-Allow-Origin"), "*")
assert.Equal(t, w.Header().Get("Access-Control-Allow-Methods"), "*")
assert.Equal(t, w.Header().Get("Access-Control-Allow-Headers"), "*")
assert.Equal(t, w.Header().Get("Access-Control-Expose-Headers"), "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar")
assert.Equal(t, w.Header().Get("Access-Control-Max-Age"), "172800")
assert.Equal(t, w.Header().Get("Access-Control-Allow-Credentials"), "false")
assert.Equal(t, w.Header().Get("content-type"), "application/json")
w = performRequest(router, "OPTIONS", "")
assert.Equal(t, w.Body.String(), "\"Options Request!\"")
}
+13
View File
@@ -0,0 +1,13 @@
package utils
import (
"Open_IM/pkg/utils"
"net"
"testing"
)
func TestServerIP(t *testing.T) {
if net.ParseIP(utils.ServerIP) == nil {
t.Fail()
}
}
+28
View File
@@ -0,0 +1,28 @@
package utils
import (
"github.com/bwmarrin/snowflake"
)
func init() {
var err error
idGenerator, err = snowflake.NewNode(getNodeNum())
if err != nil {
panic(err)
}
}
func getNodeNum() int64 {
return 1
}
var idGenerator *snowflake.Node
func GenID() string {
return idGenerator.Generate().String()
}
func GenIDs(count int) []string {
//impl
return []string{}
}
+15
View File
@@ -0,0 +1,15 @@
package utils
import "testing"
func TestGenID(t *testing.T) {
m := map[string]struct{}{}
for i := 0; i < 2000; i++ {
got := GenID()
if _, ok := m[got]; !ok {
m[got] = struct{}{}
} else {
t.Error("id generate error", got)
}
}
}
+28
View File
@@ -0,0 +1,28 @@
package utils
import (
"Open_IM/pkg/utils"
"path/filepath"
"runtime"
"testing"
"github.com/stretchr/testify/assert"
)
var (
_, b, _, _ = runtime.Caller(0)
// Root folder of this project
Root = filepath.Join(filepath.Dir(b), "../..")
)
func Test_GenSmallImage(t *testing.T) {
println(Root)
err := utils.GenSmallImage(Root+"/docs/open-im-logo.png", Root+"/out-test/open-im-logo-test.png")
assert.Nil(t, err)
err = utils.GenSmallImage(Root+"/docs/open-im-logo.png", "out-test/open-im-logo-test.png")
assert.Nil(t, err)
err = utils.GenSmallImage(Root+"/docs/Architecture.jpg", "out-test/Architecture-test.jpg")
assert.Nil(t, err)
}
+89
View File
@@ -0,0 +1,89 @@
package utils
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/token_verify"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func Test_BuildClaims(t *testing.T) {
uid := "1"
platform := "PC"
ttl := int64(-1)
claim := token_verify.BuildClaims(uid, platform, ttl)
now := time.Now().Unix()
assert.Equal(t, claim.UID, uid, "uid should equal")
assert.Equal(t, claim.Platform, platform, "platform should equal")
assert.Equal(t, claim.RegisteredClaims.ExpiresAt, int64(-1), "StandardClaims.ExpiresAt should be equal")
// time difference within 1s
assert.Equal(t, claim.RegisteredClaims.IssuedAt, now, "StandardClaims.IssuedAt should be equal")
assert.Equal(t, claim.RegisteredClaims.NotBefore, now, "StandardClaims.NotBefore should be equal")
ttl = int64(60)
now = time.Now().Unix()
claim = token_verify.BuildClaims(uid, platform, ttl)
// time difference within 1s
assert.Equal(t, claim.RegisteredClaims.ExpiresAt, int64(60)+now, "StandardClaims.ExpiresAt should be equal")
assert.Equal(t, claim.RegisteredClaims.IssuedAt, now, "StandardClaims.IssuedAt should be equal")
assert.Equal(t, claim.RegisteredClaims.NotBefore, now, "StandardClaims.NotBefore should be equal")
}
func Test_CreateToken(t *testing.T) {
uid := "1"
platform := int32(1)
now := time.Now().Unix()
tokenString, expiresAt, err := token_verify.CreateToken(uid, platform)
assert.NotEmpty(t, tokenString)
assert.Equal(t, expiresAt, 604800+now)
assert.Nil(t, err)
}
func Test_VerifyToken(t *testing.T) {
uid := "1"
platform := int32(1)
tokenString, _, _ := token_verify.CreateToken(uid, platform)
result, _ := token_verify.VerifyToken(tokenString, uid)
assert.True(t, result)
result, _ = token_verify.VerifyToken(tokenString, "2")
assert.False(t, result)
}
func Test_ParseRedisInterfaceToken(t *testing.T) {
uid := "1"
platform := int32(1)
tokenString, _, _ := token_verify.CreateToken(uid, platform)
claims, err := token_verify.ParseRedisInterfaceToken([]uint8(tokenString))
assert.Nil(t, err)
assert.Equal(t, claims.UID, uid)
// timeout
config.Config.TokenPolicy.AccessExpire = -80
tokenString, _, _ = token_verify.CreateToken(uid, platform)
claims, err = token_verify.ParseRedisInterfaceToken([]uint8(tokenString))
assert.Equal(t, err, constant.ExpiredToken)
assert.Nil(t, claims)
}
func Test_ParseToken(t *testing.T) {
uid := "1"
platform := int32(1)
tokenString, _, _ := token_verify.CreateToken(uid, platform)
claims, err := token_verify.ParseToken(tokenString, "")
if err == nil {
assert.Equal(t, claims.UID, uid)
}
}
func Test_GetClaimFromToken(t *testing.T) {
token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVSUQiOiJvcGVuSU0xMjM0NTYiLCJQbGF0Zm9ybSI6IiIsImV4cCI6MTYzODg0NjQ3NiwibmJmIjoxNjM4MjQxNjc2LCJpYXQiOjE2MzgyNDE2NzZ9.W8RZB7ec5ySFj-rGE2Aho2z32g3MprQMdCyPiQu_C2I"
c, err := token_verify.GetClaimFromToken(token)
assert.Nil(t, c)
assert.Nil(t, err)
}
+16
View File
@@ -0,0 +1,16 @@
package utils
import (
"Open_IM/pkg/utils"
"testing"
"github.com/stretchr/testify/assert"
)
func Test_Md5(t *testing.T) {
result := utils.Md5("go")
assert.Equal(t, result, "34d1f91fb2e514b8576fab1a75a89a6b")
result2 := utils.Md5("go")
assert.Equal(t, result, result2)
}
@@ -0,0 +1,46 @@
package utils
import (
"Open_IM/pkg/common/constant"
"testing"
"github.com/stretchr/testify/assert"
)
func Test_PlatformIDToName(t *testing.T) {
assert.Equal(t, constant.PlatformIDToName(1), "IOS")
assert.Equal(t, constant.PlatformIDToName(2), "Android")
assert.Equal(t, constant.PlatformIDToName(3), "Windows")
assert.Equal(t, constant.PlatformIDToName(4), "OSX")
assert.Equal(t, constant.PlatformIDToName(5), "Web")
assert.Equal(t, constant.PlatformIDToName(6), "MiniWeb")
assert.Equal(t, constant.PlatformIDToName(7), "Linux")
assert.Equal(t, constant.PlatformIDToName(0), "")
}
func Test_PlatformNameToID(t *testing.T) {
assert.Equal(t, constant.PlatformNameToID("IOS"), int32(1))
assert.Equal(t, constant.PlatformNameToID("Android"), int32(2))
assert.Equal(t, constant.PlatformNameToID("Windows"), int32(3))
assert.Equal(t, constant.PlatformNameToID("OSX"), int32(4))
assert.Equal(t, constant.PlatformNameToID("Web"), int32(5))
assert.Equal(t, constant.PlatformNameToID("MiniWeb"), int32(6))
assert.Equal(t, constant.PlatformNameToID("Linux"), int32(7))
assert.Equal(t, constant.PlatformNameToID("UnknownDevice"), int32(0))
assert.Equal(t, constant.PlatformNameToID(""), int32(0))
}
func Test_PlatformNameToClass(t *testing.T) {
assert.Equal(t, constant.PlatformNameToClass("IOS"), "Mobile")
assert.Equal(t, constant.PlatformNameToClass("Android"), "Mobile")
assert.Equal(t, constant.PlatformNameToClass("OSX"), "PC")
assert.Equal(t, constant.PlatformNameToClass("Windows"), "PC")
assert.Equal(t, constant.PlatformNameToClass("Web"), "PC")
assert.Equal(t, constant.PlatformNameToClass("MiniWeb"), "Mobile")
assert.Equal(t, constant.PlatformNameToClass("Linux"), "PC")
assert.Equal(t, constant.PlatformNameToClass("UnknownDevice"), "")
assert.Equal(t, constant.PlatformNameToClass(""), "")
}
+49
View File
@@ -0,0 +1,49 @@
package utils
import (
"encoding/json"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
"reflect"
)
func JsonDataList(resp interface{}) []map[string]interface{} {
var list []proto.Message
if reflect.TypeOf(resp).Kind() == reflect.Slice {
s := reflect.ValueOf(resp)
for i := 0; i < s.Len(); i++ {
ele := s.Index(i)
list = append(list, ele.Interface().(proto.Message))
}
}
result := make([]map[string]interface{}, 0)
for _, v := range list {
m := ProtoToMap(v, false)
result = append(result, m)
}
return result
}
func JsonDataOne(pb proto.Message) map[string]interface{} {
return ProtoToMap(pb, false)
}
func ProtoToMap(pb proto.Message, idFix bool) map[string]interface{} {
marshaler := jsonpb.Marshaler{
OrigName: true,
EnumsAsInts: false,
EmitDefaults: false,
}
s, _ := marshaler.MarshalToString(pb)
out := make(map[string]interface{})
json.Unmarshal([]byte(s), &out)
if idFix {
if _, ok := out["id"]; ok {
out["_id"] = out["id"]
delete(out, "id")
}
}
return out
}