You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
1.8 KiB

7 years ago
8 years ago
7 years ago
7 years ago
  1. package p2p
  2. import (
  3. "bytes"
  4. "net"
  5. "strings"
  6. "testing"
  7. "github.com/stretchr/testify/require"
  8. "github.com/tendermint/tendermint/libs/log"
  9. )
  10. func TestListener(t *testing.T) {
  11. // Create a listener
  12. l := NewDefaultListener("tcp://:8001", "", false, log.TestingLogger())
  13. // Dial the listener
  14. lAddr := l.ExternalAddress()
  15. connOut, err := lAddr.Dial()
  16. if err != nil {
  17. t.Fatalf("Could not connect to listener address %v", lAddr)
  18. } else {
  19. t.Logf("Created a connection to listener address %v", lAddr)
  20. }
  21. connIn, ok := <-l.Connections()
  22. if !ok {
  23. t.Fatalf("Could not get inbound connection from listener")
  24. }
  25. msg := []byte("hi!")
  26. go func() {
  27. _, err := connIn.Write(msg)
  28. if err != nil {
  29. t.Error(err)
  30. }
  31. }()
  32. b := make([]byte, 32)
  33. n, err := connOut.Read(b)
  34. if err != nil {
  35. t.Fatalf("Error reading off connection: %v", err)
  36. }
  37. b = b[:n]
  38. if !bytes.Equal(msg, b) {
  39. t.Fatalf("Got %s, expected %s", b, msg)
  40. }
  41. // Close the server, no longer needed.
  42. l.Stop()
  43. }
  44. func TestExternalAddress(t *testing.T) {
  45. {
  46. // Create a listener with no external addr. Should default
  47. // to local ipv4.
  48. l := NewDefaultListener("tcp://:8001", "", false, log.TestingLogger())
  49. lAddr := l.ExternalAddress().String()
  50. _, _, err := net.SplitHostPort(lAddr)
  51. require.Nil(t, err)
  52. spl := strings.Split(lAddr, ".")
  53. require.Equal(t, len(spl), 4)
  54. l.Stop()
  55. }
  56. {
  57. // Create a listener with set external ipv4 addr.
  58. setExAddr := "8.8.8.8:8080"
  59. l := NewDefaultListener("tcp://:8001", setExAddr, false, log.TestingLogger())
  60. lAddr := l.ExternalAddress().String()
  61. require.Equal(t, lAddr, setExAddr)
  62. l.Stop()
  63. }
  64. {
  65. // Invalid external addr causes panic
  66. setExAddr := "awrlsckjnal:8080"
  67. require.Panics(t, func() { NewDefaultListener("tcp://:8001", setExAddr, false, log.TestingLogger()) })
  68. }
  69. }