git » dnss » commit 678d6ab

dnsserver: Add unit tests for wantToCache

author Alberto Bertogli
2023-02-26 20:22:11 UTC
committer Alberto Bertogli
2023-02-26 20:22:11 UTC
parent 15a8c58fa76ac7470da11a24fc915ff616b5cc70

dnsserver: Add unit tests for wantToCache

internal/dnsserver/caching_test.go +53 -0

diff --git a/internal/dnsserver/caching_test.go b/internal/dnsserver/caching_test.go
index 8e948df..a759f04 100644
--- a/internal/dnsserver/caching_test.go
+++ b/internal/dnsserver/caching_test.go
@@ -6,6 +6,7 @@ import (
 	"fmt"
 	"reflect"
 	"strconv"
+	"strings"
 	"testing"
 	"time"
 
@@ -130,6 +131,50 @@ func TestFailedQueries(t *testing.T) {
 	}
 }
 
+func TestWantToCache(t *testing.T) {
+	query := newQuery("test.", dns.TypeA)
+	q := query.Question[0]
+	reply := newReply(mustNewRR(t, "test. A 1.2.3.4"))
+	reply.Question = []dns.Question{q}
+
+	if err := wantToCache(q, reply); err != nil {
+		t.Errorf("wantToCache failed on cacheable request: %v", err)
+	}
+
+	r := reply.Copy()
+	r.Rcode = dns.RcodeBadName
+	checkWantToCache(t, q, r, "unsuccessful query")
+
+	r = reply.Copy()
+	r.Response = false
+	checkWantToCache(t, q, r, "response = false")
+
+	r = reply.Copy()
+	r.Opcode = dns.OpcodeUpdate
+	checkWantToCache(t, q, r, "opcode")
+
+	r = reply.Copy()
+	r.Answer = []dns.RR{}
+	checkWantToCache(t, q, r, "answer is empty")
+
+	r = reply.Copy()
+	r.Truncated = true
+	checkWantToCache(t, q, r, "truncated reply")
+
+	r = reply.Copy()
+	r.Question = []dns.Question{q, q}
+	checkWantToCache(t, q, r, "too many/few questions (2)")
+
+	r = reply.Copy()
+	r.Question = []dns.Question{}
+	checkWantToCache(t, q, r, "too many/few questions (0)")
+
+	r = reply.Copy()
+	r.Question = []dns.Question{
+		dns.Question{"other.", dns.TypeMX, dns.ClassINET}}
+	checkWantToCache(t, q, r, "reply question does not match")
+}
+
 // Test that we handle the cache filling up.
 // Note this test is tied to the current behaviour of not doing any eviction
 // when we're full, which is not ideal and will likely be changed in the
@@ -297,6 +342,14 @@ func queryFail(t *testing.T, c *cachingResolver) *dns.Msg {
 	return resp
 }
 
+func checkWantToCache(t *testing.T, q dns.Question, r *dns.Msg, exp string) {
+	t.Helper()
+	err := wantToCache(q, r)
+	if !strings.Contains(err.Error(), exp) {
+		t.Errorf("q:%v r:%v expected:%q got:%v", q, r, exp, err)
+	}
+}
+
 func mustNewRR(tb testing.TB, s string) dns.RR {
 	rr, err := dns.NewRR(s)
 	if err != nil {