From 85b6c83294b7720eb6213eee2e0085212712dd57 Mon Sep 17 00:00:00 2001 From: Harshitha U R Date: Mon, 23 Jan 2023 15:50:25 +0530 Subject: [PATCH] Adds unit test for fqdn.go Signed-off-by: Harshitha U R --- .../controller/networkpolicy/fqdn_test.go | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/pkg/agent/controller/networkpolicy/fqdn_test.go b/pkg/agent/controller/networkpolicy/fqdn_test.go index 2989556c5b4..e2d293ddd24 100644 --- a/pkg/agent/controller/networkpolicy/fqdn_test.go +++ b/pkg/agent/controller/networkpolicy/fqdn_test.go @@ -16,6 +16,7 @@ package networkpolicy import ( "context" + "net" "testing" "time" @@ -305,3 +306,85 @@ func TestLookupIPFallback(t *testing.T) { err := f.lookupIP(ctx, "www.google.com") require.NoError(t, err, "Error when resolving name") } + +func TestString(t *testing.T) { + tests := []struct { + name string + selectorItem *fqdnSelectorItem + matchName string + matchRegex string + expectedOutput string + }{ + { + name: "matching the regex", + selectorItem: &fqdnSelectorItem{ + matchRegex: "^.*antrea[.]io$", + }, + expectedOutput: "matchRegex:^.*antrea[.]io$", + }, + { + name: "matching the name", + selectorItem: &fqdnSelectorItem{ + matchName: "test.antrea.io", + }, + expectedOutput: "matchName:test.antrea.io", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + gotOutput := tc.selectorItem.String() + assert.Equal(t, tc.expectedOutput, gotOutput) + }) + } +} + +func TestGetIPsForFQDNSelectors(t *testing.T) { + selectorItem := fqdnSelectorItem{ + matchName: "test.antrea.io", + } + tests := []struct { + name string + fqdns []string + existingSelectorItemToFQDN map[fqdnSelectorItem]sets.String + existingDNSCache map[string]dnsMeta + expectedMatchedIPs []net.IP + }{ + { + name: "matched ip found", + fqdns: []string{"test.antrea.io"}, + existingSelectorItemToFQDN: map[fqdnSelectorItem]sets.String{ + selectorItem: sets.NewString("test.antrea.io"), + }, + existingDNSCache: map[string]dnsMeta{ + "test.antrea.io": { + responseIPs: map[string]net.IP{ + "IP": net.ParseIP("127.0.0.1"), + }, + }, + }, + expectedMatchedIPs: []net.IP{net.ParseIP("127.0.0.1")}, + }, + { + name: "no matched ip", + fqdns: []string{"^.*antrea[.]io$"}, + expectedMatchedIPs: nil, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + controller := gomock.NewController(t) + defer controller.Finish() + f, _ := newMockFQDNController(t, controller, nil) + if tc.existingSelectorItemToFQDN != nil { + f.selectorItemToFQDN = tc.existingSelectorItemToFQDN + } + if tc.existingDNSCache != nil { + f.dnsEntryCache = tc.existingDNSCache + } + gotOutput := f.getIPsForFQDNSelectors(tc.fqdns) + assert.Equal(t, tc.expectedMatchedIPs, gotOutput) + }) + } +}