1package magna
2
3import (
4 "testing"
5)
6
7func TestMessageDecode(t *testing.T) {
8 bytes := []byte{
9 0x8e, 0x19, 0x81, 0x80, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x04, 0x6e, 0x65,
10 0x77, 0x73, 0x0b, 0x79, 0x63, 0x6f, 0x6d, 0x62, 0x69, 0x6e, 0x61, 0x74, 0x6f, 0x72, 0x03,
11 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x01, 0x00, 0x01, 0xc0, 0x0c, 0x00, 0x01, 0x00, 0x01, 0x00,
12 0x00, 0x00, 0x01, 0x00, 0x04, 0xd1, 0xd8, 0xe6, 0xcf,
13 }
14
15 var msg Message
16 msg.Decode(bytes)
17 assert_eq(t, uint16(0x8e19), msg.Header.ID)
18 assert_eq(t, true, msg.Header.QR)
19 assert_eq(t, OPCode(0), msg.Header.OPCode)
20 assert_eq(t, false, msg.Header.AA)
21 assert_eq(t, false, msg.Header.TC)
22 assert_eq(t, true, msg.Header.RD)
23 assert_eq(t, true, msg.Header.RA)
24 assert_eq(t, uint8(0), msg.Header.Z)
25 assert_eq(t, RCode(0), msg.Header.RCode)
26 assert_eq(t, uint16(1), msg.Header.QDCount)
27 assert_eq(t, uint16(1), msg.Header.ANCount)
28 assert_eq(t, uint16(0), msg.Header.NSCount)
29 assert_eq(t, uint16(0), msg.Header.ARCount)
30
31 assert_eq(t, 1, len(msg.Question))
32
33 question := msg.Question[0]
34 assert_eq(t, "news.ycombinator.com", question.QName)
35 assert_eq(t, DNSType(1), question.QType)
36 assert_eq(t, DNSClass(1), question.QClass)
37
38 assert_eq(t, 1, len(msg.Answer))
39 answer := msg.Answer[0]
40 assert_eq(t, answer.Name, "news.ycombinator.com")
41 assert_eq(t, DNSType(1), answer.RType)
42 assert_eq(t, DNSClass(1), answer.RClass)
43 assert_eq(t, uint32(1), answer.TTL)
44 assert_eq(t, uint16(4), answer.RDLength)
45}
46
47func TestMessageEncode(t *testing.T) {
48 bytes := []byte{
49 0x8e, 0x19, 0x81, 0x80, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x04, 0x6e, 0x65,
50 0x77, 0x73, 0x0b, 0x79, 0x63, 0x6f, 0x6d, 0x62, 0x69, 0x6e, 0x61, 0x74, 0x6f, 0x72, 0x03,
51 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x01, 0x00, 0x01, 0xc0, 0x0c, 0x00, 0x01, 0x00, 0x01, 0x00,
52 0x00, 0x00, 0x01, 0x00, 0x04, 0xd1, 0xd8, 0xe6, 0xcf,
53 }
54
55 var msg Message
56 err := msg.Decode(bytes)
57 assert_no_error(t, err)
58
59 actual := msg.Encode()
60 for i := 0; i < len(bytes); i++ {
61 if bytes[i] != actual[i] {
62 t.Fatal(bytes, actual)
63 }
64 }
65}
66
67func FuzzDecodeMessage(f *testing.F) {
68 testcases := [][]byte{
69 {
70 0x8e, 0x19, 0x81, 0x80, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x04, 0x6e, 0x65,
71 0x77, 0x73, 0x0b, 0x79, 0x63, 0x6f, 0x6d, 0x62, 0x69, 0x6e, 0x61, 0x74, 0x6f, 0x72, 0x03,
72 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x01, 0x00, 0x01, 0xc0, 0x0c, 0x00, 0x01, 0x00, 0x01, 0x00,
73 0x00, 0x00, 0x01, 0x00, 0x04, 0xd1, 0xd8, 0xe6, 0xcf,
74 },
75 }
76 for _, tc := range testcases {
77 f.Add(tc) // Use f.Add to provide a seed corpus
78 }
79 f.Fuzz(func(t *testing.T, msg []byte) {
80 var m Message
81 m.Decode(msg)
82 })
83}