github.com/openshift/installer@v1.4.17/pkg/ipnet/ipnet_test.go (about)

     1  package ipnet
     2  
     3  import (
     4  	"encoding/json"
     5  	"net"
     6  	"testing"
     7  )
     8  
     9  func assertJSON(t *testing.T, data interface{}, expected string) {
    10  	actualBytes, err := json.Marshal(data)
    11  	if err != nil {
    12  		t.Fatal(err)
    13  	}
    14  	actual := string(actualBytes)
    15  
    16  	if actual != expected {
    17  		t.Fatalf("%s != %s", actual, expected)
    18  	}
    19  }
    20  
    21  func TestMarshal(t *testing.T) {
    22  	stdlibIPNet := &net.IPNet{
    23  		IP:   net.IP{192, 168, 0, 10},
    24  		Mask: net.IPv4Mask(255, 255, 255, 0),
    25  	}
    26  	assertJSON(t, stdlibIPNet, "{\"IP\":\"192.168.0.10\",\"Mask\":\"////AA==\"}")
    27  	wrappedIPNet := &IPNet{IPNet: *stdlibIPNet}
    28  	assertJSON(t, wrappedIPNet, "\"192.168.0.10/24\"")
    29  	assertJSON(t, &IPNet{}, "null")
    30  	assertJSON(t, nil, "null")
    31  }
    32  
    33  func TestUnmarshal(t *testing.T) {
    34  	for _, ipNetIn := range []*IPNet{
    35  		nil,
    36  		{IPNet: net.IPNet{
    37  			IP:   net.IP{192, 168, 0, 10},
    38  			Mask: net.IPv4Mask(255, 255, 255, 0),
    39  		}},
    40  	} {
    41  		t.Run(ipNetIn.String(), func(t *testing.T) {
    42  			data, err := json.Marshal(ipNetIn)
    43  			if err != nil {
    44  				t.Fatal(err)
    45  			}
    46  
    47  			var ipNetOut *IPNet
    48  			err = json.Unmarshal(data, &ipNetOut)
    49  			if err != nil {
    50  				t.Fatal(err)
    51  			}
    52  
    53  			if ipNetOut.String() != ipNetIn.String() {
    54  				t.Fatalf("%v != %v", ipNetOut, ipNetIn)
    55  			}
    56  		})
    57  	}
    58  }