| 1 |
package dnstest |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"io" |
| 6 |
"testing" |
| 7 |
|
| 8 |
"codeberg.org/miekg/dns" |
| 9 |
) |
| 10 |
|
| 11 |
func TestRecorder(t *testing.T) { |
| 12 |
m := new(dns.Msg) |
| 13 |
m.Question = []dns.RR{&dns.TXT{Hdr: dns.Header{Name: "miek.nl.", Class: dns.ClassINET}}} |
| 14 |
|
| 15 |
rec := NewRecorder(nil) |
| 16 |
io.Copy(rec, m) |
| 17 |
rec.Msg.Unpack() |
| 18 |
if x := rec.Msg.Question[0].Header().Name; x != "miek.nl." { |
| 19 |
t.Errorf("expected %s, got %s", "miek.nl.", x) |
| 20 |
} |
| 21 |
} |
| 22 |
|
| 23 |
func TestMultiRecorder(t *testing.T) { |
| 24 |
m := new(dns.Msg) |
| 25 |
m.Question = []dns.RR{&dns.TXT{Hdr: dns.Header{Name: "miek.nl.", Class: dns.ClassINET}}} |
| 26 |
|
| 27 |
rec := NewMultiRecorder(nil) |
| 28 |
io.Copy(rec, m) |
| 29 |
io.Copy(rec, m) |
| 30 |
if len(rec.Msgs) != 2 { |
| 31 |
t.Errorf("expeced 2 messages, got %d", len(rec.Msgs)) |
| 32 |
} |
| 33 |
rec.Msg.Unpack() |
| 34 |
if x := rec.Msg.Question[0].Header().Name; x != "miek.nl." { |
| 35 |
t.Errorf("expected %s, got %s", "miek.nl.", x) |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
// ExampleRecorder shows how to use a [Recorder] to wrap a [dns.ResponseWriter]. |
| 40 |
func ExampleRecorder() { |
| 41 |
// Fake being a dns.HandlerFunc. |
| 42 |
var ( |
| 43 |
w dns.ResponseWriter |
| 44 |
r *dns.Msg |
| 45 |
next dns.HandlerFunc |
| 46 |
ctx context.Context |
| 47 |
) |
| 48 |
|
| 49 |
rw := NewRecorder(w) |
| 50 |
next.ServeDNS(ctx, rw, r) |
| 51 |
|
| 52 |
// If hijacked we don't get anything back. |
| 53 |
if rw.Msg == nil { |
| 54 |
return |
| 55 |
} |
| 56 |
|
| 57 |
// do/obverse things with rw.Msg... |
| 58 |
|
| 59 |
// Return message to the original writer. |
| 60 |
io.Copy(w, rw.Msg) |
| 61 |
} |