utils.go 2.04 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
package testu

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"testing"

	imp "github.com/ipfs/go-ipfs/importer"
	"github.com/ipfs/go-ipfs/importer/chunk"
	mdag "github.com/ipfs/go-ipfs/merkledag"
	mdagmock "github.com/ipfs/go-ipfs/merkledag/test"
	ft "github.com/ipfs/go-ipfs/unixfs"

16 17
	context "context"
	u "gx/ipfs/Qmb912gdngC1UWwTkhuW8knyRbcWeu5kqkxBpveLmW8bSr/go-ipfs-util"
18 19 20 21 22 23 24 25 26 27 28 29
)

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()
}

30
func GetNode(t testing.TB, dserv mdag.DAGService, data []byte) *mdag.ProtoNode {
31 32 33 34 35 36 37 38 39
	in := bytes.NewReader(data)
	node, err := imp.BuildTrickleDagFromReader(dserv, SizeSplitterGen(500)(in))
	if err != nil {
		t.Fatal(err)
	}

	return node
}

40
func GetEmptyNode(t testing.TB, dserv mdag.DAGService) *mdag.ProtoNode {
41 42 43
	return GetNode(t, dserv, []byte{})
}

44
func GetRandomNode(t testing.TB, dserv mdag.DAGService, size int64) ([]byte, *mdag.ProtoNode) {
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
	in := io.LimitReader(u.NewTimeSeededRand(), size)
	buf, err := ioutil.ReadAll(in)
	if err != nil {
		t.Fatal(err)
	}

	node := GetNode(t, dserv, buf)
	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
}

67
func PrintDag(nd *mdag.ProtoNode, ds mdag.DAGService, indent int) {
68 69 70 71 72 73 74 75 76
	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()))
77
	if len(nd.Links()) > 0 {
78 79
		fmt.Println()
	}
80
	for _, lnk := range nd.Links() {
81 82 83 84
		child, err := lnk.GetNode(context.Background(), ds)
		if err != nil {
			panic(err)
		}
85
		PrintDag(child.(*mdag.ProtoNode), ds, indent+1)
86
	}
87
	if len(nd.Links()) > 0 {
88 89 90 91 92 93
		for i := 0; i < indent; i++ {
			fmt.Print(" ")
		}
	}
	fmt.Println("}")
}