github.com/unirita/cuto@v0.9.8-0.20160830082821-aa6652f877b7/testutil/netstab.go (about) 1 package testutil 2 3 import ( 4 "net" 5 "time" 6 ) 7 8 // net.Listenerのスタブ構造体 9 type ListenerStub struct { 10 AcceptErr error 11 CloseErr error 12 IsClosed bool 13 14 addr net.Addr 15 } 16 17 // net.Connのスタブ構造体 18 type ConnStub struct { 19 ReadStr string // Read関数で取得させる文字列 20 WriteStr string // Write関数で書き込まれた文字列 21 ReadErr error 22 WriteErr error 23 CloseErr error 24 SetDeadlineErr error 25 SetReadDeadlineErr error 26 SetWriteDeadlineErr error 27 IsClosed bool 28 29 localAddr net.Addr 30 remoteAddr net.Addr 31 } 32 33 // net.Addrのスタブ構造体 34 type AddrStub struct { 35 nwk string 36 str string 37 } 38 39 func NewListenerStub() *ListenerStub { 40 listener := new(ListenerStub) 41 listener.addr = NewAddrStub("127.0.0.1:12345") 42 return listener 43 } 44 45 func NewConnStub() *ConnStub { 46 conn := new(ConnStub) 47 conn.ReadStr = "\n" 48 conn.localAddr = NewAddrStub("127.0.0.1:54321") 49 conn.remoteAddr = NewAddrStub("127.0.0.1:12345") 50 return conn 51 } 52 53 func NewAddrStub(str string) *AddrStub { 54 addr := new(AddrStub) 55 addr.nwk = "tcp" 56 addr.str = str 57 return addr 58 } 59 60 func (l *ListenerStub) Accept() (c net.Conn, err error) { 61 if l.AcceptErr != nil { 62 return nil, l.AcceptErr 63 } 64 return NewConnStub(), nil 65 } 66 67 func (l *ListenerStub) Close() error { 68 if l.CloseErr != nil { 69 return l.CloseErr 70 } 71 l.IsClosed = true 72 return nil 73 } 74 75 func (l *ListenerStub) Addr() net.Addr { 76 return l.addr 77 } 78 79 func (c *ConnStub) Read(b []byte) (n int, err error) { 80 if c.ReadErr != nil { 81 return 0, c.ReadErr 82 } 83 copy(b, []byte(c.ReadStr)) 84 return len(c.ReadStr), nil 85 } 86 87 func (c *ConnStub) Write(b []byte) (n int, err error) { 88 if c.WriteErr != nil { 89 return 0, c.WriteErr 90 } 91 c.WriteStr = string(b) 92 return len(c.WriteStr), nil 93 } 94 95 func (c *ConnStub) Close() error { 96 if c.CloseErr != nil { 97 return c.CloseErr 98 } 99 c.IsClosed = true 100 return nil 101 } 102 103 func (c *ConnStub) LocalAddr() net.Addr { 104 return c.localAddr 105 } 106 107 func (c *ConnStub) RemoteAddr() net.Addr { 108 return c.remoteAddr 109 } 110 111 func (c *ConnStub) SetDeadline(t time.Time) error { 112 return c.SetDeadlineErr 113 } 114 115 func (c *ConnStub) SetReadDeadline(t time.Time) error { 116 return c.SetReadDeadlineErr 117 } 118 119 func (c *ConnStub) SetWriteDeadline(t time.Time) error { 120 return c.SetWriteDeadlineErr 121 } 122 123 func (a *AddrStub) Network() string { 124 return a.nwk 125 } 126 127 func (a *AddrStub) String() string { 128 return a.str 129 }