github.com/keltia/go-ipfs@v0.3.8-0.20150909044612-210793031c63/core/mock/mock.go (about)

     1  package coremock
     2  
     3  import (
     4  	"net"
     5  
     6  	"github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
     7  	syncds "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore/sync"
     8  	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
     9  
    10  	commands "github.com/ipfs/go-ipfs/commands"
    11  	core "github.com/ipfs/go-ipfs/core"
    12  	metrics "github.com/ipfs/go-ipfs/metrics"
    13  	host "github.com/ipfs/go-ipfs/p2p/host"
    14  	mocknet "github.com/ipfs/go-ipfs/p2p/net/mock"
    15  	peer "github.com/ipfs/go-ipfs/p2p/peer"
    16  	"github.com/ipfs/go-ipfs/repo"
    17  	config "github.com/ipfs/go-ipfs/repo/config"
    18  	ds2 "github.com/ipfs/go-ipfs/util/datastore2"
    19  	testutil "github.com/ipfs/go-ipfs/util/testutil"
    20  )
    21  
    22  // NewMockNode constructs an IpfsNode for use in tests.
    23  func NewMockNode() (*core.IpfsNode, error) {
    24  	ctx := context.Background()
    25  
    26  	// effectively offline, only peer in its network
    27  	return core.NewNode(ctx, &core.BuildCfg{
    28  		Online: true,
    29  		Host:   MockHostOption(mocknet.New(ctx)),
    30  	})
    31  }
    32  
    33  func MockHostOption(mn mocknet.Mocknet) core.HostOption {
    34  	return func(ctx context.Context, id peer.ID, ps peer.Peerstore, bwr metrics.Reporter, fs []*net.IPNet) (host.Host, error) {
    35  		return mn.AddPeerWithPeerstore(id, ps)
    36  	}
    37  }
    38  
    39  func MockCmdsCtx() (commands.Context, error) {
    40  	// Generate Identity
    41  	ident, err := testutil.RandIdentity()
    42  	if err != nil {
    43  		return commands.Context{}, err
    44  	}
    45  	p := ident.ID()
    46  
    47  	conf := config.Config{
    48  		Identity: config.Identity{
    49  			PeerID: p.String(),
    50  		},
    51  	}
    52  
    53  	r := &repo.Mock{
    54  		D: ds2.CloserWrap(syncds.MutexWrap(datastore.NewMapDatastore())),
    55  		C: conf,
    56  	}
    57  
    58  	node, err := core.NewNode(context.Background(), &core.BuildCfg{
    59  		Repo: r,
    60  	})
    61  
    62  	return commands.Context{
    63  		Online:     true,
    64  		ConfigRoot: "/tmp/.mockipfsconfig",
    65  		LoadConfig: func(path string) (*config.Config, error) {
    66  			return &conf, nil
    67  		},
    68  		ConstructNode: func() (*core.IpfsNode, error) {
    69  			return node, nil
    70  		},
    71  	}, nil
    72  }