importer_test.go 2.08 KB
Newer Older
1 2 3 4 5
package importer

import (
	"bytes"
	"crypto/rand"
6
	"fmt"
7 8
	"io"
	"io/ioutil"
9
	"os"
10 11
	"testing"

12 13
	"github.com/jbenet/go-ipfs/importer/chunk"
	uio "github.com/jbenet/go-ipfs/unixfs/io"
14 15
)

16 17 18
// NOTE:
// These tests tests a combination of unixfs/io/dagreader and importer/chunk.
// Maybe split them up somehow?
19 20 21
func TestBuildDag(t *testing.T) {
	td := os.TempDir()
	fi, err := os.Create(td + "/tmpfi")
22 23 24
	if err != nil {
		t.Fatal(err)
	}
25 26

	_, err = io.CopyN(fi, rand.Reader, 1024*1024)
27 28 29 30
	if err != nil {
		t.Fatal(err)
	}

31 32 33
	fi.Close()

	_, err = NewDagFromFile(td + "/tmpfi")
34 35 36
	if err != nil {
		t.Fatal(err)
	}
37
}
38

39 40
//Test where calls to read are smaller than the chunk size
func TestSizeBasedSplit(t *testing.T) {
41
	bs := &chunk.SizeSplitter{512}
42
	testFileConsistency(t, bs, 32*512)
43
	bs = &chunk.SizeSplitter{4096}
44 45 46 47 48 49
	testFileConsistency(t, bs, 32*4096)

	// Uneven offset
	testFileConsistency(t, bs, 31*4095)
}

Jeromy's avatar
Jeromy committed
50 51 52 53 54 55
func dup(b []byte) []byte {
	o := make([]byte, len(b))
	copy(o, b)
	return o
}

56
func testFileConsistency(t *testing.T, bs chunk.BlockSplitter, nbytes int) {
57
	buf := new(bytes.Buffer)
58
	io.CopyN(buf, rand.Reader, int64(nbytes))
Jeromy's avatar
Jeromy committed
59
	should := dup(buf.Bytes())
60
	nd, err := NewDagFromReaderWithSplitter(buf, bs)
61 62 63
	if err != nil {
		t.Fatal(err)
	}
64
	r, err := uio.NewDagReader(nd, nil)
65 66 67 68 69 70 71 72 73
	if err != nil {
		t.Fatal(err)
	}

	out, err := ioutil.ReadAll(r)
	if err != nil {
		t.Fatal(err)
	}

74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
	err = arrComp(out, should)
	if err != nil {
		t.Fatal(err)
	}
}

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
}

func TestMaybeRabinConsistency(t *testing.T) {
93
	testFileConsistency(t, chunk.NewMaybeRabin(4096), 256*4096)
94
}
95 96 97 98 99

func TestRabinBlockSize(t *testing.T) {
	buf := new(bytes.Buffer)
	nbytes := 1024 * 1024
	io.CopyN(buf, rand.Reader, int64(nbytes))
100
	rab := chunk.NewMaybeRabin(4096)
101 102 103 104 105 106 107 108 109 110
	blkch := rab.Split(buf)

	var blocks [][]byte
	for b := range blkch {
		blocks = append(blocks, b)
	}

	fmt.Printf("Avg block size: %d\n", nbytes/len(blocks))

}