provider_test.go 1.64 KB
Newer Older
Erik Ingenito's avatar
Erik Ingenito committed
1 2 3 4 5 6 7
package provider

import (
	"context"
	"math/rand"
	"testing"
	"time"
8 9 10 11 12 13

	blocksutil "github.com/ipfs/go-ipfs-blocksutil"
	cid "github.com/ipfs/go-cid"
	datastore "github.com/ipfs/go-datastore"
	pstore "github.com/libp2p/go-libp2p-peerstore"
	sync "github.com/ipfs/go-datastore/sync"
Erik Ingenito's avatar
Erik Ingenito committed
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
)

var blockGenerator = blocksutil.NewBlockGenerator()

type mockRouting struct {
	provided chan cid.Cid
}

func mockContentRouting() *mockRouting {
	r := mockRouting{}
	r.provided = make(chan cid.Cid)
	return &r
}

func TestAnnouncement(t *testing.T) {
	ctx := context.Background()
30
	defer ctx.Done()
Erik Ingenito's avatar
Erik Ingenito committed
31

32 33
	ds := sync.MutexWrap(datastore.NewMapDatastore())
	queue, err := NewQueue(ctx, "test", ds)
Erik Ingenito's avatar
Erik Ingenito committed
34 35 36 37 38 39 40 41 42 43 44
	if err != nil {
		t.Fatal(err)
	}

	r := mockContentRouting()

	provider := NewProvider(ctx, queue, r)
	provider.Run()

	cids := cid.NewSet()

Erik Ingenito's avatar
Erik Ingenito committed
45
	for i := 0; i < 1000; i++ {
Erik Ingenito's avatar
Erik Ingenito committed
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
		c := blockGenerator.Next().Cid()
		cids.Add(c)
	}

	go func() {
		for _, c := range cids.Keys() {
			err = provider.Provide(c)
			// A little goroutine stirring to exercise some different states
			r := rand.Intn(10)
			time.Sleep(time.Microsecond * time.Duration(r))
		}
	}()

	for cids.Len() > 0 {
		select {
			case cp := <-r.provided:
				if !cids.Has(cp) {
					t.Fatal("Wrong CID provided")
				}
				cids.Remove(cp)
Erik Ingenito's avatar
Erik Ingenito committed
66
			case <-time.After(time.Second * 5):
Erik Ingenito's avatar
Erik Ingenito committed
67 68 69 70 71 72 73 74 75 76 77 78 79 80
				t.Fatal("Timeout waiting for cids to be provided.")
		}
	}
}

func (r *mockRouting) Provide(ctx context.Context, cid cid.Cid, recursive bool) error {
	r.provided <- cid
	return nil
}

// Search for peers who are able to provide a given key
func (r *mockRouting) FindProvidersAsync(ctx context.Context, cid cid.Cid, timeout int) <-chan pstore.PeerInfo {
	return nil
}