blob: 5f5f486739bf831cf4735a3d13df9308243b89d9 [file] [log] [blame]
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build fuchsia
package net
import (
"syscall/zx/net"
"syscall/zx/posix/socket"
"testing"
)
func TestIPToSockaddr(t *testing.T) {
type inArgs struct {
domain socket.Domain
ip IP
port int
zone string
}
type want struct {
addr net.SocketAddress
err bool
}
makeIpv4 := func(addr [4]byte, port uint16) net.SocketAddress {
return net.SocketAddressWithIpv4(net.Ipv4SocketAddress{
Address: net.Ipv4Address{
Addr: addr,
},
Port: port,
})
}
makeIpv6 := func(addr [16]byte, port uint16, zone uint64) net.SocketAddress {
return net.SocketAddressWithIpv6(net.Ipv6SocketAddress{
Address: net.Ipv6Address{
Addr: addr,
},
Port: port,
ZoneIndex: zone,
})
}
tests := []struct {
name string
in inArgs
want want
}{
{
"v4 non-numeric string zone ignored",
inArgs{socket.DomainIpv4, ParseIP("1.2.3.4"), 6667, "zone"},
want{makeIpv4([4]byte{1, 2, 3, 4}, 6667), false},
},
{
"v4 numeric string zone ignored",
inArgs{socket.DomainIpv4, ParseIP("1.2.3.4"), 6697, "17"},
want{makeIpv4([4]byte{1, 2, 3, 4}, 6697), false},
},
{
"v4 invalid IP returns error",
inArgs{socket.DomainIpv4, IP([]byte{1}), 6697, ""},
want{net.SocketAddress{}, true},
},
{
"v6 with known non-numeric zone converted",
// This test runs in a sandbox with interface 'lo' on index 1.
inArgs{socket.DomainIpv6, ParseIP("fe80::1"), 443, "lo"},
want{makeIpv6([16]byte{0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, 443, 1), false},
},
{
"v6 with unknown non-numeric zone ignored",
inArgs{socket.DomainIpv6, ParseIP("fe80::1"), 443, "unknownif"},
want{makeIpv6([16]byte{0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, 443, 0), false},
},
{
"v6 with numeric zone handled properly",
inArgs{socket.DomainIpv6, ParseIP("fe80::1"), 80, "42"},
want{makeIpv6([16]byte{0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, 80, 42), false},
},
{
"v6 invalid IP returns error",
inArgs{socket.DomainIpv6, IP([]byte{1}), 1, ""},
want{net.SocketAddress{}, true},
},
}
for _, test := range tests {
addr, err := ipToSockaddr(test.in.domain, test.in.ip, test.in.port, test.in.zone)
if test.want.err && err == nil {
t.Errorf("test %q returned no error, but an error was expected", test.name)
continue
} else if !test.want.err && err != nil {
t.Errorf("test %q got error %v; no error was expected", test.name, err)
continue
}
if addr != test.want.addr {
t.Errorf("test %q got addr %v, wanted %v", test.name, addr, test.want.addr)
}
}
}