blocks_test.go 1.8 KB
Newer Older
1 2
package blocks

Jakub Sztandera's avatar
Jakub Sztandera committed
3 4 5 6
import (
	"bytes"
	"testing"

7 8
	mh "gx/ipfs/QmYDds3421prZgqKbLpEK7T9Aa2eVdQ7o3YarX1LVLdP2J/go-multihash"
	u "gx/ipfs/Qmb912gdngC1UWwTkhuW8knyRbcWeu5kqkxBpveLmW8bSr/go-ipfs-util"
Jeromy's avatar
Jeromy committed
9
	cid "gx/ipfs/QmcTcsTvfaeEBRFo1TkFgT8sRmgi1n1LTZpecfVP8fzpGD/go-cid"
Jakub Sztandera's avatar
Jakub Sztandera committed
10
)
11 12 13 14 15

func TestBlocksBasic(t *testing.T) {

	// Test empty data
	empty := []byte{}
16
	NewBlock(empty)
17 18

	// Test nil case
19
	NewBlock(nil)
20 21

	// Test some data
22
	NewBlock([]byte("Hello world!"))
23
}
Jakub Sztandera's avatar
Jakub Sztandera committed
24 25 26 27 28

func TestData(t *testing.T) {
	data := []byte("some data")
	block := NewBlock(data)

Jeromy's avatar
Jeromy committed
29
	if !bytes.Equal(block.RawData(), data) {
Jakub Sztandera's avatar
Jakub Sztandera committed
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
		t.Error("data is wrong")
	}
}

func TestHash(t *testing.T) {
	data := []byte("some other data")
	block := NewBlock(data)

	hash, err := mh.Sum(data, mh.SHA2_256, -1)
	if err != nil {
		t.Fatal(err)
	}

	if !bytes.Equal(block.Multihash(), hash) {
		t.Error("wrong multihash")
	}
}

48
func TestCid(t *testing.T) {
Jakub Sztandera's avatar
Jakub Sztandera committed
49 50
	data := []byte("yet another data")
	block := NewBlock(data)
51
	c := block.Cid()
Jakub Sztandera's avatar
Jakub Sztandera committed
52

53
	if !bytes.Equal(block.Multihash(), c.Hash()) {
Jakub Sztandera's avatar
Jakub Sztandera committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
		t.Error("key contains wrong data")
	}
}

func TestManualHash(t *testing.T) {
	oldDebugState := u.Debug
	defer (func() {
		u.Debug = oldDebugState
	})()

	data := []byte("I can't figure out more names .. data")
	hash, err := mh.Sum(data, mh.SHA2_256, -1)
	if err != nil {
		t.Fatal(err)
	}

70 71
	c := cid.NewCidV0(hash)

Jakub Sztandera's avatar
Jakub Sztandera committed
72
	u.Debug = false
73
	block, err := NewBlockWithCid(data, c)
Jakub Sztandera's avatar
Jakub Sztandera committed
74 75 76 77 78 79 80 81 82
	if err != nil {
		t.Fatal(err)
	}

	if !bytes.Equal(block.Multihash(), hash) {
		t.Error("wrong multihash")
	}

	data[5] = byte((uint32(data[5]) + 5) % 256) // Transfrom hash to be different
83
	block, err = NewBlockWithCid(data, c)
Jakub Sztandera's avatar
Jakub Sztandera committed
84 85 86 87 88 89 90 91 92 93
	if err != nil {
		t.Fatal(err)
	}

	if !bytes.Equal(block.Multihash(), hash) {
		t.Error("wrong multihash")
	}

	u.Debug = true

94
	block, err = NewBlockWithCid(data, c)
95
	if err != ErrWrongHash {
Jakub Sztandera's avatar
Jakub Sztandera committed
96 97 98 99
		t.Fatal(err)
	}

}