| // 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 ( |
| "bytes" |
| "syscall" |
| "syscall/zx/mxnet" |
| "testing" |
| ) |
| |
| func TestIPToSockaddr(t *testing.T) { |
| type inArgs struct { |
| family int |
| ip IP |
| port int |
| zone string |
| } |
| |
| type want struct { |
| addr mxnet.Addr |
| portres uint16 |
| zone uint32 |
| err bool |
| } |
| |
| tests := []struct { |
| name string |
| in inArgs |
| want want |
| }{ |
| { |
| "v4 non-numeric string zone ignored", |
| inArgs{syscall.AF_INET, ParseIP("1.2.3.4"), 6667, "zone"}, |
| want{mxnet.Addr([]byte{1, 2, 3, 4}), 6667, 0, false}, |
| }, |
| { |
| "v4 numeric string zone ignored", |
| inArgs{syscall.AF_INET, ParseIP("1.2.3.4"), 6697, "17"}, |
| want{mxnet.Addr([]byte{1, 2, 3, 4}), 6697, 0, false}, |
| }, |
| { |
| "v4 invalid IP returns error", |
| inArgs{syscall.AF_INET, IP([]byte{1}), 6697, ""}, |
| want{"", 0, 0, true}, |
| }, |
| { |
| "v6 with non-numeric zone ignored", |
| inArgs{syscall.AF_INET6, ParseIP("fe80::1"), 443, "zone"}, |
| want{mxnet.Addr([]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{syscall.AF_INET6, ParseIP("fe80::1"), 80, "42"}, |
| want{mxnet.Addr([]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{syscall.AF_INET6, IP([]byte{1}), 1, ""}, |
| want{"", 0, 0, true}, |
| }, |
| } |
| |
| for _, test := range tests { |
| addr, portres, zone, err := ipToSockaddr(test.in.family, 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 !bytes.Equal([]byte(addr), []byte(test.want.addr)) { |
| t.Errorf("test %q got addr %v, wanted %v", test.name, []byte(addr), []byte(test.want.addr)) |
| } |
| |
| if portres != test.want.portres { |
| t.Errorf("test %q got portres %d, wanted %d", test.name, portres, test.want.portres) |
| } |
| |
| if zone != test.want.zone { |
| t.Errorf("test %q got zone %d, wanted %d", test.name, zone, test.want.zone) |
| } |
| } |
| } |