testutils.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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. )
  12. var ErrClosed = errors.New("closed")
  13. // BlockingRW implements io.Reader, Writer and Closer, but only returns when closed
  14. type BlockingRW struct {
  15. c chan struct{}
  16. closeOnce sync.Once
  17. }
  18. func NewBlockingRW() *BlockingRW {
  19. return &BlockingRW{
  20. c: make(chan struct{}),
  21. closeOnce: sync.Once{},
  22. }
  23. }
  24. func (rw *BlockingRW) Read(p []byte) (int, error) {
  25. <-rw.c
  26. return 0, ErrClosed
  27. }
  28. func (rw *BlockingRW) Write(p []byte) (int, error) {
  29. <-rw.c
  30. return 0, ErrClosed
  31. }
  32. func (rw *BlockingRW) Close() error {
  33. rw.closeOnce.Do(func() {
  34. close(rw.c)
  35. })
  36. return nil
  37. }
  38. // NoopRW implements io.Reader and Writer but never returns when called
  39. type NoopRW struct{}
  40. func (rw *NoopRW) Read(p []byte) (n int, err error) {
  41. return len(p), nil
  42. }
  43. func (rw *NoopRW) Write(p []byte) (n int, err error) {
  44. return len(p), nil
  45. }
  46. type NoopCloser struct{}
  47. func (NoopCloser) Close() error {
  48. return nil
  49. }
  50. // FakeConnectionInfo implements the methods of protocol.Connection that are
  51. // not implemented by protocol.Connection
  52. type FakeConnectionInfo struct {
  53. Name string
  54. }
  55. func (f *FakeConnectionInfo) RemoteAddr() net.Addr {
  56. return &FakeAddr{}
  57. }
  58. func (f *FakeConnectionInfo) Type() string {
  59. return "fake"
  60. }
  61. func (f *FakeConnectionInfo) Crypto() string {
  62. return "fake"
  63. }
  64. func (f *FakeConnectionInfo) Transport() string {
  65. return "fake"
  66. }
  67. func (f *FakeConnectionInfo) Priority() int {
  68. return 9000
  69. }
  70. func (f *FakeConnectionInfo) String() string {
  71. return ""
  72. }
  73. type FakeAddr struct{}
  74. func (FakeAddr) Network() string {
  75. return "network"
  76. }
  77. func (FakeAddr) String() string {
  78. return "address"
  79. }