github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/p2p/nat/nat_test.go (about) 1 // Copyright 2018 The go-ethereum Authors 2 // Copyright 2019 The go-aigar Authors 3 // This file is part of the go-aigar library. 4 // 5 // The go-aigar library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The go-aigar library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the go-aigar library. If not, see <http://www.gnu.org/licenses/>. 17 18 package nat 19 20 import ( 21 "net" 22 "testing" 23 "time" 24 ) 25 26 // This test checks that autodisc doesn't hang and returns 27 // consistent results when multiple goroutines call its methods 28 // concurrently. 29 func TestAutoDiscRace(t *testing.T) { 30 ad := startautodisc("thing", func() Interface { 31 time.Sleep(500 * time.Millisecond) 32 return ExtIP{33, 44, 55, 66} 33 }) 34 35 // Spawn a few concurrent calls to ad.ExternalIP. 36 type rval struct { 37 ip net.IP 38 err error 39 } 40 results := make(chan rval, 50) 41 for i := 0; i < cap(results); i++ { 42 go func() { 43 ip, err := ad.ExternalIP() 44 results <- rval{ip, err} 45 }() 46 } 47 48 // Check that they all return the correct result within the deadline. 49 deadline := time.After(2 * time.Second) 50 for i := 0; i < cap(results); i++ { 51 select { 52 case <-deadline: 53 t.Fatal("deadline exceeded") 54 case rval := <-results: 55 if rval.err != nil { 56 t.Errorf("result %d: unexpected error: %v", i, rval.err) 57 } 58 wantIP := net.IP{33, 44, 55, 66} 59 if !rval.ip.Equal(wantIP) { 60 t.Errorf("result %d: got IP %v, want %v", i, rval.ip, wantIP) 61 } 62 } 63 } 64 }