ext_test.go 7.33 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
}

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
97 98 99
	ctx := context.Background()
	fn := &fauxNet{}
	fs := &fauxSender{}
Jeromy's avatar
Jeromy committed
100

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
101
	peerstore := peer.NewPeerstore()
Jeromy's avatar
Jeromy committed
102
	local := new(peer.Peer)
103
	local.ID = peer.ID("test_peer")
Jeromy's avatar
Jeromy committed
104

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
105
	d := NewDHT(local, peerstore, fn, fs, ds.NewMapDatastore())
106 107 108 109
	other := &peer.Peer{ID: peer.ID("other_peer")}
	d.Update(other)

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
130 131
		resp := &Message{
			Type: pmes.Type,
132
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
133 134
		m, err := msg.FromObject(mes.Peer(), resp)
		return m
135 136 137
	})

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

148
	fs.handlers = nil
149
	// Now we test this DHT's handleGetValue failure
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
150 151
	typ := Message_GET_VALUE
	str := "hello"
Chas Leichner's avatar
Chas Leichner committed
152
	req := Message{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
153 154
		Type:  &typ,
		Key:   &str,
155 156
		Value: []byte{0},
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
157

158
	// u.POut("handleGetValue Test\n")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
159 160 161 162 163
	mes, err := msg.FromObject(other, &req)
	if err != nil {
		t.Error(err)
	}

164
	mes = d.HandleMessage(ctx, mes)
165

166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
	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
181
}
Jeromy's avatar
Jeromy committed
182 183 184 185 186

// 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)
187
	p.Addresses = []ma.Multiaddr{nil}
Jeromy's avatar
Jeromy committed
188 189 190 191 192
	crand.Read(p.ID)
	return p
}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
195 196
	fn := &fauxNet{}
	fs := &fauxSender{}
Jeromy's avatar
Jeromy committed
197 198 199

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
202
	d := NewDHT(local, peerstore, fn, fs, ds.NewMapDatastore())
Jeromy's avatar
Jeromy committed
203 204 205 206 207 208 209 210

	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
211
	fs.AddHandler(func(mes msg.NetMessage) msg.NetMessage {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
212 213
		pmes := new(Message)
		err := proto.Unmarshal(mes.Data(), pmes)
Jeromy's avatar
Jeromy committed
214 215 216 217 218
		if err != nil {
			t.Fatal(err)
		}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
222
			peers := []*peer.Peer{}
Jeromy's avatar
Jeromy committed
223
			for i := 0; i < 7; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
224 225 226 227 228 229
				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
230
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
231
			return mes
Jeromy's avatar
Jeromy committed
232 233 234 235 236 237
		default:
			panic("Shouldnt recieve this.")
		}

	})

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
238 239
	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
240
	u.DOut("get value got %v\n", v)
Jeromy's avatar
Jeromy committed
241 242 243 244 245 246 247 248 249 250 251 252 253
	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.")
}
254 255 256 257

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

260
	u.Debug = false
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
261 262 263
	fn := &fauxNet{}
	fs := &fauxSender{}
	peerstore := peer.NewPeerstore()
264 265 266
	local := new(peer.Peer)
	local.ID = peer.ID("test_peer")

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
267
	d := NewDHT(local, peerstore, fn, fs, ds.NewMapDatastore())
268 269 270 271 272 273 274 275 276

	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
277
	fs.AddHandler(func(mes msg.NetMessage) msg.NetMessage {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
278 279
		pmes := new(Message)
		err := proto.Unmarshal(mes.Data(), pmes)
280 281 282 283 284
		if err != nil {
			t.Fatal(err)
		}

		switch pmes.GetType() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
285 286 287 288
		case Message_GET_VALUE:
			resp := &Message{
				Type:        pmes.Type,
				CloserPeers: peersToPBPeers([]*peer.Peer{other}),
289 290
			}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
291 292 293 294 295
			mes, err := msg.FromObject(mes.Peer(), resp)
			if err != nil {
				t.Error(err)
			}
			return mes
296 297 298 299 300 301
		default:
			panic("Shouldnt recieve this.")
		}

	})

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
302 303
	ctx, _ := context.WithTimeout(context.Background(), time.Second*30)
	_, err := d.GetValue(ctx, u.Key("hello"))
304 305 306 307 308 309 310 311 312 313 314 315 316
	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.")
}