ext_test.go 7.44 KB
Newer Older
Jeromy's avatar
Jeromy committed
1 2 3 4 5
package dht

import (
	"testing"

Jeromy's avatar
Jeromy committed
6 7
	crand "crypto/rand"

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
8
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
9
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/goprotobuf/proto"
10

11
	ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
12 13
	msg "github.com/jbenet/go-ipfs/net/message"
	mux "github.com/jbenet/go-ipfs/net/mux"
Jeromy's avatar
Jeromy committed
14
	peer "github.com/jbenet/go-ipfs/peer"
15
	pb "github.com/jbenet/go-ipfs/routing/dht/pb"
16
	u "github.com/jbenet/go-ipfs/util"
Jeromy's avatar
Jeromy committed
17 18 19 20

	"time"
)

21 22 23 24 25 26
// mesHandleFunc is a function that takes in outgoing messages
// and can respond to them, simulating other peers on the network.
// returning nil will chose not to respond and pass the message onto the
// next registered handler
type mesHandleFunc func(msg.NetMessage) msg.NetMessage

Jeromy's avatar
Jeromy committed
27 28
// fauxNet is a standin for a swarm.Network in order to more easily recreate
// different testing scenarios
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
29
type fauxSender struct {
30
	handlers []mesHandleFunc
Jeromy's avatar
Jeromy committed
31 32
}

33 34 35
func (f *fauxSender) AddHandler(fn func(msg.NetMessage) msg.NetMessage) {
	f.handlers = append(f.handlers, fn)
}
Jeromy's avatar
Jeromy committed
36

