coding_test.go 1 KB
Newer Older
Steven Allen's avatar
Steven Allen committed
1 2 3 4 5 6 7
package format

import (
	"errors"
	"testing"

	mh "github.com/multiformats/go-multihash"
tavit ohanian's avatar
tavit ohanian committed
8 9
	blocks "gitlab.dms3.io/dms3/public/go-block-format"
	cid "gitlab.dms3.io/dms3/public/go-cid"
Steven Allen's avatar
Steven Allen committed
10 11 12
)

func init() {
Steven Allen's avatar
Steven Allen committed
13
	Register(cid.Raw, func(b blocks.Block) (Node, error) {
Steven Allen's avatar
Steven Allen committed
14 15 16 17 18
		node := &EmptyNode{}
		if b.RawData() != nil || !b.Cid().Equals(node.Cid()) {
			return nil, errors.New("can only decode empty blocks")
		}
		return node, nil
Steven Allen's avatar
Steven Allen committed
19
	})
Steven Allen's avatar
Steven Allen committed
20 21 22 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
}

func TestDecode(t *testing.T) {
	id, err := cid.Prefix{
		Version:  1,
		Codec:    cid.Raw,
		MhType:   mh.ID,
		MhLength: 0,
	}.Sum(nil)

	if err != nil {
		t.Fatalf("failed to create cid: %s", err)
	}

	block, err := blocks.NewBlockWithCid(nil, id)
	if err != nil {
		t.Fatalf("failed to create empty block: %s", err)
	}
	node, err := Decode(block)
	if err != nil {
		t.Fatalf("failed to decode empty node: %s", err)
	}
	if !node.Cid().Equals(id) {
		t.Fatalf("empty node doesn't have the right cid")
	}

	if _, ok := node.(*EmptyNode); !ok {
		t.Fatalf("empty node doesn't have the right type")
	}

}