Merge pull request #1175 from macb/testing_getPrivateIP

consul: refactor GetPrivateIP for testability
This commit is contained in:
James Phillips 2015-08-25 15:00:14 -07:00
commit 9b5d7f28ab
3 changed files with 77 additions and 2 deletions

View File

@ -120,9 +120,10 @@ func TestServer_StartStop(t *testing.T) {
config := DefaultConfig()
config.DataDir = dir
private, err := GetPrivateIP()
// Advertise on localhost.
private, _, err := net.ParseCIDR("127.0.0.1/32")
if err != nil {
t.Fatalf("err: %v", err)
t.Fatalf("failed to parse 127.0.0.1 cidr: %v", err)
}
config.RPCAdvertise = &net.TCPAddr{

View File

@ -169,6 +169,10 @@ func GetPrivateIP() (net.IP, error) {
return nil, fmt.Errorf("Failed to get interface addresses: %v", err)
}
return getPrivateIP(addresses)
}
func getPrivateIP(addresses []net.Addr) (net.IP, error) {
var candidates []net.IP
// Find private IPv4 address
@ -200,6 +204,7 @@ func GetPrivateIP() (net.IP, error) {
default:
return nil, fmt.Errorf("Multiple private IPs found. Please configure one.")
}
}
// Converts bytes to an integer

View File

@ -1,6 +1,7 @@
package consul
import (
"errors"
"net"
"regexp"
"testing"
@ -28,6 +29,74 @@ func TestToLowerList(t *testing.T) {
}
}
func TestGetPrivateIP(t *testing.T) {
ip, _, err := net.ParseCIDR("10.1.2.3/32")
if err != nil {
t.Fatalf("failed to parse private cidr: %v", err)
}
pubIP, _, err := net.ParseCIDR("8.8.8.8/32")
if err != nil {
t.Fatalf("failed to parse public cidr: %v", err)
}
tests := []struct {
addrs []net.Addr
expected net.IP
err error
}{
{
addrs: []net.Addr{
&net.IPAddr{
IP: ip,
},
&net.IPAddr{
IP: pubIP,
},
},
expected: ip,
},
{
addrs: []net.Addr{
&net.IPAddr{
IP: pubIP,
},
},
err: errors.New("No private IP address found"),
},
{
addrs: []net.Addr{
&net.IPAddr{
IP: ip,
},
&net.IPAddr{
IP: ip,
},
&net.IPAddr{
IP: pubIP,
},
},
err: errors.New("Multiple private IPs found. Please configure one."),
},
}
for _, test := range tests {
ip, err := getPrivateIP(test.addrs)
switch {
case test.err != nil && err != nil:
if err.Error() != test.err.Error() {
t.Fatalf("unexpected error: %v != %v", test.err, err)
}
case (test.err == nil && err != nil) || (test.err != nil && err == nil):
t.Fatalf("unexpected error: %v != %v", test.err, err)
default:
if !test.expected.Equal(ip) {
t.Fatalf("unexpected ip: %v != %v", ip, test.expected)
}
}
}
}
func TestIsPrivateIP(t *testing.T) {
if !isPrivateIP("192.168.1.1") {
t.Fatalf("bad")