aboutsummaryrefslogtreecommitdiff
path: root/plugin/erratic/erratic_test.go
blob: 8a3b4e011d910c2d4120cf4c12fd3d949edf0849 (plain) (blame)
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
package erratic

import (
	"context"
	"testing"

	"github.com/coredns/coredns/plugin/pkg/dnstest"
	"github.com/coredns/coredns/plugin/test"

	"github.com/miekg/dns"
)

func TestErraticDrop(t *testing.T) {
	e := &Erratic{drop: 2} // 50% drops

	tests := []struct {
		expectedCode int
		expectedErr  error
		drop         bool
	}{
		{expectedCode: dns.RcodeSuccess, expectedErr: nil, drop: true},
		{expectedCode: dns.RcodeSuccess, expectedErr: nil, drop: false},
	}

	ctx := context.TODO()

	for i, tc := range tests {
		req := new(dns.Msg)
		req.SetQuestion("example.org.", dns.TypeA)

		rec := dnstest.NewRecorder(&test.ResponseWriter{})
		code, err := e.ServeDNS(ctx, rec, req)

		if err != tc.expectedErr {
			t.Errorf("Test %d: Expected error %q, but got %q", i, tc.expectedErr, err)
		}
		if code != int(tc.expectedCode) {
			t.Errorf("Test %d: Expected status code %d, but got %d", i, tc.expectedCode, code)
		}

		if tc.drop && rec.Msg != nil {
			t.Errorf("Test %d: Expected dropped message, but got %q", i, rec.Msg.Question[0].Name)
		}
	}
}

func TestErraticTruncate(t *testing.T) {
	e := &Erratic{truncate: 2} // 50% drops

	tests := []struct {
		expectedCode int
		expectedErr  error
		truncate     bool
	}{
		{expectedCode: dns.RcodeSuccess, expectedErr: nil, truncate: true},
		{expectedCode: dns.RcodeSuccess, expectedErr: nil, truncate: false},
	}

	ctx := context.TODO()

	for i, tc := range tests {
		req := new(dns.Msg)
		req.SetQuestion("example.org.", dns.TypeA)

		rec := dnstest.NewRecorder(&test.ResponseWriter{})
		code, err := e.ServeDNS(ctx, rec, req)

		if err != tc.expectedErr {
			t.Errorf("Test %d: Expected error %q, but got %q", i, tc.expectedErr, err)
		}
		if code != int(tc.expectedCode) {
			t.Errorf("Test %d: Expected status code %d, but got %d", i, tc.expectedCode, code)
		}

		if tc.truncate && !rec.Msg.Truncated {
			t.Errorf("Test %d: Expected truncated message, but got %q", i, rec.Msg.Question[0].Name)
		}
	}
}