This repository has been archived by the owner on Mar 31, 2022. It is now read-only.
forked from rs/dnscache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dnscache_test.go
83 lines (79 loc) · 1.86 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
package dnscache
import (
"context"
"fmt"
"net"
"net/http"
"strings"
"testing"
)
func TestResolver_LookupHost(t *testing.T) {
r := &Resolver{}
var cacheMiss bool
r.onCacheMiss = func() {
cacheMiss = true
}
hosts := []string{"google.com", "google.com.", "netflix.com"}
for _, host := range hosts {
t.Run(host, func(t *testing.T) {
for _, wantMiss := range []bool{true, false, false} {
cacheMiss = false
addrs, err := r.LookupHost(context.Background(), host)
if err != nil {
t.Fatal(err)
}
if len(addrs) == 0 {
t.Error("got no record")
}
for _, addr := range addrs {
if net.ParseIP(addr) == nil {
t.Errorf("got %q; want a literal IP address", addr)
}
}
if wantMiss != cacheMiss {
t.Errorf("got cache miss=%v, want %v", cacheMiss, wantMiss)
}
}
})
}
}
func TestClearCache(t *testing.T) {
r := &Resolver{}
_, _ = r.LookupHost(context.Background(), "google.com")
if e := r.cache["hgoogle.com"]; e != nil && !e.used {
t.Error("cache entry used flag is false, want true")
}
r.Refresh(true)
if e := r.cache["hgoogle.com"]; e != nil && e.used {
t.Error("cache entry used flag is true, want false")
}
r.Refresh(true)
if e := r.cache["hgoogle.com"]; e != nil {
t.Error("cache entry is not cleared")
}
}
func Example() {
r := &Resolver{}
t := &http.Transport{
DialContext: func(ctx context.Context, network string, addr string) (conn net.Conn, err error) {
separator := strings.LastIndex(addr, ":")
ips, err := r.LookupHost(ctx, addr[:separator])
if err != nil {
return nil, err
}
for _, ip := range ips {
conn, err = net.Dial(network, ip+addr[separator:])
if err == nil {
break
}
}
return
},
}
c := &http.Client{Transport: t}
res, err := c.Get("http://httpbin.org/status/418")
if err == nil {
fmt.Println(res.StatusCode)
}
// Output: 418
}