forked from matrix-org/gomatrixserverlib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdnscache_test.go
103 lines (88 loc) · 2.46 KB
/
dnscache_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
92
93
94
95
96
97
98
99
100
101
102
103
package gomatrixserverlib
import (
"context"
"net"
"testing"
"time"
)
var dnsResolverHits chan string
func init() {
dnsResolverHits = make(chan string, 1)
}
type dummyNetResolver struct{}
func (r *dummyNetResolver) LookupIPAddr(_ context.Context, hostname string) ([]net.IPAddr, error) {
dnsResolverHits <- hostname
return []net.IPAddr{
{
IP: net.IP("1.2.3.4"),
},
}, nil
}
func mustCreateCache(size int, lifetime time.Duration) *DNSCache {
cache := NewDNSCache(size, lifetime)
cache.resolver = &dummyNetResolver{}
return cache
}
func TestDNSCache(t *testing.T) {
cache := mustCreateCache(1, time.Second)
ctx := context.Background()
// STEP 1: First we'll start with first.com.
// first.com shouldn't be in the cache at this point.
if _, ok := cache.lookup(ctx, "first.com"); ok {
t.Fatalf("shouldn't be in the cache")
}
select {
case hostname := <-dnsResolverHits:
if hostname != "first.com" {
t.Fatalf("expected resolve for first.com, got %q", hostname)
}
default:
t.Fatalf("should have hit the resolver")
}
// first.com should be in the cache this time.
if _, ok := cache.lookup(ctx, "first.com"); !ok {
t.Fatalf("should be in the cache")
}
select {
case hostname := <-dnsResolverHits:
t.Fatalf("shouldn't have hit the resolver but got a resolve for %q", hostname)
default:
}
// STEP 2: Then we'll try second.net. Since the cache is only
// one entry big, this should evict first.com.
// second.net shouldn't be in the cache at this point.
if _, ok := cache.lookup(ctx, "second.net"); ok {
t.Fatalf("shouldn't be in the cache")
}
select {
case hostname := <-dnsResolverHits:
if hostname != "second.net" {
t.Fatalf("expected resolve for second.net, got %q", hostname)
}
default:
t.Fatalf("should have hit the resolver")
}
// second.net should be in the cache this time.
if _, ok := cache.lookup(ctx, "second.net"); !ok {
t.Fatalf("should be in the cache")
}
select {
case hostname := <-dnsResolverHits:
t.Fatalf("shouldn't have hit the resolver but got a resolve for %q", hostname)
default:
}
// STEP 3: Now we'll retry first.com, which should have been
// evicted.
// first.com shouldn't be in the cache at this point.
if _, ok := cache.lookup(ctx, "first.com"); ok {
t.Fatalf("shouldn't be in the cache")
}
select {
case hostname := <-dnsResolverHits:
if hostname != "first.com" {
t.Fatalf("expected resolve for first.com, got %q", hostname)
}
default:
t.Fatalf("should have hit the resolver")
}
}