github.com/ader1990/go@v0.0.0-20140630135419-8c24447fa791/src/pkg/net/hosts_test.go (about) 1 // Copyright 2009 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package net 6 7 import ( 8 "sort" 9 "testing" 10 ) 11 12 type hostTest struct { 13 host string 14 ips []IP 15 } 16 17 var hosttests = []hostTest{ 18 {"odin", []IP{ 19 IPv4(127, 0, 0, 2), 20 IPv4(127, 0, 0, 3), 21 ParseIP("::2"), 22 }}, 23 {"thor", []IP{ 24 IPv4(127, 1, 1, 1), 25 }}, 26 {"loki", []IP{}}, 27 {"ullr", []IP{ 28 IPv4(127, 1, 1, 2), 29 }}, 30 {"ullrhost", []IP{ 31 IPv4(127, 1, 1, 2), 32 }}, 33 } 34 35 func TestLookupStaticHost(t *testing.T) { 36 p := hostsPath 37 hostsPath = "testdata/hosts" 38 for i := 0; i < len(hosttests); i++ { 39 tt := hosttests[i] 40 ips := lookupStaticHost(tt.host) 41 if len(ips) != len(tt.ips) { 42 t.Errorf("# of hosts = %v; want %v", 43 len(ips), len(tt.ips)) 44 continue 45 } 46 for k, v := range ips { 47 if tt.ips[k].String() != v { 48 t.Errorf("lookupStaticHost(%q) = %v; want %v", 49 tt.host, v, tt.ips[k]) 50 } 51 } 52 } 53 hostsPath = p 54 } 55 56 // https://code.google.com/p/go/issues/detail?id=6646 57 func TestSingleLineHostsFile(t *testing.T) { 58 p := hostsPath 59 hostsPath = "testdata/hosts_singleline" 60 61 ips := lookupStaticHost("odin") 62 if len(ips) != 1 || ips[0] != "127.0.0.2" { 63 t.Errorf("lookupStaticHost = %v, want %v", ips, []string{"127.0.0.2"}) 64 } 65 66 hostsPath = p 67 } 68 69 func TestLookupHost(t *testing.T) { 70 // Can't depend on this to return anything in particular, 71 // but if it does return something, make sure it doesn't 72 // duplicate addresses (a common bug due to the way 73 // getaddrinfo works). 74 addrs, _ := LookupHost("localhost") 75 sort.Strings(addrs) 76 for i := 0; i+1 < len(addrs); i++ { 77 if addrs[i] == addrs[i+1] { 78 t.Fatalf("LookupHost(\"localhost\") = %v, has duplicate addresses", addrs) 79 } 80 } 81 }