wrappers.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. *
  3. * Copyright 2022 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package testutils
  19. import (
  20. "net"
  21. "testing"
  22. )
  23. // ConnWrapper wraps a net.Conn and pushes on a channel when closed.
  24. type ConnWrapper struct {
  25. net.Conn
  26. CloseCh *Channel
  27. }
  28. // Close closes the connection and sends a value on the close channel.
  29. func (cw *ConnWrapper) Close() error {
  30. err := cw.Conn.Close()
  31. cw.CloseCh.Replace(nil)
  32. return err
  33. }
  34. // ListenerWrapper wraps a net.Listener and the returned net.Conn.
  35. //
  36. // It pushes on a channel whenever it accepts a new connection.
  37. type ListenerWrapper struct {
  38. net.Listener
  39. NewConnCh *Channel
  40. }
  41. // Accept wraps the Listener Accept and sends the accepted connection on a
  42. // channel.
  43. func (l *ListenerWrapper) Accept() (net.Conn, error) {
  44. c, err := l.Listener.Accept()
  45. if err != nil {
  46. return nil, err
  47. }
  48. closeCh := NewChannel()
  49. conn := &ConnWrapper{Conn: c, CloseCh: closeCh}
  50. l.NewConnCh.Send(conn)
  51. return conn, nil
  52. }
  53. // NewListenerWrapper returns a ListenerWrapper.
  54. func NewListenerWrapper(t *testing.T, lis net.Listener) *ListenerWrapper {
  55. if lis == nil {
  56. var err error
  57. lis, err = LocalTCPListener()
  58. if err != nil {
  59. t.Fatal(err)
  60. }
  61. }
  62. return &ListenerWrapper{
  63. Listener: lis,
  64. NewConnCh: NewChannel(),
  65. }
  66. }