client_conn_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package liverpc
  2. import (
  3. "context"
  4. "math/rand"
  5. "testing"
  6. "time"
  7. "go-common/library/conf/env"
  8. "go-common/library/net/metadata"
  9. . "github.com/smartystreets/goconvey/convey"
  10. )
  11. type testConn struct {
  12. }
  13. func (t *testConn) Read(p []byte) (n int, err error) {
  14. return
  15. }
  16. func (t *testConn) Write(p []byte) (n int, err error) {
  17. return
  18. }
  19. func (t *testConn) Close() (err error) {
  20. return
  21. }
  22. func TestClientConn(t *testing.T) {
  23. var (
  24. req protoReq
  25. resp protoResp
  26. )
  27. req.Header.magic = _magic
  28. req.Header.checkSum = 0
  29. req.Header.seq = rand.Uint32()
  30. req.Header.timestamp = uint32(time.Now().Unix())
  31. req.Header.reserved = 1
  32. req.Header.version = 1
  33. // command: {message_type}controller.method
  34. req.Header.cmd = make([]byte, 32)
  35. req.Header.cmd[0] = _cmdReqType
  36. // serviceMethod: Room.room_init
  37. copy(req.Header.cmd[1:], []byte("Room.room_init"))
  38. codec := &ClientConn{rwc: &testConn{}}
  39. if err := codec.writeRequest(context.TODO(), &req); err != nil {
  40. t.Error(err)
  41. t.FailNow()
  42. }
  43. if err := codec.readResponse(context.TODO(), &resp); err != nil {
  44. t.Error(err)
  45. t.FailNow()
  46. }
  47. t.Logf("request header:%+v body:%s", req.Header, req.Body)
  48. t.Logf("response header:%+v body:%s", resp.Header, resp.Body)
  49. }
  50. func TestGroups(t *testing.T) {
  51. Convey("groups", t, func() {
  52. client := Client{}
  53. // env before empty
  54. env.Color = "red"
  55. client.addrs.Store(GroupAddrs{
  56. "red": []string{"r1", "r2"},
  57. "": {"empty1", "empty2"},
  58. "dark": {"d1", "d2"},
  59. "blue": []string{"b1", "b2"},
  60. })
  61. addrs, _ := client.fetchAddrs(context.TODO(), nil)
  62. So(addrs, ShouldResemble, []string{"r1", "r2"})
  63. // can get env
  64. env.Color = ""
  65. addrs, _ = client.fetchAddrs(context.TODO(), nil)
  66. So(addrs, ShouldResemble, []string{"empty1", "empty2"})
  67. // from metadata.color
  68. env.Color = "red"
  69. addrs, _ = client.fetchAddrs(
  70. metadata.NewContext(context.TODO(), metadata.MD{metadata.Color: "blue"}), nil)
  71. So(addrs, ShouldResemble, []string{"b1", "b2"})
  72. // header source_group always first
  73. addrs, _ = client.fetchAddrs(
  74. metadata.NewContext(context.TODO(), metadata.MD{metadata.Color: "blue"}),
  75. &Args{Header: &Header{SourceGroup: "dark"}})
  76. So(addrs, ShouldResemble, []string{"d1", "d2"})
  77. })
  78. }