peer_test.go 4.7 KB
Newer Older
Z
zelig 已提交
1 2
package p2p

3
import (
F
Felix Lange 已提交
4
	"errors"
F
Felix Lange 已提交
5
	"fmt"
F
Felix Lange 已提交
6
	"math/rand"
7
	"net"
F
Felix Lange 已提交
8
	"reflect"
9 10 11 12 13 14 15 16 17 18 19 20 21
	"testing"
	"time"
)

var discard = Protocol{
	Name:   "discard",
	Length: 1,
	Run: func(p *Peer, rw MsgReadWriter) error {
		for {
			msg, err := rw.ReadMsg()
			if err != nil {
				return err
			}
F
Felix Lange 已提交
22
			fmt.Printf("discarding %d\n", msg.Code)
23 24 25 26 27 28 29
			if err = msg.Discard(); err != nil {
				return err
			}
		}
	},
}

F
Felix Lange 已提交
30
func testPeer(protos []Protocol) (func(), *conn, *Peer, <-chan DiscReason) {
31 32 33
	fd1, fd2 := net.Pipe()
	c1 := &conn{fd: fd1, transport: newTestTransport(randomID(), fd1)}
	c2 := &conn{fd: fd2, transport: newTestTransport(randomID(), fd2)}
F
Felix Lange 已提交
34
	for _, p := range protos {
35 36
		c1.caps = append(c1.caps, p.cap())
		c2.caps = append(c2.caps, p.cap())
F
Felix Lange 已提交
37 38
	}

39
	peer := newPeer(c1, protos)
F
Felix Lange 已提交
40 41
	errc := make(chan DiscReason, 1)
	go func() { errc <- peer.run() }()
F
Felix Lange 已提交
42

43 44
	closer := func() { c2.close(errors.New("close func called")) }
	return closer, c2, peer, errc
45 46 47 48 49 50 51 52
}

func TestPeerProtoReadMsg(t *testing.T) {
	done := make(chan struct{})
	proto := Protocol{
		Name:   "a",
		Length: 5,
		Run: func(peer *Peer, rw MsgReadWriter) error {
53
			if err := ExpectMsg(rw, 2, []uint{1}); err != nil {
F
Felix Lange 已提交
54
				t.Error(err)
55
			}
56
			if err := ExpectMsg(rw, 3, []uint{2}); err != nil {
F
Felix Lange 已提交
57
				t.Error(err)
58
			}
59
			if err := ExpectMsg(rw, 4, []uint{3}); err != nil {
F
Felix Lange 已提交
60
				t.Error(err)
61 62 63 64 65 66
			}
			close(done)
			return nil
		},
	}

F
Felix Lange 已提交
67
	closer, rw, _, errc := testPeer([]Protocol{proto})
F
Felix Lange 已提交
68
	defer closer()
69

70 71 72
	Send(rw, baseProtocolLength+2, []uint{1})
	Send(rw, baseProtocolLength+3, []uint{2})
	Send(rw, baseProtocolLength+4, []uint{3})
F
Felix Lange 已提交
73

74 75 76 77 78 79 80 81 82 83 84 85 86 87
	select {
	case <-done:
	case err := <-errc:
		t.Errorf("peer returned: %v", err)
	case <-time.After(2 * time.Second):
		t.Errorf("receive timeout")
	}
}

func TestPeerProtoEncodeMsg(t *testing.T) {
	proto := Protocol{
		Name:   "a",
		Length: 2,
		Run: func(peer *Peer, rw MsgReadWriter) error {
88
			if err := SendItems(rw, 2); err == nil {
89 90
				t.Error("expected error for out-of-range msg code, got nil")
			}
91
			if err := SendItems(rw, 1, "foo", "bar"); err != nil {
92 93 94 95 96
				t.Errorf("write error: %v", err)
			}
			return nil
		},
	}
F
Felix Lange 已提交
97
	closer, rw, _, _ := testPeer([]Protocol{proto})
F
Felix Lange 已提交
98
	defer closer()
99

100
	if err := ExpectMsg(rw, 17, []string{"foo", "bar"}); err != nil {
F
Felix Lange 已提交
101
		t.Error(err)
O
Merge  
obscuren 已提交
102
	}
103 104
}

