istio.io/istio@v0.0.0-20240520182934-d79c90f27776/tools/istio-iptables/pkg/config/config_test.go (about) 1 // Copyright Istio Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package config 16 17 import ( 18 "net" 19 "net/netip" 20 "testing" 21 ) 22 23 var tesrLocalIPAddrs = func(ips []netip.Addr) ([]net.Addr, error) { 24 var IPAddrs []net.Addr 25 for i := 0; i < len(ips); i++ { 26 var ipAddr net.Addr 27 ipNetAddr := &net.IPNet{IP: net.ParseIP(ips[i].String())} 28 ipAddr = ipNetAddr 29 IPAddrs = append(IPAddrs, ipAddr) 30 } 31 return IPAddrs, nil 32 } 33 34 func TestGetLocalIP(t *testing.T) { 35 tests := []struct { 36 name string 37 lipas func() ([]net.Addr, error) 38 isDS bool 39 expected bool 40 }{ 41 { 42 name: "ipv4 only local ip addresses", 43 lipas: func() ([]net.Addr, error) { 44 return tesrLocalIPAddrs([]netip.Addr{ 45 netip.MustParseAddr("127.0.0.1"), 46 netip.MustParseAddr("1.2.3.5"), 47 }) 48 }, 49 isDS: false, 50 expected: false, 51 }, 52 { 53 name: "ipv6 only local ip addresses", 54 lipas: func() ([]net.Addr, error) { 55 return tesrLocalIPAddrs([]netip.Addr{ 56 netip.MustParseAddr("::1"), 57 netip.MustParseAddr("2222:3333::1"), 58 }) 59 }, 60 isDS: false, 61 expected: true, 62 }, 63 { 64 name: "mixed ipv4 and ipv6 local ip addresses", 65 lipas: func() ([]net.Addr, error) { 66 return tesrLocalIPAddrs([]netip.Addr{ 67 netip.MustParseAddr("::1"), 68 netip.MustParseAddr("127.0.0.1"), 69 netip.MustParseAddr("1.2.3.5"), 70 netip.MustParseAddr("2222:3333::1"), 71 }) 72 }, 73 isDS: false, 74 expected: false, 75 }, 76 77 { 78 name: "mixed ipv4 and ipv6 local ip addresses with dual stack enable", 79 lipas: func() ([]net.Addr, error) { 80 return tesrLocalIPAddrs([]netip.Addr{ 81 netip.MustParseAddr("::1"), 82 netip.MustParseAddr("127.0.0.1"), 83 netip.MustParseAddr("1.2.3.5"), 84 netip.MustParseAddr("2222:3333::1"), 85 }) 86 }, 87 isDS: true, 88 expected: true, 89 }, 90 } 91 for _, tt := range tests { 92 t.Run(tt.name, func(t *testing.T) { 93 LocalIPAddrs = tt.lipas 94 _, isV6, err := getLocalIP(tt.isDS) 95 if err != nil { 96 t.Errorf("getLocalIP err: %s", err) 97 } 98 if isV6 != tt.expected { 99 t.Errorf("unexpected EnableIPv6 result, expected: %t got: %t", tt.expected, isV6) 100 } 101 }) 102 } 103 }