testutils.go 1.84 KB
Newer Older
1 2 3
package bitswap

import (
4
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
5 6 7 8 9 10 11 12 13 14 15 16 17 18
	ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
	ds_sync "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore/sync"
	"github.com/jbenet/go-ipfs/blocks/blockstore"
	"github.com/jbenet/go-ipfs/exchange"
	tn "github.com/jbenet/go-ipfs/exchange/bitswap/testnet"
	"github.com/jbenet/go-ipfs/peer"
	"github.com/jbenet/go-ipfs/routing/mock"
)

func NewSessionGenerator(
	net tn.Network, rs mock.RoutingServer) SessionGenerator {
	return SessionGenerator{
		net: net,
		rs:  rs,
19
		ps:  peer.NewPeerstore(),
20 21 22 23 24 25 26 27
		seq: 0,
	}
}

type SessionGenerator struct {
	seq int
	net tn.Network
	rs  mock.RoutingServer
28
	ps  peer.Peerstore
29 30 31 32
}

func (g *SessionGenerator) Next() Instance {
	g.seq++
33
	return session(g.net, g.rs, g.ps, []byte(string(g.seq)))
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
}

func (g *SessionGenerator) Instances(n int) []Instance {
	instances := make([]Instance, 0)
	for j := 0; j < n; j++ {
		inst := g.Next()
		instances = append(instances, inst)
	}
	return instances
}

type Instance struct {
	Peer       peer.Peer
	Exchange   exchange.Interface
	Blockstore blockstore.Blockstore
}

// session creates a test bitswap session.
//
// NB: It's easy make mistakes by providing the same peer ID to two different
// sessions. To safeguard, use the SessionGenerator to generate sessions. It's
// just a much better idea.
56 57
func session(net tn.Network, rs mock.RoutingServer, ps peer.Peerstore, id peer.ID) Instance {
	p := ps.WithID(id)
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73

	adapter := net.Adapter(p)
	htc := rs.Client(p)
	bstore := blockstore.NewBlockstore(ds_sync.MutexWrap(ds.NewMapDatastore()))

	const alwaysSendToPeer = true
	ctx := context.TODO()

	bs := New(ctx, p, adapter, htc, bstore, alwaysSendToPeer)

	return Instance{
		Peer:       p,
		Exchange:   bs,
		Blockstore: bstore,
	}
}