batch_test.go 1.83 KB
Newer Older
Steven Allen's avatar
Steven Allen committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
package format

import (
	"context"
	"sync"
	"testing"

	cid "github.com/ipfs/go-cid"
)

// Test dag
type testDag struct {
	mu    sync.Mutex
	nodes map[string]Node
}

func newTestDag() *testDag {
	return &testDag{nodes: make(map[string]Node)}
}

func (d *testDag) Get(ctx context.Context, cid *cid.Cid) (Node, error) {
	d.mu.Lock()
	defer d.mu.Unlock()
	if n, ok := d.nodes[cid.KeyString()]; ok {
		return n, nil
	}
	return nil, ErrNotFound
}

func (d *testDag) GetMany(ctx context.Context, cids []*cid.Cid) <-chan *NodeOption {
	d.mu.Lock()
	defer d.mu.Unlock()
	out := make(chan *NodeOption, len(cids))
	for _, c := range cids {
		if n, ok := d.nodes[c.KeyString()]; ok {
			out <- &NodeOption{Node: n}
		} else {
			out <- &NodeOption{Err: ErrNotFound}
		}
	}
	return out
}

Steven Allen's avatar
Steven Allen committed
44
func (d *testDag) Add(node Node) error {
Steven Allen's avatar
Steven Allen committed
45 46
	d.mu.Lock()
	defer d.mu.Unlock()
Steven Allen's avatar
Steven Allen committed
47 48
	d.nodes[node.Cid().KeyString()] = node
	return nil
Steven Allen's avatar
Steven Allen committed
49 50
}

Steven Allen's avatar
Steven Allen committed
51
func (d *testDag) AddMany(nodes []Node) error {
Steven Allen's avatar
Steven Allen committed
52 53
	d.mu.Lock()
	defer d.mu.Unlock()
Steven Allen's avatar
Steven Allen committed
54 55
	for _, n := range nodes {
		d.nodes[n.Cid().KeyString()] = n
Steven Allen's avatar
Steven Allen committed
56
	}
Steven Allen's avatar
Steven Allen committed
57
	return nil
Steven Allen's avatar
Steven Allen committed
58 59 60 61 62
}

func (d *testDag) Remove(c *cid.Cid) error {
	d.mu.Lock()
	defer d.mu.Unlock()
Steven Allen's avatar
Steven Allen committed
63
	delete(d.nodes, c.KeyString())
Steven Allen's avatar
Steven Allen committed
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 92 93 94 95 96 97
	return nil
}

var _ DAGService = new(testDag)

func TestBatch(t *testing.T) {
	d := newTestDag()
	b := NewBatch(d)
	for i := 0; i < 1000; i++ {
		// It would be great if we could use *many* different nodes here
		// but we can't add any dependencies and I don't feel like adding
		// any more testing code.
		if _, err := b.Add(new(EmptyNode)); err != nil {
			t.Fatal(err)
		}
	}
	if err := b.Commit(); err != nil {
		t.Fatal(err)
	}

	n, err := d.Get(context.Background(), new(EmptyNode).Cid())
	if err != nil {
		t.Fatal(err)
	}
	switch n.(type) {
	case *EmptyNode:
	default:
		t.Fatal("expected the node to exist in the dag")
	}

	if len(d.nodes) != 1 {
		t.Fatal("should have one node")
	}
}