nat_test.go 1.8 KB

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