ext_test.go 7.35 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/datastore.go"
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
	u "github.com/jbenet/go-ipfs/util"
Jeromy's avatar
Jeromy committed
16 17 18 19

	"time"
)

20 21 22 23 24 25
// 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
26 27
// 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
28
type fauxSender struct {
29
	handlers []mesHandleFunc
Jeromy's avatar
Jeromy committed
30 31
}

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

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

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
52 53 54 55 56
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
57
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
58
	}
Jeromy's avatar
Jeromy committed
59 60 61
	return nil
}

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

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

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
82 83 84 85 86 87
// 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
88 89
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
	pmes := new(Message)
	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
187
}
Jeromy's avatar
Jeromy committed
188 189

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

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

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

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

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

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

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

		switch pmes.GetType() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
225 226
		case Message_GET_VALUE:
			resp := &Message{Type: pmes.Type}
Jeromy's avatar
Jeromy committed
227

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

	})

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
244
	ctx, _ = context.WithTimeout(ctx, time.Second*5)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
245
	v, err := d.GetValue(ctx, u.Key("hello"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
246
	log.Debug("get value got %v", v)
Jeromy's avatar
Jeromy committed
247 248 249 250 251 252 253 254 255 256 257 258 259
	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.")
}
260 261 262 263

// 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
264 265
	// t.Skip("skipping test because it makes a lot of output")

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

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

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

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

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

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

	})

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
309
	ctx, _ = context.WithTimeout(ctx, time.Second*30)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
310
	_, err := d.GetValue(ctx, u.Key("hello"))
311 312 313 314 315 316 317 318 319 320 321 322 323
	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.")
}