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

import (
	"context"
5 6
	"fmt"
	"reflect"
7 8 9 10 11 12 13 14 15 16 17 18 19 20
	"testing"
	"time"

	"github.com/ipfs/go-graphsync/testutil"
)

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()
	incomingResponses := make(chan ResponseProgress)
21
	incomingErrors := make(chan ResponseError)
22 23
	cancelRequest := func() {}

24 25
	outgoingResponses, outgoingErrors := rc.collectResponses(
		requestCtx, incomingResponses, incomingErrors, cancelRequest)
26 27 28 29 30 31 32 33 34 35 36

	blocks := testutil.GenerateBlocksOfSize(10, 100)

	for _, block := range blocks {
		select {
		case <-ctx.Done():
			t.Fatal("should have written to channel but couldn't")
		case incomingResponses <- block:
		}
	}

37 38
	interimError := fmt.Errorf("A block was missing")
	terminalError := fmt.Errorf("Something terrible happened")
39 40 41 42 43 44 45 46 47 48 49
	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:
	}

50 51 52 53 54 55 56 57 58 59
	for _, block := range blocks {
		select {
		case <-ctx.Done():
			t.Fatal("should have read from channel but couldn't")
		case testBlock := <-outgoingResponses:
			if testBlock.Cid() != block.Cid() {
				t.Fatal("stored blocks incorrectly")
			}
		}
	}
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76

	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")
				}
			}
		}
	}
77
}