utils.go 2.46 KB
Newer Older
1 2 3 4
package testu

import (
	"bytes"
5
	"context"
6 7 8 9 10 11
	"fmt"
	"io"
	"io/ioutil"
	"testing"

	"github.com/ipfs/go-ipfs/importer/chunk"
12 13
	h "github.com/ipfs/go-ipfs/importer/helpers"
	trickle "github.com/ipfs/go-ipfs/importer/trickle"
14 15 16 17
	mdag "github.com/ipfs/go-ipfs/merkledag"
	mdagmock "github.com/ipfs/go-ipfs/merkledag/test"
	ft "github.com/ipfs/go-ipfs/unixfs"

18
	node "gx/ipfs/QmPN7cwmpcc4DWXb4KTB9dNAJgjuPY69h3npsMfhRrQL9c/go-ipld-format"
19
	u "gx/ipfs/QmSU6eubNdhXjFBJBSksTp8kv8YRub8mGAPv8tVJHmL2EU/go-ipfs-util"
20 21 22 23 24 25 26 27 28 29 30 31
)

func SizeSplitterGen(size int64) chunk.SplitterGen {
	return func(r io.Reader) chunk.Splitter {
		return chunk.NewSizeSplitter(r, size)
	}
}

func GetDAGServ() mdag.DAGService {
	return mdagmock.Mock()
}

32 33 34 35 36 37 38 39
type UseRawLeaves bool

const (
	ProtoBufLeaves UseRawLeaves = false
	RawLeaves      UseRawLeaves = true
)

func GetNode(t testing.TB, dserv mdag.DAGService, data []byte, rawLeaves UseRawLeaves) node.Node {
40
	in := bytes.NewReader(data)
41 42 43 44 45 46 47 48

	dbp := h.DagBuilderParams{
		Dagserv:   dserv,
		Maxlinks:  h.DefaultLinksPerBlock,
		RawLeaves: bool(rawLeaves),
	}

	node, err := trickle.TrickleLayout(dbp.New(SizeSplitterGen(500)(in)))
49 50 51 52 53 54 55
	if err != nil {
		t.Fatal(err)
	}

	return node
}

56 57
func GetEmptyNode(t testing.TB, dserv mdag.DAGService, rawLeaves UseRawLeaves) node.Node {
	return GetNode(t, dserv, []byte{}, rawLeaves)
58 59
}

60
func GetRandomNode(t testing.TB, dserv mdag.DAGService, size int64, rawLeaves UseRawLeaves) ([]byte, node.Node) {
61 62 63 64 65 66
	in := io.LimitReader(u.NewTimeSeededRand(), size)
	buf, err := ioutil.ReadAll(in)
	if err != nil {
		t.Fatal(err)
	}

67
	node := GetNode(t, dserv, buf, rawLeaves)
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
	return buf, node
}

func ArrComp(a, b []byte) error {
	if len(a) != len(b) {
		return fmt.Errorf("Arrays differ in length. %d != %d", len(a), len(b))
	}
	for i, v := range a {
		if v != b[i] {
			return fmt.Errorf("Arrays differ at index: %d", i)
		}
	}
	return nil
}

83
func PrintDag(nd *mdag.ProtoNode, ds mdag.DAGService, indent int) {
84 85 86 87 88 89 90 91 92
	pbd, err := ft.FromBytes(nd.Data())
	if err != nil {
		panic(err)
	}

	for i := 0; i < indent; i++ {
		fmt.Print(" ")
	}
	fmt.Printf("{size = %d, type = %s, children = %d", pbd.GetFilesize(), pbd.GetType().String(), len(pbd.GetBlocksizes()))
93
	if len(nd.Links()) > 0 {
94 95
		fmt.Println()
	}
96
	for _, lnk := range nd.Links() {
97 98 99 100
		child, err := lnk.GetNode(context.Background(), ds)
		if err != nil {
			panic(err)
		}
101
		PrintDag(child.(*mdag.ProtoNode), ds, indent+1)
102
	}
103
	if len(nd.Links()) > 0 {
104 105 106 107 108 109
		for i := 0; i < indent; i++ {
			fmt.Print(" ")
		}
	}
	fmt.Println("}")
}