github.com/zhuohuang-hust/src-cbuild@v0.0.0-20230105071821-c7aab3e7c840/opts/ip_test.go (about)

     1  package opts
     2  
     3  import (
     4  	"net"
     5  	"testing"
     6  )
     7  
     8  func TestIpOptString(t *testing.T) {
     9  	addresses := []string{"", "0.0.0.0"}
    10  	var ip net.IP
    11  
    12  	for _, address := range addresses {
    13  		stringAddress := NewIPOpt(&ip, address).String()
    14  		if stringAddress != address {
    15  			t.Fatalf("IpOpt string should be `%s`, not `%s`", address, stringAddress)
    16  		}
    17  	}
    18  }
    19  
    20  func TestNewIpOptInvalidDefaultVal(t *testing.T) {
    21  	ip := net.IPv4(127, 0, 0, 1)
    22  	defaultVal := "Not an ip"
    23  
    24  	ipOpt := NewIPOpt(&ip, defaultVal)
    25  
    26  	expected := "127.0.0.1"
    27  	if ipOpt.String() != expected {
    28  		t.Fatalf("Expected [%v], got [%v]", expected, ipOpt.String())
    29  	}
    30  }
    31  
    32  func TestNewIpOptValidDefaultVal(t *testing.T) {
    33  	ip := net.IPv4(127, 0, 0, 1)
    34  	defaultVal := "192.168.1.1"
    35  
    36  	ipOpt := NewIPOpt(&ip, defaultVal)
    37  
    38  	expected := "192.168.1.1"
    39  	if ipOpt.String() != expected {
    40  		t.Fatalf("Expected [%v], got [%v]", expected, ipOpt.String())
    41  	}
    42  }
    43  
    44  func TestIpOptSetInvalidVal(t *testing.T) {
    45  	ip := net.IPv4(127, 0, 0, 1)
    46  	ipOpt := &IPOpt{IP: &ip}
    47  
    48  	invalidIP := "invalid ip"
    49  	expectedError := "invalid ip is not an ip address"
    50  	err := ipOpt.Set(invalidIP)
    51  	if err == nil || err.Error() != expectedError {
    52  		t.Fatalf("Expected an Error with [%v], got [%v]", expectedError, err.Error())
    53  	}
    54  }