github.com/arieschain/arieschain@v0.0.0-20191023063405-37c074544356/p2p/nat/nat_test.go (about)

     1  package nat
     2  
     3  import (
     4  	"net"
     5  	"testing"
     6  	"time"
     7  )
     8  
     9  // This test checks that autodisc doesn't hang and returns
    10  // consistent results when multiple goroutines call its methods
    11  // concurrently.
    12  func TestAutoDiscRace(t *testing.T) {
    13  	ad := startautodisc("thing", func() Interface {
    14  		time.Sleep(500 * time.Millisecond)
    15  		return extIP{33, 44, 55, 66}
    16  	})
    17  
    18  	// Spawn a few concurrent calls to ad.ExternalIP.
    19  	type rval struct {
    20  		ip  net.IP
    21  		err error
    22  	}
    23  	results := make(chan rval, 50)
    24  	for i := 0; i < cap(results); i++ {
    25  		go func() {
    26  			ip, err := ad.ExternalIP()
    27  			results <- rval{ip, err}
    28  		}()
    29  	}
    30  
    31  	// Check that they all return the correct result within the deadline.
    32  	deadline := time.After(2 * time.Second)
    33  	for i := 0; i < cap(results); i++ {
    34  		select {
    35  		case <-deadline:
    36  			t.Fatal("deadline exceeded")
    37  		case rval := <-results:
    38  			if rval.err != nil {
    39  				t.Errorf("result %d: unexpected error: %v", i, rval.err)
    40  			}
    41  			wantIP := net.IP{33, 44, 55, 66}
    42  			if !rval.ip.Equal(wantIP) {
    43  				t.Errorf("result %d: got IP %v, want %v", i, rval.ip, wantIP)
    44  			}
    45  		}
    46  	}
    47  }