/
mock.go
101 lines (86 loc) · 2.35 KB
/
mock.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package coremock
import (
"context"
"fmt"
"io/ioutil"
libp2p2 "github.com/ipfs/go-ipfs/core/node/libp2p"
"github.com/ipfs/go-ipfs/commands"
"github.com/ipfs/go-ipfs/core"
"github.com/ipfs/go-ipfs/repo"
"github.com/ipfs/go-datastore"
syncds "github.com/ipfs/go-datastore/sync"
config "github.com/ipfs/go-ipfs-config"
"github.com/libp2p/go-libp2p"
host "github.com/libp2p/go-libp2p-core/host"
peer "github.com/libp2p/go-libp2p-core/peer"
pstore "github.com/libp2p/go-libp2p-core/peerstore"
testutil "github.com/libp2p/go-libp2p-testing/net"
mocknet "github.com/libp2p/go-libp2p/p2p/net/mock"
)
// NewMockNode constructs an IpfsNode for use in tests.
func NewMockNode() (*core.IpfsNode, error) {
ctx := context.Background()
// effectively offline, only peer in its network
return core.NewNode(ctx, &core.BuildCfg{
Online: true,
Host: MockHostOption(mocknet.New(ctx)),
})
}
func MockHostOption(mn mocknet.Mocknet) libp2p2.HostOption {
return func(ctx context.Context, id peer.ID, ps pstore.Peerstore, _ ...libp2p.Option) (host.Host, error) {
return mn.AddPeerWithPeerstore(id, ps)
}
}
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(),
},
}
r := &repo.Mock{
D: syncds.MutexWrap(datastore.NewMapDatastore()),
C: conf,
}
node, err := core.NewNode(context.Background(), &core.BuildCfg{
Repo: r,
})
if err != nil {
return commands.Context{}, err
}
return commands.Context{
ConfigRoot: "/tmp/.mockipfsconfig",
LoadConfig: func(path string) (*config.Config, error) {
return &conf, nil
},
ConstructNode: func() (*core.IpfsNode, error) {
return node, nil
},
}, nil
}
func MockPublicNode(ctx context.Context, mn mocknet.Mocknet) (*core.IpfsNode, error) {
ds := syncds.MutexWrap(datastore.NewMapDatastore())
cfg, err := config.Init(ioutil.Discard, 2048)
if err != nil {
return nil, err
}
count := len(mn.Peers())
cfg.Addresses.Swarm = []string{
fmt.Sprintf("/ip4/18.0.%d.%d/tcp/4001", count>>16, count&0xFF),
}
cfg.Datastore = config.Datastore{}
return core.NewNode(ctx, &core.BuildCfg{
Online: true,
Routing: libp2p2.DHTServerOption,
Repo: &repo.Mock{
C: *cfg,
D: ds,
},
Host: MockHostOption(mn),
})
}