responsecollector_test.go 2.34 KB
Newer Older
1 2 3 4
package requestmanager

import (
	"context"
5 6
	"fmt"
	"reflect"
7 8 9
	"testing"
	"time"

10
	"github.com/ipfs/go-graphsync"
11
	"github.com/ipfs/go-graphsync/testutil"
12
	ipld "github.com/ipld/go-ipld-prime"
13
	cidlink "github.com/ipld/go-ipld-prime/linking/cid"
14 15 16 17 18 19 20 21 22
)

func TestBufferingResponseProgress(t *testing.T) {
	backgroundCtx := context.Background()
	ctx, cancel := context.WithTimeout(backgroundCtx, time.Second)
	defer cancel()
	rc := newResponseCollector(ctx)
	requestCtx, requestCancel := context.WithCancel(backgroundCtx)
	defer requestCancel()
23
	incomingResponses := make(chan graphsync.ResponseProgress)
24
	incomingErrors := make(chan error)
25 26
	cancelRequest := func() {}

27 28
	outgoingResponses, outgoingErrors := rc.collectResponses(
		requestCtx, incomingResponses, incomingErrors, cancelRequest)
29

30
	blockStore := make(map[ipld.Link][]byte)
31
	loader, storer := testutil.NewTestStore(blockStore)
32 33
	blockChain := testutil.SetupBlockChain(ctx, t, loader, storer, 100, 10)
	blocks := blockChain.AllBlocks()
34

35
	for i, block := range blocks {
36 37 38
		select {
		case <-ctx.Done():
			t.Fatal("should have written to channel but couldn't")
39
		case incomingResponses <- graphsync.ResponseProgress{
40
			Node: blockChain.NodeTipIndex(i),
41
			LastBlock: struct {
42 43
				Path ipld.Path
				Link ipld.Link
44 45
			}{ipld.Path{}, cidlink.Link{Cid: block.Cid()}},
		}:
46 47 48
		}
	}

49 50
	interimError := fmt.Errorf("A block was missing")
	terminalError := fmt.Errorf("Something terrible happened")
51 52 53 54 55 56 57 58 59 60 61
	select {
	case <-ctx.Done():
		t.Fatal("should have written error to channel but didn't")
	case incomingErrors <- interimError:
	}
	select {
	case <-ctx.Done():
		t.Fatal("should have written error to channel but didn't")
	case incomingErrors <- terminalError:
	}

62 63 64 65
	for _, block := range blocks {
		select {
		case <-ctx.Done():
			t.Fatal("should have read from channel but couldn't")
66 67
		case testResponse := <-outgoingResponses:
			if testResponse.LastBlock.Link.(cidlink.Link).Cid != block.Cid() {
68 69 70 71
				t.Fatal("stored blocks incorrectly")
			}
		}
	}
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88

	for i := 0; i < 2; i++ {
		select {
		case <-ctx.Done():
			t.Fatal("should have read from channel but couldn't")
		case testErr := <-outgoingErrors:
			if i == 0 {
				if !reflect.DeepEqual(testErr, interimError) {
					t.Fatal("incorrect error message sent")
				}
			} else {
				if !reflect.DeepEqual(testErr, terminalError) {
					t.Fatal("incorrect error message sent")
				}
			}
		}
	}
89
}