blocks_test.go 1.72 KB
Newer Older
1 2
package blocks

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

	mh "gx/ipfs/QmYf7ng2hG5XBtJA3tN34DQ2GUN5HNksEw1rLDkmr6vGku/go-multihash"
	u "gx/ipfs/QmZNVWh8LLjAavuQ2JXuFmuYH3C11xo988vSgp7UQrTRj1/go-ipfs-util"
)
10 11 12 13 14

func TestBlocksBasic(t *testing.T) {

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

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

	// Test some data
21
	NewBlock([]byte("Hello world!"))
22
}
Jakub Sztandera's avatar
Jakub Sztandera committed
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

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

	if !bytes.Equal(block.Data(), data) {
		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")
	}
}

func TestKey(t *testing.T) {
	data := []byte("yet another data")
	block := NewBlock(data)
	key := block.Key()

	if !bytes.Equal(block.Multihash(), key.ToMultihash()) {
		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)
	}

	u.Debug = false
	block, err := NewBlockWithHash(data, hash)
	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
	block, err = NewBlockWithHash(data, hash)
	if err != nil {
		t.Fatal(err)
	}

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

	u.Debug = true

	block, err = NewBlockWithHash(data, hash)
92
	if err != ErrWrongHash {
Jakub Sztandera's avatar
Jakub Sztandera committed
93 94 95 96
		t.Fatal(err)
	}

}