testutils.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. // Copyright (C) 2019 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package testutils
  7. import (
  8. "errors"
  9. "net"
  10. "sync"
  11. "time"
  12. )
  13. var ErrClosed = errors.New("closed")
  14. // BlockingRW implements io.Reader, Writer and Closer, but only returns when closed
  15. type BlockingRW struct {
  16. c chan struct{}
  17. closeOnce sync.Once
  18. }
  19. func NewBlockingRW() *BlockingRW {
  20. return &BlockingRW{
  21. c: make(chan struct{}),
  22. closeOnce: sync.Once{},
  23. }
  24. }
  25. func (rw *BlockingRW) Read(p []byte) (int, error) {
  26. <-rw.c
  27. return 0, ErrClosed
  28. }
  29. func (rw *BlockingRW) Write(p []byte) (int, error) {
  30. <-rw.c
  31. return 0, ErrClosed
  32. }
  33. func (rw *BlockingRW) Close() error {
  34. rw.closeOnce.Do(func() {
  35. close(rw.c)
  36. })
  37. return nil
  38. }
  39. // NoopRW implements io.Reader and Writer but never returns when called
  40. type NoopRW struct{}
  41. func (rw *NoopRW) Read(p []byte) (n int, err error) {
  42. return len(p), nil
  43. }
  44. func (rw *NoopRW) Write(p []byte) (n int, err error) {
  45. return len(p), nil
  46. }
  47. type NoopCloser struct{}
  48. func (NoopCloser) Close() error {
  49. return nil
  50. }
  51. // FakeConnectionInfo implements the methods of protocol.Connection that are
  52. // not implemented by protocol.Connection
  53. type FakeConnectionInfo struct {
  54. Name string
  55. }
  56. func (f *FakeConnectionInfo) RemoteAddr() net.Addr {
  57. return &FakeAddr{}
  58. }
  59. func (f *FakeConnectionInfo) Type() string {
  60. return "fake"
  61. }
  62. func (f *FakeConnectionInfo) Crypto() string {
  63. return "fake"
  64. }
  65. func (f *FakeConnectionInfo) Transport() string {
  66. return "fake"
  67. }
  68. func (f *FakeConnectionInfo) Priority() int {
  69. return 9000
  70. }
  71. func (f *FakeConnectionInfo) String() string {
  72. return ""
  73. }
  74. func (f *FakeConnectionInfo) EstablishedAt() time.Time {
  75. return time.Time{}
  76. }
  77. type FakeAddr struct{}
  78. func (FakeAddr) Network() string {
  79. return "network"
  80. }
  81. func (FakeAddr) String() string {
  82. return "address"
  83. }