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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
|
package forward
import (
"testing"
"time"
"github.com/coredns/coredns/plugin/pkg/dnstest"
"github.com/miekg/dns"
)
func TestCached(t *testing.T) {
s := dnstest.NewServer(func(w dns.ResponseWriter, r *dns.Msg) {
ret := new(dns.Msg)
ret.SetReply(r)
w.WriteMsg(ret)
})
defer s.Close()
tr := newTransport(s.Addr)
tr.Start()
defer tr.Stop()
c1, cache1, _ := tr.Dial("udp")
c2, cache2, _ := tr.Dial("udp")
if cache1 || cache2 {
t.Errorf("Expected non-cached connection")
}
tr.Yield(c1)
tr.Yield(c2)
c3, cached3, _ := tr.Dial("udp")
if !cached3 {
t.Error("Expected cached connection (c3)")
}
if c2 != c3 {
t.Error("Expected c2 == c3")
}
tr.Yield(c3)
// dial another protocol
c4, cached4, _ := tr.Dial("tcp")
if cached4 {
t.Errorf("Expected non-cached connection (c4)")
}
tr.Yield(c4)
}
func TestCleanupByTimer(t *testing.T) {
s := dnstest.NewServer(func(w dns.ResponseWriter, r *dns.Msg) {
ret := new(dns.Msg)
ret.SetReply(r)
w.WriteMsg(ret)
})
defer s.Close()
tr := newTransport(s.Addr)
tr.SetExpire(100 * time.Millisecond)
tr.Start()
defer tr.Stop()
c1, _, _ := tr.Dial("udp")
c2, _, _ := tr.Dial("udp")
tr.Yield(c1)
time.Sleep(10 * time.Millisecond)
tr.Yield(c2)
time.Sleep(120 * time.Millisecond)
c3, cached, _ := tr.Dial("udp")
if cached {
t.Error("Expected non-cached connection (c3)")
}
tr.Yield(c3)
time.Sleep(120 * time.Millisecond)
c4, cached, _ := tr.Dial("udp")
if cached {
t.Error("Expected non-cached connection (c4)")
}
tr.Yield(c4)
}
func TestCleanupAll(t *testing.T) {
s := dnstest.NewServer(func(w dns.ResponseWriter, r *dns.Msg) {
ret := new(dns.Msg)
ret.SetReply(r)
w.WriteMsg(ret)
})
defer s.Close()
tr := newTransport(s.Addr)
c1, _ := dns.DialTimeout("udp", tr.addr, maxDialTimeout)
c2, _ := dns.DialTimeout("udp", tr.addr, maxDialTimeout)
c3, _ := dns.DialTimeout("udp", tr.addr, maxDialTimeout)
tr.conns[typeUDP] = []*persistConn{{c1, time.Now()}, {c2, time.Now()}, {c3, time.Now()}}
if len(tr.conns[typeUDP]) != 3 {
t.Error("Expected 3 connections")
}
tr.cleanup(true)
if len(tr.conns[typeUDP]) > 0 {
t.Error("Expected no cached connections")
}
}
|