notify_test.go 1.91 KB
Newer Older
Steven Allen's avatar
Steven Allen committed
1 2 3 4
package dht

import (
	"context"
5
	"fmt"
Steven Allen's avatar
Steven Allen committed
6
	"testing"
7 8
	"time"

9
	tu "github.com/libp2p/go-libp2p-testing/etc"
Steven Allen's avatar
Steven Allen committed
10 11 12 13 14 15 16 17 18
)

func TestNotifieeMultipleConn(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	d1 := setupDHT(ctx, t, false)
	d2 := setupDHT(ctx, t, false)

19 20 21 22 23 24 25 26
	nn1, err := newSubscriberNotifiee(d1)
	if err != nil {
		t.Fatal(err)
	}
	nn2, err := newSubscriberNotifiee(d2)
	if err != nil {
		t.Fatal(err)
	}
Steven Allen's avatar
Steven Allen committed
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

	connect(t, ctx, d1, d2)
	c12 := d1.host.Network().ConnsToPeer(d2.self)[0]
	c21 := d2.host.Network().ConnsToPeer(d1.self)[0]

	// Pretend to reestablish/re-kill connection
	nn1.Connected(d1.host.Network(), c12)
	nn2.Connected(d2.host.Network(), c21)

	if !checkRoutingTable(d1, d2) {
		t.Fatal("no routes")
	}
	nn1.Disconnected(d1.host.Network(), c12)
	nn2.Disconnected(d2.host.Network(), c21)

	if !checkRoutingTable(d1, d2) {
		t.Fatal("no routes")
	}

	for _, conn := range d1.host.Network().ConnsToPeer(d2.self) {
		conn.Close()
	}
	for _, conn := range d2.host.Network().ConnsToPeer(d1.self) {
		conn.Close()
	}

53 54 55 56 57 58
	tu.WaitFor(ctx, func() error {
		if checkRoutingTable(d1, d2) {
			return fmt.Errorf("should not have routes")
		}
		return nil
	})
Steven Allen's avatar
Steven Allen committed
59 60 61
}

func TestNotifieeFuzz(t *testing.T) {
62
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
Steven Allen's avatar
Steven Allen committed
63 64 65 66 67
	defer cancel()

	d1 := setupDHT(ctx, t, false)
	d2 := setupDHT(ctx, t, false)

Matt Joiner's avatar
Matt Joiner committed
68
	for i := 0; i < 10; i++ {
Steven Allen's avatar
Steven Allen committed
69 70 71 72 73
		connectNoSync(t, ctx, d1, d2)
		for _, conn := range d1.host.Network().ConnsToPeer(d2.self) {
			conn.Close()
		}
	}
74 75 76 77 78 79
	tu.WaitFor(ctx, func() error {
		if checkRoutingTable(d1, d2) {
			return fmt.Errorf("should not have routes")
		}
		return nil
	})
Steven Allen's avatar
Steven Allen committed
80 81 82 83 84 85 86 87
	connect(t, ctx, d1, d2)
}

func checkRoutingTable(a, b *IpfsDHT) bool {
	// loop until connection notification has been received.
	// under high load, this may not happen as immediately as we would like.
	return a.routingTable.Find(b.self) != "" && b.routingTable.Find(a.self) != ""
}