You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

95 lines
2.2 KiB

  1. // Copyright 2018, OpenCensus Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package testpb
  15. import (
  16. "context"
  17. "fmt"
  18. "io"
  19. "net"
  20. "testing"
  21. "time"
  22. "go.opencensus.io/plugin/ocgrpc"
  23. "go.opencensus.io/trace"
  24. "google.golang.org/grpc"
  25. )
  26. type testServer struct{}
  27. var _ FooServer = (*testServer)(nil)
  28. func (s *testServer) Single(ctx context.Context, in *FooRequest) (*FooResponse, error) {
  29. if in.SleepNanos > 0 {
  30. _, span := trace.StartSpan(ctx, "testpb.Single.Sleep")
  31. span.AddAttributes(trace.Int64Attribute("sleep_nanos", in.SleepNanos))
  32. time.Sleep(time.Duration(in.SleepNanos))
  33. span.End()
  34. }
  35. if in.Fail {
  36. return nil, fmt.Errorf("request failed")
  37. }
  38. return &FooResponse{}, nil
  39. }
  40. func (s *testServer) Multiple(stream Foo_MultipleServer) error {
  41. for {
  42. in, err := stream.Recv()
  43. if err == io.EOF {
  44. return nil
  45. }
  46. if err != nil {
  47. return err
  48. }
  49. if in.Fail {
  50. return fmt.Errorf("request failed")
  51. }
  52. if err := stream.Send(&FooResponse{}); err != nil {
  53. return err
  54. }
  55. }
  56. }
  57. // NewTestClient returns a new TestClient.
  58. func NewTestClient(l *testing.T) (client FooClient, cleanup func()) {
  59. // initialize server
  60. listener, err := net.Listen("tcp", "localhost:0")
  61. if err != nil {
  62. l.Fatal(err)
  63. }
  64. server := grpc.NewServer(grpc.StatsHandler(&ocgrpc.ServerHandler{}))
  65. RegisterFooServer(server, &testServer{})
  66. go server.Serve(listener)
  67. // Initialize client.
  68. clientConn, err := grpc.Dial(
  69. listener.Addr().String(),
  70. grpc.WithInsecure(),
  71. grpc.WithStatsHandler(&ocgrpc.ClientHandler{}),
  72. grpc.WithBlock())
  73. if err != nil {
  74. l.Fatal(err)
  75. }
  76. client = NewFooClient(clientConn)
  77. cleanup = func() {
  78. server.GracefulStop()
  79. clientConn.Close()
  80. }
  81. return client, cleanup
  82. }