-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathbrowser_test.go
91 lines (83 loc) · 1.91 KB
/
browser_test.go
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package dnssd
import (
"context"
"fmt"
"net"
"os"
"strings"
"testing"
"time"
)
func TestBrowse(t *testing.T) {
testIface, _ := net.InterfaceByName("lo0")
if testIface == nil {
testIface, _ = net.InterfaceByName("lo")
}
if testIface == nil {
t.Fatal("can not find the local interface")
}
localhost, err := os.Hostname()
if err != nil {
t.Fatal(err)
}
localhost = strings.TrimSuffix(strings.Replace(localhost, " ", "-", -1), ".local") // replace spaces with dashes and remove .local suffix
for tName, hostValue := range map[string]string{
"regular host": "My-Computer",
"empty host": "",
"ip address": "192.168.0.1",
} {
t.Run(tName, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cfg := Config{
Name: "My Service",
Type: "_test._tcp",
Host: hostValue,
Port: 12334,
Ifaces: []string{testIface.Name},
}
srv, err := NewService(cfg)
if err != nil {
t.Fatal(err)
}
rs, err := NewResponder()
if err != nil {
t.Fatal(err)
}
go func() {
_ = rs.Respond(ctx)
}()
_, err = rs.Add(srv)
if err != nil {
t.Fatal(err)
}
resultChan := make(chan BrowseEntry)
defer close(resultChan)
go func() {
_ = LookupType(ctx, fmt.Sprintf("%s.local.", cfg.Type), func(entry BrowseEntry) {
resultChan <- entry
}, func(entry BrowseEntry) {})
}()
select {
case <-ctx.Done():
t.Fatal("timeout")
case entry := <-resultChan:
if entry.Name != cfg.Name {
t.Fatalf("is=%v want=%v", entry.Name, cfg.Name)
}
if tName == "empty host" {
if entry.Host != localhost {
t.Fatalf("is=%v want=%v", entry.Host, localhost)
}
} else {
if entry.Host != cfg.Host {
t.Fatalf("is=%v want=%v", entry.Host, cfg.Host)
}
}
if entry.Port != cfg.Port {
t.Fatalf("is=%v want=%v", entry.Port, cfg.Port)
}
}
})
}
}