github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/util/addr/addr_test.go (about) 1 // Licensed under the Apache License, Version 2.0 (the "License"); 2 // you may not use this file except in compliance with the License. 3 // You may obtain a copy of the License at 4 // 5 // https://www.apache.org/licenses/LICENSE-2.0 6 // 7 // Unless required by applicable law or agreed to in writing, software 8 // distributed under the License is distributed on an "AS IS" BASIS, 9 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 // See the License for the specific language governing permissions and 11 // limitations under the License. 12 // 13 // Original source: github.com/micro/go-micro/v3/util/addr/addr_test.go 14 15 package addr 16 17 import ( 18 "net" 19 "testing" 20 ) 21 22 func TestIsLocal(t *testing.T) { 23 testData := []struct { 24 addr string 25 expect bool 26 }{ 27 {"localhost", true}, 28 {"localhost:8080", true}, 29 {"127.0.0.1", true}, 30 {"127.0.0.1:1001", true}, 31 {"80.1.1.1", false}, 32 } 33 34 for _, d := range testData { 35 res := IsLocal(d.addr) 36 if res != d.expect { 37 t.Fatalf("expected %t got %t", d.expect, res) 38 } 39 } 40 } 41 42 func TestExtractor(t *testing.T) { 43 testData := []struct { 44 addr string 45 expect string 46 parse bool 47 }{ 48 {"127.0.0.1", "127.0.0.1", false}, 49 {"10.0.0.1", "10.0.0.1", false}, 50 {"", "", true}, 51 {"0.0.0.0", "", true}, 52 {"[::]", "", true}, 53 } 54 55 for _, d := range testData { 56 addr, err := Extract(d.addr) 57 if err != nil { 58 t.Errorf("Unexpected error %v", err) 59 } 60 61 if d.parse { 62 ip := net.ParseIP(addr) 63 if ip == nil { 64 t.Error("Unexpected nil IP") 65 } 66 67 } else if addr != d.expect { 68 t.Errorf("Expected %s got %s", d.expect, addr) 69 } 70 } 71 72 } 73 74 func TestAppendPrivateBlocks(t *testing.T) { 75 tests := []struct { 76 addr string 77 expect bool 78 }{ 79 {addr: "9.134.71.34", expect: true}, 80 {addr: "8.10.110.34", expect: false}, // not in private blocks 81 } 82 83 AppendPrivateBlocks("9.134.0.0/16") 84 85 for _, test := range tests { 86 t.Run(test.addr, func(t *testing.T) { 87 res := isPrivateIP(test.addr) 88 if res != test.expect { 89 t.Fatalf("expected %t got %t", test.expect, res) 90 } 91 }) 92 } 93 }