37
func (f *fauxSender) SendRequest(ctx context.Context, m msg.NetMessage) (msg.NetMessage, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
38 39 40 41 42 43
	for _, h := range f.handlers {
		reply := h(m)
		if reply != nil {
			return reply, nil
		}
	}
Jeromy's avatar
Jeromy committed
44

45 46 47 48 49 50
	// no reply? ok force a timeout
	select {
	case <-ctx.Done():
	}

	return nil, ctx.Err()
Jeromy's avatar
Jeromy committed
51 52
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
53 54 55 56 57
func (f *fauxSender) SendMessage(ctx context.Context, m msg.NetMessage) error {
	for _, h := range f.handlers {
		reply := h(m)
		if reply != nil {
			return nil
Jeromy's avatar
Jeromy committed
58
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
59
	}
Jeromy's avatar
Jeromy committed
60 61 62
	return nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
63 64 65
// fauxNet is a standin for a swarm.Network in order to more easily recreate
// different testing scenarios
type fauxNet struct {
66
}
Jeromy's avatar
Jeromy committed
67

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
68
// DialPeer attempts to establish a connection to a given peer
69
func (f *fauxNet) DialPeer(peer.Peer) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
70
	return nil
71 72
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
73
// ClosePeer connection to peer
74
func (f *fauxNet) ClosePeer(peer.Peer) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
75
	return nil
Jeromy's avatar
Jeromy committed
76 77
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
78
// IsConnected returns whether a connection to given peer exists.
79
func (f *fauxNet) IsConnected(peer.Peer) (bool, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
80
	return true, nil
81 82
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
83 84 85 86 87 88
// GetProtocols returns the protocols registered in the network.
func (f *fauxNet) GetProtocols() *mux.ProtocolMap { return nil }

// SendMessage sends given Message out
func (f *fauxNet) SendMessage(msg.NetMessage) error {
	return nil
Jeromy's avatar
Jeromy committed
89 90
}

91
func (f *fauxNet) GetPeerList() []peer.Peer {
92 93 94
	return nil
}

95 96 97 98
func (f *fauxNet) GetBandwidthTotals() (uint64, uint64) {
	return 0, 0
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
99 100 101
// Close terminates all network operation
func (f *fauxNet) Close() error { return nil }

102
func TestGetFailures(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
103 104
	// t.Skip("skipping test because it makes a lot of output")

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
105 106 107
	ctx := context.Background()
	fn := &fauxNet{}
	fs := &fauxSender{}
Jeromy's avatar
Jeromy committed
108

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
109
	peerstore := peer.NewPeerstore()
110
	local := peer.WithIDString("test_peer")
Jeromy's avatar
Jeromy committed
111

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
112
	d := NewDHT(ctx, local, peerstore, fn, fs, ds.NewMapDatastore())
113
	other := peer.WithIDString("other_peer")
114 115 116
	d.Update(other)

	// This one should time out
117
	// u.POut("Timout Test\n")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
118 119
	ctx1, _ := context.WithTimeout(context.Background(), time.Second)
	_, err := d.GetValue(ctx1, u.Key("test"))
Jeromy's avatar
Jeromy committed
120
	if err != nil {
121 122
		if err != context.DeadlineExceeded {
			t.Fatal("Got different error than we expected", err)
123 124 125
		}
	} else {
		t.Fatal("Did not get expected error!")
Jeromy's avatar
Jeromy committed
126 127
	}

128
	// u.POut("NotFound Test\n")
129
	// Reply with failures to every message
130
	fs.AddHandler(func(mes msg.NetMessage) msg.NetMessage {
131
		pmes := new(pb.Message)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
132
		err := proto.Unmarshal(mes.Data(), pmes)
133 134 135 136
		if err != nil {
			t.Fatal(err)
		}

137
		resp := &pb.Message{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
138
			Type: pmes.Type,
139
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
140 141
		m, err := msg.FromObject(mes.Peer(), resp)
		return m
142 143 144
	})

	// This one should fail with NotFound
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
145 146
	ctx2, _ := context.WithTimeout(context.Background(), time.Second)
	_, err = d.GetValue(ctx2, u.Key("test"))
147 148
	if err != nil {
		if err != u.ErrNotFound {
149
			t.Fatalf("Expected ErrNotFound, got: %s", err)
150 151 152 153
		}
	} else {
		t.Fatal("expected error, got none.")
	}
154

155
	fs.handlers = nil
156
	// Now we test this DHT's handleGetValue failure
157
	typ := pb.Message_GET_VALUE
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
158
	str := "hello"
159
	req := pb.Message{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
160 161
		Type:  &typ,
		Key:   &str,
162 163
		Value: []byte{0},
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
164

165
	// u.POut("handleGetValue Test\n")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
166 167 168 169 170
	mes, err := msg.FromObject(other, &req)
	if err != nil {
		t.Error(err)
	}

171
	mes = d.HandleMessage(ctx, mes)
172

173
	pmes := new(pb.Message)
174 175 176 177 178 179 180 181 182 183 184 185 186 187
	err = proto.Unmarshal(mes.Data(), pmes)
	if err != nil {
		t.Fatal(err)
	}
	if pmes.GetValue() != nil {
		t.Fatal("shouldnt have value")
	}
	if pmes.GetCloserPeers() != nil {
		t.Fatal("shouldnt have closer peers")
	}
	if pmes.GetProviderPeers() != nil {
		t.Fatal("shouldnt have provider peers")
	}

Jeromy's avatar
Jeromy committed
188
}
Jeromy's avatar
Jeromy committed
189 190

// TODO: Maybe put these in some sort of "ipfs_testutil" package
191 192 193 194
func _randPeer() peer.Peer {
	id := make(peer.ID, 16)
	crand.Read(id)
	p := peer.WithID(id)
Jeromy's avatar
Jeromy committed
195 196 197 198
	return p
}

func TestNotFound(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
199 200
	// t.Skip("skipping test because it makes a lot of output")

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
201
	ctx := context.Background()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
202 203
	fn := &fauxNet{}
	fs := &fauxSender{}
Jeromy's avatar
Jeromy committed
204

205
	local := peer.WithIDString("test_peer")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
206
	peerstore := peer.NewPeerstore()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
207
	peerstore.Add(local)
Jeromy's avatar
Jeromy committed
208

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
209
	d := NewDHT(ctx, local, peerstore, fn, fs, ds.NewMapDatastore())
Jeromy's avatar
Jeromy committed
210

211
	var ps []peer.Peer
Jeromy's avatar
Jeromy committed
212 213 214 215 216 217
	for i := 0; i < 5; i++ {
		ps = append(ps, _randPeer())
		d.Update(ps[i])
	}

	// Reply with random peers to every message
218
	fs.AddHandler(func(mes msg.NetMessage) msg.NetMessage {
219
		pmes := new(pb.Message)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
220
		err := proto.Unmarshal(mes.Data(), pmes)
Jeromy's avatar
Jeromy committed
221 222 223 224 225
		if err != nil {
			t.Fatal(err)
		}

		switch pmes.GetType() {
226 227
		case pb.Message_GET_VALUE:
			resp := &pb.Message{Type: pmes.Type}
Jeromy's avatar
Jeromy committed
228

229
			peers := []peer.Peer{}
Jeromy's avatar
Jeromy committed
230
			for i := 0; i < 7; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
231 232
				peers = append(peers, _randPeer())
			}
233
			resp.CloserPeers = pb.PeersToPBPeers(peers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
234 235 236
			mes, err := msg.FromObject(mes.Peer(), resp)
			if err != nil {
				t.Error(err)
Jeromy's avatar
Jeromy committed
237
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
238
			return mes
Jeromy's avatar
Jeromy committed
239 240 241 242 243 244
		default:
			panic("Shouldnt recieve this.")
		}

	})

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
245
	ctx, _ = context.WithTimeout(ctx, time.Second*5)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
246
	v, err := d.GetValue(ctx, u.Key("hello"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
247
	log.Debug("get value got %v", v)
Jeromy's avatar
Jeromy committed
248 249 250 251 252 253 254 255 256 257 258 259 260
	if err != nil {
		switch err {
		case u.ErrNotFound:
			//Success!
			return
		case u.ErrTimeout:
			t.Fatal("Should not have gotten timeout!")
		default:
			t.Fatalf("Got unexpected error: %s", err)
		}
	}
	t.Fatal("Expected to recieve an error.")
}
261 262 263 264

// If less than K nodes are in the entire network, it should fail when we make
// a GET rpc and nobody has the value
func TestLessThanKResponses(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
265 266
	// t.Skip("skipping test because it makes a lot of output")

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
267
	ctx := context.Background()
268
	u.Debug = false
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
269 270
	fn := &fauxNet{}
	fs := &fauxSender{}
271
	local := peer.WithIDString("test_peer")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
272
	peerstore := peer.NewPeerstore()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
273
	peerstore.Add(local)
274

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
275
	d := NewDHT(ctx, local, peerstore, fn, fs, ds.NewMapDatastore())
276

277
	var ps []peer.Peer
278 279 280 281 282 283 284
	for i := 0; i < 5; i++ {
		ps = append(ps, _randPeer())
		d.Update(ps[i])
	}
	other := _randPeer()

	// Reply with random peers to every message
285
	fs.AddHandler(func(mes msg.NetMessage) msg.NetMessage {
286
		pmes := new(pb.Message)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
287
		err := proto.Unmarshal(mes.Data(), pmes)
288 289 290 291 292
		if err != nil {
			t.Fatal(err)
		}

		switch pmes.GetType() {
293 294
		case pb.Message_GET_VALUE:
			resp := &pb.Message{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
295
				Type:        pmes.Type,
296
				CloserPeers: pb.PeersToPBPeers([]peer.Peer{other}),
297 298
			}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
299 300 301 302 303
			mes, err := msg.FromObject(mes.Peer(), resp)
			if err != nil {
				t.Error(err)
			}
			return mes
304 305 306 307 308 309
		default:
			panic("Shouldnt recieve this.")
		}

	})

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
310
	ctx, _ = context.WithTimeout(ctx, time.Second*30)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
311
	_, err := d.GetValue(ctx, u.Key("hello"))
312 313 314 315 316 317 318 319 320 321 322 323 324
	if err != nil {
		switch err {
		case u.ErrNotFound:
			//Success!
			return
		case u.ErrTimeout:
			t.Fatal("Should not have gotten timeout!")
		default:
			t.Fatalf("Got unexpected error: %s", err)
		}
	}
	t.Fatal("Expected to recieve an error.")
}