http urls monitor.

tcp_test.go 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package tcp
  2. import (
  3. "fmt"
  4. "os"
  5. "testing"
  6. "time"
  7. "git.links123.net/links123.com/skeleton/config"
  8. jwt "github.com/dgrijalva/jwt-go"
  9. "github.com/stretchr/testify/assert"
  10. "github.com/wpajqz/go-sdk/export"
  11. )
  12. var client *export.Client
  13. type (
  14. ReadyStateCallback struct{}
  15. RequestStatusCallback struct {
  16. Start func()
  17. End func()
  18. Success func(header, body []byte)
  19. Error func(code int, message string)
  20. }
  21. )
  22. func (readyStateCallback *ReadyStateCallback) OnOpen() {
  23. fmt.Println("Open connection")
  24. }
  25. func (readyStateCallback *ReadyStateCallback) OnClose() {
  26. fmt.Println("Close connection")
  27. }
  28. func (readyStateCallback *ReadyStateCallback) OnError(err string) {
  29. fmt.Println("Error:", err)
  30. }
  31. func (r RequestStatusCallback) OnStart() {
  32. if r.Start != nil {
  33. r.Start()
  34. }
  35. }
  36. func (r RequestStatusCallback) OnSuccess(header, body []byte) {
  37. if r.Success != nil {
  38. r.Success(header, body)
  39. }
  40. }
  41. func (r RequestStatusCallback) OnError(code int, message string) {
  42. if r.Error != nil {
  43. r.Error(code, message)
  44. }
  45. }
  46. func (r RequestStatusCallback) OnEnd() {
  47. if r.End != nil {
  48. r.End()
  49. }
  50. }
  51. func genToken(userID int64) string {
  52. // Create a new token object, specifying signing method and the claims
  53. // you would like it to contain.
  54. token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
  55. "user_id": userID,
  56. "expired": time.Now().Add(time.Hour).Unix(),
  57. })
  58. // Sign and get the complete encoded token as a string using the secret
  59. tokenString, err := token.SignedString([]byte(config.C.App.Secret))
  60. if err != nil {
  61. panic(err)
  62. }
  63. return tokenString
  64. }
  65. func TestHealthy(t *testing.T) {
  66. err := client.SyncSend("/v1/", nil, &RequestStatusCallback{
  67. Success: func(header, body []byte) {
  68. fmt.Print(header)
  69. assert.Equal(t, "{\"keepalive\":\"true\"}", string(body))
  70. },
  71. Error: func(code int, message string) {
  72. t.Error(code, message)
  73. },
  74. })
  75. if err != nil {
  76. t.Error(err)
  77. }
  78. }
  79. func TestMain(m *testing.M) {
  80. // start tcp server
  81. go Start("127.0.0.1", "8081")
  82. client = export.NewClient("127.0.0.1", 8081, &ReadyStateCallback{})
  83. for {
  84. time.Sleep(time.Second)
  85. if client.GetReadyState() == export.OPEN {
  86. break
  87. }
  88. }
  89. client.SetRequestProperty("Authorization", "Bearer "+genToken(217))
  90. // call flag.Parse() here if TestMain uses flags
  91. os.Exit(m.Run())
  92. }