github.com/volts-dev/volts@v0.0.0-20240120094013-5e9c65924106/internal/addr/addr_test.go (about) 1 package addr 2 3 import ( 4 "net" 5 "testing" 6 ) 7 8 func TestIsLocal(t *testing.T) { 9 testData := []struct { 10 addr string 11 expect bool 12 }{ 13 {"localhost", true}, 14 {"localhost:8080", true}, 15 {"127.0.0.1", true}, 16 {"127.0.0.1:1001", true}, 17 {"80.1.1.1", false}, 18 } 19 20 for _, d := range testData { 21 res := IsLocal(d.addr) 22 if res != d.expect { 23 t.Fatalf("expected %t got %t", d.expect, res) 24 } 25 } 26 } 27 28 func TestExtractor(t *testing.T) { 29 testData := []struct { 30 addr string 31 expect string 32 parse bool 33 }{ 34 {"127.0.0.1", "127.0.0.1", false}, 35 {"10.0.0.1", "10.0.0.1", false}, 36 {"", "", true}, 37 {"0.0.0.0", "", true}, 38 {"[::]", "", true}, 39 } 40 41 for _, d := range testData { 42 addr, err := Extract(d.addr) 43 if err != nil { 44 t.Errorf("Unexpected error %v", err) 45 } 46 47 if d.parse { 48 ip := net.ParseIP(addr) 49 if ip == nil { 50 t.Error("Unexpected nil IP") 51 } 52 53 } else if addr != d.expect { 54 t.Errorf("Expected %s got %s", d.expect, addr) 55 } 56 } 57 58 } 59 60 func TestAppendPrivateBlocks(t *testing.T) { 61 tests := []struct { 62 addr string 63 expect bool 64 }{ 65 {addr: "9.134.71.34", expect: true}, 66 {addr: "8.10.110.34", expect: false}, // not in private blocks 67 } 68 69 AppendPrivateBlocks("9.134.0.0/16") 70 71 for _, test := range tests { 72 t.Run(test.addr, func(t *testing.T) { 73 res := isPrivateIP(test.addr) 74 if res != test.expect { 75 t.Fatalf("expected %t got %t", test.expect, res) 76 } 77 }) 78 } 79 }