direct_test.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package direct
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "testing"
  7. "time"
  8. "go-common/library/net/netutil/breaker"
  9. "go-common/library/net/rpc/warden"
  10. pb "go-common/library/net/rpc/warden/proto/testproto"
  11. "go-common/library/net/rpc/warden/resolver"
  12. xtime "go-common/library/time"
  13. )
  14. type testServer struct {
  15. name string
  16. }
  17. func (ts *testServer) SayHello(context.Context, *pb.HelloRequest) (*pb.HelloReply, error) {
  18. return &pb.HelloReply{Message: ts.name, Success: true}, nil
  19. }
  20. func (ts *testServer) StreamHello(ss pb.Greeter_StreamHelloServer) error {
  21. panic("not implement error")
  22. }
  23. func createServer(name, listen string) *warden.Server {
  24. s := warden.NewServer(&warden.ServerConfig{Timeout: xtime.Duration(time.Second)})
  25. ts := &testServer{name}
  26. pb.RegisterGreeterServer(s.Server(), ts)
  27. go func() {
  28. if err := s.Run(listen); err != nil {
  29. panic(fmt.Sprintf("run warden server fail! err: %s", err))
  30. }
  31. }()
  32. return s
  33. }
  34. func TestMain(m *testing.M) {
  35. resolver.Register(New())
  36. ctx := context.TODO()
  37. s1 := createServer("server1", "127.0.0.1:18081")
  38. s2 := createServer("server2", "127.0.0.1:18082")
  39. defer s1.Shutdown(ctx)
  40. defer s2.Shutdown(ctx)
  41. os.Exit(m.Run())
  42. }
  43. func createTestClient(t *testing.T, connStr string) pb.GreeterClient {
  44. client := warden.NewClient(&warden.ClientConfig{
  45. Dial: xtime.Duration(time.Second * 10),
  46. Timeout: xtime.Duration(time.Second * 10),
  47. Breaker: &breaker.Config{
  48. Window: xtime.Duration(3 * time.Second),
  49. Sleep: xtime.Duration(3 * time.Second),
  50. Bucket: 10,
  51. Ratio: 0.3,
  52. Request: 20,
  53. },
  54. })
  55. conn, err := client.Dial(context.TODO(), connStr)
  56. if err != nil {
  57. t.Fatalf("create client fail!err%s", err)
  58. }
  59. return pb.NewGreeterClient(conn)
  60. }
  61. func TestDirect(t *testing.T) {
  62. cli := createTestClient(t, "direct://default/127.0.0.1:18083,127.0.0.1:18082")
  63. count := 0
  64. for i := 0; i < 10; i++ {
  65. if resp, err := cli.SayHello(context.TODO(), &pb.HelloRequest{Age: 1, Name: "hello"}); err != nil {
  66. t.Fatalf("TestDirect: SayHello failed!err:=%v", err)
  67. } else {
  68. if resp.Message == "server2" {
  69. count++
  70. }
  71. }
  72. }
  73. if count != 10 {
  74. t.Fatalf("TestDirect: get server2 times must be 10")
  75. }
  76. }