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

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

	cid "github.com/ipfs/go-cid"
	datastore "github.com/ipfs/go-datastore"
	sync "github.com/ipfs/go-datastore/sync"
Erik Ingenito's avatar
Gofmt  
Erik Ingenito committed
12 13
	blocksutil "github.com/ipfs/go-ipfs-blocksutil"
	pstore "github.com/libp2p/go-libp2p-peerstore"
14 15 16 17

	q "github.com/ipfs/go-ipfs/provider/queue"

	. "github.com/ipfs/go-ipfs/provider/simple"
Erik Ingenito's avatar
Erik Ingenito committed
18 19 20 21 22 23 24 25
)

var blockGenerator = blocksutil.NewBlockGenerator()

type mockRouting struct {
	provided chan cid.Cid
}

Erik Ingenito's avatar
Erik Ingenito committed
26 27 28 29 30 31 32 33 34
func (r *mockRouting) Provide(ctx context.Context, cid cid.Cid, recursive bool) error {
	r.provided <- cid
	return nil
}

func (r *mockRouting) FindProvidersAsync(ctx context.Context, cid cid.Cid, timeout int) <-chan pstore.PeerInfo {
	return nil
}

Erik Ingenito's avatar
Erik Ingenito committed
35 36 37 38 39 40 41 42
func mockContentRouting() *mockRouting {
	r := mockRouting{}
	r.provided = make(chan cid.Cid)
	return &r
}

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

45
	ds := sync.MutexWrap(datastore.NewMapDatastore())
46
	queue, err := q.NewQueue(ctx, "test", ds)
Erik Ingenito's avatar
Erik Ingenito committed
47 48 49 50 51 52
	if err != nil {
		t.Fatal(err)
	}

	r := mockContentRouting()

53 54
	prov := NewProvider(ctx, queue, r)
	prov.Run()
Erik Ingenito's avatar
Erik Ingenito committed
55 56 57

	cids := cid.NewSet()

58
	for i := 0; i < 100; i++ {
Erik Ingenito's avatar
Erik Ingenito committed
59 60 61 62 63 64
		c := blockGenerator.Next().Cid()
		cids.Add(c)
	}

	go func() {
		for _, c := range cids.Keys() {
65
			err = prov.Provide(c)
Erik Ingenito's avatar
Erik Ingenito committed
66 67 68 69 70 71 72 73
			// 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 {
Erik Ingenito's avatar
Gofmt  
Erik Ingenito committed
74 75 76 77 78 79 80
		case cp := <-r.provided:
			if !cids.Has(cp) {
				t.Fatal("Wrong CID provided")
			}
			cids.Remove(cp)
		case <-time.After(time.Second * 5):
			t.Fatal("Timeout waiting for cids to be provided.")
Erik Ingenito's avatar
Erik Ingenito committed
81 82 83
		}
	}
}