api.go 1.88 KB
Newer Older
1 2 3 4
package tests

import (
	"context"
5
	"errors"
6
	"testing"
7
	"time"
8 9 10 11

	coreiface "github.com/ipfs/go-ipfs/core/coreapi/interface"
)

12 13
var apiNotImplemented = errors.New("api not implemented")

14 15
func (tp *provider) makeAPI(ctx context.Context) (coreiface.CoreAPI, error) {
	api, err := tp.MakeAPISwarm(ctx, false, 1)
16 17 18 19
	if err != nil {
		return nil, err
	}

20
	return api[0], nil
21 22
}

23 24 25
type Provider interface {
	// Make creates n nodes. fullIdentity set to false can be ignored
	MakeAPISwarm(ctx context.Context, fullIdentity bool, n int) ([]coreiface.CoreAPI, error)
26 27
}

28 29 30 31 32 33 34 35 36 37
func (tp *provider) MakeAPISwarm(ctx context.Context, fullIdentity bool, n int) ([]coreiface.CoreAPI, error) {
	tp.apis <- 1
	go func() {
		<-ctx.Done()
		tp.apis <- -1
	}()

	return tp.Provider.MakeAPISwarm(ctx, fullIdentity, n)
}

38 39
type provider struct {
	Provider
40 41

	apis chan int
42
}
43

44
func TestApi(p Provider) func(t *testing.T) {
45 46 47 48 49 50 51 52 53 54 55 56 57 58
	running := 1
	apis := make(chan int)
	zeroRunning := make(chan struct{})
	go func() {
		for i := range apis {
			running += i
			if running < 1 {
				close(zeroRunning)
				return
			}
		}
	}()

	tp := &provider{Provider: p, apis: apis}
59 60 61 62 63 64 65 66 67 68 69 70

	return func(t *testing.T) {
		t.Run("Block", tp.TestBlock)
		t.Run("Dag", tp.TestDag)
		t.Run("Dht", tp.TestDht)
		t.Run("Key", tp.TestKey)
		t.Run("Name", tp.TestName)
		t.Run("Object", tp.TestObject)
		t.Run("Path", tp.TestPath)
		t.Run("Pin", tp.TestPin)
		t.Run("PubSub", tp.TestPubSub)
		t.Run("Unixfs", tp.TestUnixfs)
71 72 73 74 75 76

		apis <- -1
		t.Run("TestsCancelCtx", func(t *testing.T) {
			select {
			case <-zeroRunning:
			case <-time.After(time.Second):
77
				t.Errorf("%d test swarms(s) not closed", running)
78 79
			}
		})
80
	}
81
}
82 83 84 85 86 87 88 89 90 91 92 93 94

func (tp *provider) hasApi(t *testing.T, tf func(coreiface.CoreAPI) error) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	api, err := tp.makeAPI(ctx)
	if err != nil {
		t.Fatal(err)
	}

	if err := tf(api); err != nil {
		t.Fatal(api)
	}
}