F
Felix Lange 已提交
105
func TestPeerPing(t *testing.T) {
F
Felix Lange 已提交
106
	closer, rw, _, _ := testPeer(nil)
F
Felix Lange 已提交
107
	defer closer()
108
	if err := SendItems(rw, pingMsg); err != nil {
F
Felix Lange 已提交
109 110
		t.Fatal(err)
	}
111
	if err := ExpectMsg(rw, pongMsg, nil); err != nil {
F
Felix Lange 已提交
112 113 114
		t.Error(err)
	}
}
115

F
Felix Lange 已提交
116
func TestPeerDisconnect(t *testing.T) {
F
Felix Lange 已提交
117
	closer, rw, _, disc := testPeer(nil)
F
Felix Lange 已提交
118
	defer closer()
119
	if err := SendItems(rw, discMsg, DiscQuitting); err != nil {
F
Felix Lange 已提交
120
		t.Fatal(err)
121
	}
122 123
	select {
	case reason := <-disc:
F
Felix Lange 已提交
124
		if reason != DiscRequested {
125 126 127 128
			t.Errorf("run returned wrong reason: got %v, want %v", reason, DiscRequested)
		}
	case <-time.After(500 * time.Millisecond):
		t.Error("peer did not return")
129 130
	}
}
F
Felix Lange 已提交
131

F
Felix Lange 已提交
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
// This test is supposed to verify that Peer can reliably handle
// multiple causes of disconnection occurring at the same time.
func TestPeerDisconnectRace(t *testing.T) {
	maybe := func() bool { return rand.Intn(1) == 1 }

	for i := 0; i < 1000; i++ {
		protoclose := make(chan error)
		protodisc := make(chan DiscReason)
		closer, rw, p, disc := testPeer([]Protocol{
			{
				Name:   "closereq",
				Run:    func(p *Peer, rw MsgReadWriter) error { return <-protoclose },
				Length: 1,
			},
			{
				Name:   "disconnect",
				Run:    func(p *Peer, rw MsgReadWriter) error { p.Disconnect(<-protodisc); return nil },
				Length: 1,
			},
		})

		// Simulate incoming messages.
		go SendItems(rw, baseProtocolLength+1)
		go SendItems(rw, baseProtocolLength+2)
		// Close the network connection.
		go closer()
		// Make protocol "closereq" return.
		protoclose <- errors.New("protocol closed")
		// Make protocol "disconnect" call peer.Disconnect
		protodisc <- DiscAlreadyConnected
		// In some cases, simulate something else calling peer.Disconnect.
		if maybe() {
			go p.Disconnect(DiscInvalidIdentity)
		}
		// In some cases, simulate remote requesting a disconnect.
		if maybe() {
			go SendItems(rw, discMsg, DiscQuitting)
		}

		select {
		case <-disc:
		case <-time.After(2 * time.Second):
			// Peer.run should return quickly. If it doesn't the Peer
			// goroutines are probably deadlocked. Call panic in order to
			// show the stacks.
			panic("Peer.run took to long to return.")
		}
	}
}

F
Felix Lange 已提交
182 183 184 185 186 187 188
func TestNewPeer(t *testing.T) {
	name := "nodename"
	caps := []Cap{{"foo", 2}, {"bar", 3}}
	id := randomID()
	p := NewPeer(id, name, caps)
	if p.ID() != id {
		t.Errorf("ID mismatch: got %v, expected %v", p.ID(), id)
F
Felix Lange 已提交
189
	}
F
Felix Lange 已提交
190 191
	if p.Name() != name {
		t.Errorf("Name mismatch: got %v, expected %v", p.Name(), name)
F
Felix Lange 已提交
192
	}
F
Felix Lange 已提交
193 194
	if !reflect.DeepEqual(p.Caps(), caps) {
		t.Errorf("Caps mismatch: got %v, expected %v", p.Caps(), caps)
F
Felix Lange 已提交
195 196
	}

F
Felix Lange 已提交
197 198
	p.Disconnect(DiscAlreadyConnected) // Should not hang
}