ext_test.go 7.46 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 12
	ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/datastore.go"
	ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
13 14
	msg "github.com/jbenet/go-ipfs/net/message"
	mux "github.com/jbenet/go-ipfs/net/mux"
Jeromy's avatar
Jeromy committed
15
	peer "github.com/jbenet/go-ipfs/peer"
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 69 70
// DialPeer attempts to establish a connection to a given peer
func (f *fauxNet) DialPeer(*peer.Peer) error {
	return nil
71 72
}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
78 79 80
// IsConnected returns whether a connection to given peer exists.
func (f *fauxNet) IsConnected(*peer.Peer) (bool, error) {
	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 92 93 94
func (f *fauxNet) GetPeerList() []*peer.Peer {
	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()
Jeromy's avatar
Jeromy committed
110
	local := new(peer.Peer)
111
	local.ID = peer.ID("test_peer")
Jeromy's avatar
Jeromy committed
112

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
113
	d := NewDHT(local, peerstore, fn, fs, ds.NewMapDatastore())
114 115 116 117
	other := &peer.Peer{ID: peer.ID("other_peer")}
	d.Update(other)

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

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

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

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

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

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

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

174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
	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
189
}
Jeromy's avatar
Jeromy committed
190 191 192 193 194

// TODO: Maybe put these in some sort of "ipfs_testutil" package
func _randPeer() *peer.Peer {
	p := new(peer.Peer)
	p.ID = make(peer.ID, 16)
195
	p.Addresses = []ma.Multiaddr{nil}
Jeromy's avatar
Jeromy committed
196 197 198 199 200
	crand.Read(p.ID)
	return p
}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
203 204
	fn := &fauxNet{}
	fs := &fauxSender{}
Jeromy's avatar
Jeromy committed
205 206 207

	local := new(peer.Peer)
	local.ID = peer.ID("test_peer")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
208
	peerstore := peer.NewPeerstore()
Jeromy's avatar
Jeromy committed
209

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
210
	d := NewDHT(local, peerstore, fn, fs, ds.NewMapDatastore())
Jeromy's avatar
Jeromy committed
211 212 213 214 215 216 217 218

	var ps []*peer.Peer
	for i := 0; i < 5; i++ {
		ps = append(ps, _randPeer())
		d.Update(ps[i])
	}

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
230
			peers := []*peer.Peer{}
Jeromy's avatar
Jeromy committed
231
			for i := 0; i < 7; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
232 233 234 235 236 237
				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
238
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
239
			return mes
Jeromy's avatar
Jeromy committed
240 241 242 243 244 245
		default:
			panic("Shouldnt recieve this.")
		}

	})

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

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
275
	d := NewDHT(local, peerstore, fn, fs, ds.NewMapDatastore())
276 277 278 279 280 281 282 283 284

	var ps []*peer.Peer
	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 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
286 287
		pmes := new(Message)
		err := proto.Unmarshal(mes.Data(), pmes)
288 289 290 291 292
		if err != nil {
			t.Fatal(err)
		}

		switch pmes.GetType() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
293 294 295 296
		case Message_GET_VALUE:
			resp := &Message{
				Type:        pmes.Type,
				CloserPeers: 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 311
	ctx, _ := context.WithTimeout(context.Background(), time.Second*30)
	_, 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.")
}