From cae3999e67026005d5a950b83b2e45fd6a261d39 Mon Sep 17 00:00:00 2001 From: Adin Schmahmann Date: Wed, 2 Dec 2020 04:26:20 -0500 Subject: [PATCH] test: add test for when nodes are connected before the DHT is created --- dht_test.go | 70 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/dht_test.go b/dht_test.go index fc5608011..85dcc22f6 100644 --- a/dht_test.go +++ b/dht_test.go @@ -2023,3 +2023,73 @@ func TestBootStrapWhenRTIsEmpty(t *testing.T) { rt.Find(bootstrappers[2].self) != "" && rt.Find(bootstrapcons[1].self) != "" && rt.Find(bootstrapcons[2].self) != "" }, 5*time.Second, 500*time.Millisecond) } + +func TestPreconnectedNodes(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + // If this test fails it may hang so set a timeout + ctx, cancel = context.WithTimeout(ctx, time.Second*10) + defer cancel() + + opts := []Option{ + testPrefix, + DisableAutoRefresh(), + Mode(ModeServer), + } + + // Create hosts + h1 := bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)) + h2 := bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)) + + // Setup first DHT + d1, err := New(ctx, h1, opts...) + if err != nil { + t.Fatal(err) + } + + // Connect the first host to the second + if err := h1.Connect(ctx, peer.AddrInfo{ID: h2.ID(), Addrs: h2.Addrs()}); err != nil { + t.Fatal(err) + } + + // Wait until we know identify has completed by checking for supported protocols + // TODO: Is this needed? Could we do h2.Connect(h1) and that would wait for identify to complete. + for { + h1Protos, err := h2.Peerstore().SupportsProtocols(h1.ID(), d1.protocolsStrs...) + if err != nil { + t.Fatal(err) + } + + if len(h1Protos) > 0 { + break + } + + select { + case <-time.After(time.Millisecond * 100): + case <-ctx.Done(): + t.Fatal("test hung") + } + } + + // Setup the second DHT + d2, err := New(ctx, h2, opts...) + if err != nil { + t.Fatal(err) + } + + // See if it works + peerCh, err := d2.GetClosestPeers(ctx, "testkey") + if err != nil { + t.Fatal(err) + } + + select { + case p := <-peerCh: + if p == h1.ID() { + break + } + t.Fatal("could not find peer") + case <-ctx.Done(): + t.Fatal("test hung") + } +}