libp2p_test.go 1.91 KB
Newer Older
1
2
3
4
5
package libp2p

import (
	"context"
	"fmt"
6
	"regexp"
Steven Allen's avatar
Steven Allen committed
7
	"strings"
8
9
10
11
	"testing"

	crypto "github.com/libp2p/go-libp2p-crypto"
	host "github.com/libp2p/go-libp2p-host"
12
	"github.com/libp2p/go-tcp-transport"
13
14
15
)

func TestNewHost(t *testing.T) {
Steven Allen's avatar
Steven Allen committed
16
	h, err := makeRandomHost(t, 9000)
17
18
19
	if err != nil {
		t.Fatal(err)
	}
Steven Allen's avatar
Steven Allen committed
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
	h.Close()
}

func TestBadTransportConstructor(t *testing.T) {
	ctx := context.Background()
	h, err := New(ctx, Transport(func() {}))
	if err == nil {
		h.Close()
		t.Fatal("expected an error")
	}
	if !strings.Contains(err.Error(), "libp2p_test.go") {
		t.Error("expected error to contain debugging info")
	}
}

func TestInsecure(t *testing.T) {
	ctx := context.Background()
	h, err := New(ctx, NoSecurity)
	if err != nil {
		t.Fatal(err)
	}
	h.Close()
42
43
}

44
45
46
func TestDefaultListenAddrs(t *testing.T) {
	ctx := context.Background()

Abhishek Upperwal's avatar
Abhishek Upperwal committed
47
	re := regexp.MustCompile("/(ip)[4|6]/((0.0.0.0)|(::))/tcp/")
48

49
50
51
52
53
	// Test 1: Setting the correct listen addresses if userDefined.Transport == nil && userDefined.ListenAddrs == nil
	h, err := New(ctx)
	if err != nil {
		t.Fatal(err)
	}
54
55
56
57
	for _, addr := range h.Network().ListenAddresses() {
		if re.FindStringSubmatchIndex(addr.String()) == nil {
			t.Error("expected ip4 or ip6 interface")
		}
58
	}
59

60
61
62
63
	h.Close()

	// Test 2: Listen addr should not set if user defined transport is passed.
	h, err = New(
64
		ctx,
Abhishek Upperwal's avatar
Abhishek Upperwal committed
65
		Transport(tcp.NewTCPTransport),
66
67
68
69
70
	)
	if err != nil {
		t.Fatal(err)
	}

71
	if len(h.Network().ListenAddresses()) != 0 {
72
73
74
75
76
		t.Error("expected zero listen addrs as none is set with user defined transport")
	}
	h.Close()
}

77
78
79
80
81
82
83
84
85
86
func makeRandomHost(t *testing.T, port int) (host.Host, error) {
	ctx := context.Background()
	priv, _, err := crypto.GenerateKeyPair(crypto.RSA, 2048)
	if err != nil {
		t.Fatal(err)
	}

	opts := []Option{
		ListenAddrStrings(fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", port)),
		Identity(priv),
Steven Allen's avatar
Steven Allen committed
87
88
89
		DefaultTransports,
		DefaultMuxers,
		DefaultSecurity,
90
91
92
93
94
		NATPortMap(),
	}

	return New(ctx, opts...)
}