-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
local_test.go
119 lines (102 loc) · 2.27 KB
/
local_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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package main
import (
"context"
"net"
"testing"
"github.com/miekg/dns"
)
func Question(t *testing.T, domain string, qtype uint16) *dns.Msg {
t.Helper()
t.Logf("%s %s", domain, dns.Type(qtype))
m := new(dns.Msg)
m.SetQuestion(domain, qtype)
return m
}
type TestWriter struct {
response *dns.Msg
}
func (tw *TestWriter) WriteMsg(res *dns.Msg) error {
tw.response = res
return nil
}
func Test_Local_Intercept(t *testing.T) {
pctx, pcancel := context.WithCancel(context.Background())
defer pcancel()
tests := map[string]struct {
records []*Record
request *Request
answer dns.RR
pass bool
}{
"match-direct": {
records: []*Record{{
Pattern: "test.example.tld",
Type: DIRECT,
IP: net.ParseIP("192.168.0.1"),
}},
request: &Request{
ctx: pctx,
cancel: pcancel,
w: &TestWriter{}, // test writer
r: Question(t, "test.example.tld.", dns.TypeA),
},
answer: &dns.A{
Hdr: dns.RR_Header{
Name: "test.example.tld.",
Rrtype: dns.TypeA,
Class: dns.ClassINET,
Ttl: DEFAULTTTL,
},
A: net.ParseIP("192.168.0.1"),
},
},
"nomatch-direct": {
records: []*Record{{
Pattern: "test.example.tld",
Type: DIRECT,
IP: net.ParseIP("192.168.0.1"),
}},
request: &Request{
ctx: pctx,
cancel: pcancel,
w: &TestWriter{}, // test writer
r: Question(t, "mismatch.tld.", dns.TypeA),
},
pass: true,
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
ctx, cancel := context.WithCancel(pctx)
defer cancel()
logger := &NOOPLogger{}
local, err := LocalResolver(ctx, logger, test.records...)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
r, pass := local.Intercept(ctx, test.request)
if pass {
if !test.pass {
t.Fatalf("expected match; got pass")
}
return
}
// Passthrough
if r != nil {
t.Fatalf("expected nil, got %v", r)
}
// Check answer
w, ok := test.request.w.(*TestWriter)
if !ok {
t.Fatalf("expected TestWriter, got %T", test.request.w)
}
if w.response.Answer[0].String() != test.answer.String() {
t.Fatalf(
"expected\n[%s]\ngot\n[%s]",
test.answer.String(),
w.response.Answer[0].String(),
)
}
})
}
}