queue_test.go 1.63 KB
Newer Older
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 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
package provider

import (
	"context"
	"testing"
	"time"

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

func makeCids(n int) []cid.Cid {
	cids := make([]cid.Cid, 0, 10)
	for i := 0; i < 10; i++ {
		c := blockGenerator.Next().Cid()
		cids = append(cids, c)
	}
	return cids
}

func assertOrdered(cids []cid.Cid, q *Queue, t *testing.T) {
	for _, c := range cids {
		select {
		case dequeued := <- q.dequeue:
			if c != dequeued.cid {
				t.Fatalf("Error in ordering of CIDs retrieved from queue. Expected: %s, got: %s", c, dequeued.cid)
			}

		case <-time.After(time.Second * 1):
			t.Fatal("Timeout waiting for cids to be provided.")
		}
	}
}

func TestBasicOperation(t *testing.T) {
	ctx := context.Background()
	defer ctx.Done()

	ds := sync.MutexWrap(datastore.NewMapDatastore())
	queue, err := NewQueue(ctx, "test", ds)
	if err != nil {
		t.Fatal(err)
	}
	queue.Run()

	cids := makeCids(10)

	for _, c := range cids {
		err = queue.Enqueue(c)
		if err != nil {
			t.Fatal("Failed to enqueue CID")
		}
	}

	assertOrdered(cids, queue, t)
}

func TestInitialization(t *testing.T) {
	ctx := context.Background()
	defer ctx.Done()

	ds := sync.MutexWrap(datastore.NewMapDatastore())
	queue, err := NewQueue(ctx, "test", ds)
	if err != nil {
		t.Fatal(err)
	}
	queue.Run()

	cids := makeCids(10)

	for _, c := range cids {
		err = queue.Enqueue(c)
		if err != nil {
			t.Fatal("Failed to enqueue CID")
		}
	}

	assertOrdered(cids[:5], queue, t)

	// make a new queue, same data
	queue, err = NewQueue(ctx, "test", ds)
	if err != nil {
		t.Fatal(err)
	}
	queue.Run()

	assertOrdered(cids[5:], queue, t)
}