ext_test.go 6.97 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 97
	ctx := context.Background()
	fn := &fauxNet{}
	fs := &fauxSender{}
Jeromy's avatar
Jeromy committed
98

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

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

	// This one should time out
108
	// u.POut("Timout Test\n")
109
	_, err := d.GetValue(u.Key("test"), time.Millisecond*10)
Jeromy's avatar
Jeromy committed
110
	if err != nil {
111 112
		if err != context.DeadlineExceeded {
			t.Fatal("Got different error than we expected", err)
113 114 115
		}
	} else {
		t.Fatal("Did not get expected error!")
Jeromy's avatar
Jeromy committed
116 117
	}

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

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

	// This one should fail with NotFound
135
	_, err = d.GetValue(u.Key("test"), time.Millisecond*1000)
136 137
	if err != nil {
		if err != u.ErrNotFound {
138
			t.Fatalf("Expected ErrNotFound, got: %s", err)
139 140 141 142
		}
	} else {
		t.Fatal("expected error, got none.")
	}
143

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

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

160
	mes, err = d.HandleMessage(ctx, mes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
161 162 163
	if err != nil {
		t.Error(err)
	}
164

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

// 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)
	p.Addresses = []*ma.Multiaddr{nil}
	crand.Read(p.ID)
	return p
}

func TestNotFound(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
192 193
	fn := &fauxNet{}
	fs := &fauxSender{}
Jeromy's avatar
Jeromy committed
194 195 196

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

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

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

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

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

	})

235 236
	v, err := d.GetValue(u.Key("hello"), time.Second*5)
	u.POut("get value got %v\n", v)
Jeromy's avatar
Jeromy committed
237 238 239 240 241 242 243 244 245 246 247 248 249
	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.")
}
250 251 252 253 254

// 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) {
	u.Debug = false
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
255 256 257
	fn := &fauxNet{}
	fs := &fauxSender{}
	peerstore := peer.NewPeerstore()
258 259 260
	local := new(peer.Peer)
	local.ID = peer.ID("test_peer")

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
261
	d := NewDHT(local, peerstore, fn, fs, ds.NewMapDatastore())
262 263 264 265 266 267 268 269 270

	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
271
	fs.AddHandler(func(mes msg.NetMessage) msg.NetMessage {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
272 273
		pmes := new(Message)
		err := proto.Unmarshal(mes.Data(), pmes)
274 275 276 277 278
		if err != nil {
			t.Fatal(err)
		}

		switch pmes.GetType() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
279 280 281 282
		case Message_GET_VALUE:
			resp := &Message{
				Type:        pmes.Type,
				CloserPeers: peersToPBPeers([]*peer.Peer{other}),
283 284
			}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
285 286 287 288 289
			mes, err := msg.FromObject(mes.Peer(), resp)
			if err != nil {
				t.Error(err)
			}
			return mes
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
		default:
			panic("Shouldnt recieve this.")
		}

	})

	_, err := d.GetValue(u.Key("hello"), time.Second*30)
	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.")
}