ext_test.go 6.1 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"

8 9
	"code.google.com/p/goprotobuf/proto"

Jeromy's avatar
Jeromy committed
10 11
	peer "github.com/jbenet/go-ipfs/peer"
	swarm "github.com/jbenet/go-ipfs/swarm"
12 13
	u "github.com/jbenet/go-ipfs/util"
	ma "github.com/jbenet/go-multiaddr"
Jeromy's avatar
Jeromy committed
14 15 16 17 18 19 20

	"time"
)

// fauxNet is a standin for a swarm.Network in order to more easily recreate
// different testing scenarios
type fauxNet struct {
21 22
	Chan     *swarm.Chan
	handlers []mesHandleFunc
Jeromy's avatar
Jeromy committed
23 24 25 26

	swarm.Network
}

27 28 29 30
// 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
Jeromy's avatar
Jeromy committed
31 32 33 34 35 36 37 38 39
type mesHandleFunc func(*swarm.Message) *swarm.Message

func newFauxNet() *fauxNet {
	fn := new(fauxNet)
	fn.Chan = swarm.NewChan(8)

	return fn
}

40 41 42
// Instead of 'Listening' Start up a goroutine that will check
// all outgoing messages against registered message handlers,
// and reply if needed
Jeromy's avatar
Jeromy committed
43 44 45 46 47
func (f *fauxNet) Listen() error {
	go func() {
		for {
			select {
			case in := <-f.Chan.Outgoing:
48
				for _, h := range f.handlers {
Jeromy's avatar
Jeromy committed
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
					reply := h(in)
					if reply != nil {
						f.Chan.Incoming <- reply
						break
					}
				}
			}
		}
	}()
	return nil
}

func (f *fauxNet) AddHandler(fn func(*swarm.Message) *swarm.Message) {
	f.handlers = append(f.handlers, fn)
}

func (f *fauxNet) Send(mes *swarm.Message) {
66 67
	f.Chan.Outgoing <- mes
}
Jeromy's avatar
Jeromy committed
68

69 70 71 72
func (f *fauxNet) GetErrChan() chan error {
	return f.Chan.Errors
}

73 74
func (f *fauxNet) GetChannel(t swarm.PBWrapper_MessageType) *swarm.Chan {
	return f.Chan
Jeromy's avatar
Jeromy committed
75 76
}

77 78 79 80
func (f *fauxNet) Connect(addr *ma.Multiaddr) (*peer.Peer, error) {
	return nil, nil
}

Jeromy's avatar
Jeromy committed
81 82 83 84
func (f *fauxNet) GetConnection(id peer.ID, addr *ma.Multiaddr) (*peer.Peer, error) {
	return &peer.Peer{ID: id, Addresses: []*ma.Multiaddr{addr}}, nil
}

85
func TestGetFailures(t *testing.T) {
Jeromy's avatar
Jeromy committed
86 87 88 89
	fn := newFauxNet()
	fn.Listen()

	local := new(peer.Peer)
90
	local.ID = peer.ID("test_peer")
Jeromy's avatar
Jeromy committed
91 92 93

	d := NewDHT(local, fn)

94 95
	other := &peer.Peer{ID: peer.ID("other_peer")}

Jeromy's avatar
Jeromy committed
96 97
	d.Start()

98 99 100
	d.Update(other)

	// This one should time out
101
	_, err := d.GetValue(u.Key("test"), time.Millisecond*10)
Jeromy's avatar
Jeromy committed
102
	if err != nil {
103
		if err != u.ErrTimeout {
104 105 106 107
			t.Fatal("Got different error than we expected.")
		}
	} else {
		t.Fatal("Did not get expected error!")
Jeromy's avatar
Jeromy committed
108 109
	}

110
	// Reply with failures to every message
111 112 113 114 115 116 117
	fn.AddHandler(func(mes *swarm.Message) *swarm.Message {
		pmes := new(PBDHTMessage)
		err := proto.Unmarshal(mes.Data, pmes)
		if err != nil {
			t.Fatal(err)
		}

Chas Leichner's avatar
Chas Leichner committed
118
		resp := Message{
119
			Type:     pmes.GetType(),
Chas Leichner's avatar
Chas Leichner committed
120
			ID:       pmes.GetId(),
121 122 123 124 125 126 127
			Response: true,
			Success:  false,
		}
		return swarm.NewMessage(mes.Peer, resp.ToProtobuf())
	})

	// This one should fail with NotFound
128
	_, err = d.GetValue(u.Key("test"), time.Millisecond*1000)
129 130
	if err != nil {
		if err != u.ErrNotFound {
131
			t.Fatalf("Expected ErrNotFound, got: %s", err)
132 133 134 135
		}
	} else {
		t.Fatal("expected error, got none.")
	}
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152

	success := make(chan struct{})
	fn.handlers = nil
	fn.AddHandler(func(mes *swarm.Message) *swarm.Message {
		resp := new(PBDHTMessage)
		err := proto.Unmarshal(mes.Data, resp)
		if err != nil {
			t.Fatal(err)
		}
		if resp.GetSuccess() {
			t.Fatal("Get returned success when it shouldnt have.")
		}
		success <- struct{}{}
		return nil
	})

	// Now we test this DHT's handleGetValue failure
Chas Leichner's avatar
Chas Leichner committed
153
	req := Message{
154 155
		Type:  PBDHTMessage_GET_VALUE,
		Key:   "hello",
156
		ID:    swarm.GenerateMessageID(),
157 158 159 160 161
		Value: []byte{0},
	}
	fn.Chan.Incoming <- swarm.NewMessage(other, req.ToProtobuf())

	<-success
Jeromy's avatar
Jeromy committed
162
}
Jeromy's avatar
Jeromy committed
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230

// 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) {
	fn := newFauxNet()
	fn.Listen()

	local := new(peer.Peer)
	local.ID = peer.ID("test_peer")

	d := NewDHT(local, fn)
	d.Start()

	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
	fn.AddHandler(func(mes *swarm.Message) *swarm.Message {
		t.Log("Handling message...")
		pmes := new(PBDHTMessage)
		err := proto.Unmarshal(mes.Data, pmes)
		if err != nil {
			t.Fatal(err)
		}

		switch pmes.GetType() {
		case PBDHTMessage_GET_VALUE:
			resp := Message{
				Type:     pmes.GetType(),
				ID:       pmes.GetId(),
				Response: true,
				Success:  false,
			}

			for i := 0; i < 7; i++ {
				resp.Peers = append(resp.Peers, _randPeer())
			}
			return swarm.NewMessage(mes.Peer, resp.ToProtobuf())
		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.")
}
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291

// 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
	fn := newFauxNet()
	fn.Listen()

	local := new(peer.Peer)
	local.ID = peer.ID("test_peer")

	d := NewDHT(local, fn)
	d.Start()

	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
	fn.AddHandler(func(mes *swarm.Message) *swarm.Message {
		t.Log("Handling message...")
		pmes := new(PBDHTMessage)
		err := proto.Unmarshal(mes.Data, pmes)
		if err != nil {
			t.Fatal(err)
		}

		switch pmes.GetType() {
		case PBDHTMessage_GET_VALUE:
			resp := Message{
				Type:     pmes.GetType(),
				ID:       pmes.GetId(),
				Response: true,
				Success:  false,
				Peers:    []*peer.Peer{other},
			}

			return swarm.NewMessage(mes.Peer, resp.ToProtobuf())
		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.")
}