mux_test.go 1.38 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package mux

import (
	"bytes"
	"testing"

	inet "github.com/jbenet/go-ipfs/p2p/net"
	protocol "github.com/jbenet/go-ipfs/p2p/protocol"
)

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 {
		var buf bytes.Buffer
		if err := protocol.WriteHeader(&buf, protocol.ID(k)); err != nil {
			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
		}
	}

	m := Mux{Handlers: StreamHandlerMap{}}
	m.Default = h("default")
	m.Handlers["/dht"] = h("bitswap")
	// m.Handlers["/ipfs"] = h("bitswap") // default!
	m.Handlers["/bitswap"] = h("bitswap")
	m.Handlers["/ipfs/dksnafkasnfkdajfkdajfdsjadosiaaodj"] = h("bitswap")

	for k, v := range testCases {
		var buf bytes.Buffer
		if _, err := buf.Write([]byte(v)); err != nil {
			t.Error(err)
			continue
		}

		name, err := protocol.ReadHeader(&buf)
		if err != nil {
			t.Error(err)
			continue
		}

		if name != protocol.ID(k) {
			t.Errorf("name mismatch: %s != %s", k, name)
			continue
		}
	}

}