123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- package tcp
-
- import (
- "fmt"
- "os"
- "testing"
- "time"
-
- "git.links123.net/links123.com/skeleton/config"
- jwt "github.com/dgrijalva/jwt-go"
- "github.com/stretchr/testify/assert"
- "github.com/wpajqz/go-sdk/export"
- )
-
- var client *export.Client
-
- type (
- ReadyStateCallback struct{}
- RequestStatusCallback struct {
- Start func()
- End func()
- Success func(header, body []byte)
- Error func(code int, message string)
- }
- )
-
- func (readyStateCallback *ReadyStateCallback) OnOpen() {
- fmt.Println("Open connection")
- }
-
- func (readyStateCallback *ReadyStateCallback) OnClose() {
- fmt.Println("Close connection")
- }
-
- func (readyStateCallback *ReadyStateCallback) OnError(err string) {
- fmt.Println("Error:", err)
- }
-
- func (r RequestStatusCallback) OnStart() {
- if r.Start != nil {
- r.Start()
- }
- }
-
- func (r RequestStatusCallback) OnSuccess(header, body []byte) {
- if r.Success != nil {
- r.Success(header, body)
- }
- }
-
- func (r RequestStatusCallback) OnError(code int, message string) {
- if r.Error != nil {
- r.Error(code, message)
- }
- }
-
- func (r RequestStatusCallback) OnEnd() {
- if r.End != nil {
- r.End()
- }
- }
-
- func genToken(userID int64) string {
- // Create a new token object, specifying signing method and the claims
- // you would like it to contain.
- token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
- "user_id": userID,
- "expired": time.Now().Add(time.Hour).Unix(),
- })
-
- // Sign and get the complete encoded token as a string using the secret
- tokenString, err := token.SignedString([]byte(config.C.App.Secret))
- if err != nil {
- panic(err)
- }
- return tokenString
- }
-
- func TestHealthy(t *testing.T) {
- err := client.SyncSend("/v1/", nil, &RequestStatusCallback{
- Success: func(header, body []byte) {
- fmt.Print(header)
- assert.Equal(t, "{\"keepalive\":\"true\"}", string(body))
- },
- Error: func(code int, message string) {
- t.Error(code, message)
- },
- })
- if err != nil {
- t.Error(err)
- }
- }
-
- func TestMain(m *testing.M) {
- // start tcp server
- go Start("127.0.0.1", "8081")
- client = export.NewClient("127.0.0.1", 8081, &ReadyStateCallback{})
- for {
- time.Sleep(time.Second)
- if client.GetReadyState() == export.OPEN {
- break
- }
- }
- client.SetRequestProperty("Authorization", "Bearer "+genToken(217))
- // call flag.Parse() here if TestMain uses flags
- os.Exit(m.Run())
- }
|