mux_test.go 1.29 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1
package protocol
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
2
3
4
5
6

import (
	"bytes"
	"testing"

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
7
	inet "github.com/ipfs/go-libp2p/p2p/net"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
8
9
10
11
12
13
14
15
16
17
18
)

var testCases = map[string]string{
	"/bitswap": "\u0009/bitswap\n",
	"/dht":     "\u0005/dht\n",
	"/ipfs":    "\u0006/ipfs\n",
	"/ipfs/dksnafkasnfkdajfkdajfdsjadosiaaodj": ")/ipfs/dksnafkasnfkdajfkdajfdsjadosiaaodj\n",
}

func TestWrite(t *testing.T) {
	for k, v := range testCases {
19
20
		buf := new(bytes.Buffer)
		if err := WriteHeader(buf, ID(k)); err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
			t.Fatal(err)
		}

		v2 := buf.Bytes()
		if !bytes.Equal(v2, []byte(v)) {
			t.Errorf("failed: %s - %v != %v", k, []byte(v), v2)
		}
	}
}

func TestHandler(t *testing.T) {

	outs := make(chan string, 10)

	h := func(n string) func(s inet.Stream) {
		return func(s inet.Stream) {
			outs <- n
		}
	}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
41
	m := NewMux()
42
	m.SetDefaultHandler(h("default"))
Brian Tiger Chow's avatar
Brian Tiger Chow committed
43
	m.SetHandler("/dht", h("bitswap"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
44
	// m.Handlers["/ipfs"] = h("bitswap") // default!
Brian Tiger Chow's avatar
Brian Tiger Chow committed
45
46
	m.SetHandler("/bitswap", h("bitswap"))
	m.SetHandler("/ipfs/dksnafkasnfkdajfkdajfdsjadosiaaodj", h("bitswap"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
47
48

	for k, v := range testCases {
49
		buf := new(bytes.Buffer)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
50
51
52
53
54
		if _, err := buf.Write([]byte(v)); err != nil {
			t.Error(err)
			continue
		}

55
		name, err := ReadHeader(buf)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
56
57
58
59
60
		if err != nil {
			t.Error(err)
			continue
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
61
		if name != ID(k) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
62
63
64
65
66
67
			t.Errorf("name mismatch: %s != %s", k, name)
			continue
		}
	}

}