mock.go 1.95 KB
Newer Older
1
package coremock
2 3

import (
4 5
	"net"

6 7 8
	"github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
	syncds "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore/sync"
	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
9

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
10
	commands "github.com/ipfs/go-ipfs/commands"
11
	core "github.com/ipfs/go-ipfs/core"
12 13
	metrics "github.com/ipfs/go-ipfs/metrics"
	host "github.com/ipfs/go-ipfs/p2p/host"
14 15 16
	mocknet "github.com/ipfs/go-ipfs/p2p/net/mock"
	peer "github.com/ipfs/go-ipfs/p2p/peer"
	"github.com/ipfs/go-ipfs/repo"
17
	config "github.com/ipfs/go-ipfs/repo/config"
18 19
	ds2 "github.com/ipfs/go-ipfs/util/datastore2"
	testutil "github.com/ipfs/go-ipfs/util/testutil"
20 21
)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
22
// NewMockNode constructs an IpfsNode for use in tests.
23
func NewMockNode() (*core.IpfsNode, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
24
	ctx := context.Background()
25

26 27 28 29 30 31
	// effectively offline, only peer in its network
	return core.NewNode(ctx, &core.BuildCfg{
		Online: true,
		Host:   MockHostOption(mocknet.New(ctx)),
	})
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
32

33 34 35
func MockHostOption(mn mocknet.Mocknet) core.HostOption {
	return func(ctx context.Context, id peer.ID, ps peer.Peerstore, bwr metrics.Reporter, fs []*net.IPNet) (host.Host, error) {
		return mn.AddPeerWithPeerstore(id, ps)
36
	}
37
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

func MockCmdsCtx() (commands.Context, error) {
	// Generate Identity
	ident, err := testutil.RandIdentity()
	if err != nil {
		return commands.Context{}, err
	}
	p := ident.ID()

	conf := config.Config{
		Identity: config.Identity{
			PeerID: p.String(),
		},
	}

53
	r := &repo.Mock{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
54 55
		D: ds2.CloserWrap(syncds.MutexWrap(datastore.NewMapDatastore())),
		C: conf,
56 57 58 59 60
	}

	node, err := core.NewNode(context.Background(), &core.BuildCfg{
		Repo: r,
	})
61 62 63
	if err != nil {
		return commands.Context{}, err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
64 65 66 67 68 69 70 71 72 73 74 75

	return commands.Context{
		Online:     true,
		ConfigRoot: "/tmp/.mockipfsconfig",
		LoadConfig: func(path string) (*config.Config, error) {
			return &conf, nil
		},
		ConstructNode: func() (*core.IpfsNode, error) {
			return node, nil
		},
	}, nil
}