mapper_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package portmapper
  2. import (
  3. "github.com/dotcloud/docker/pkg/iptables"
  4. "github.com/dotcloud/docker/pkg/proxy"
  5. "net"
  6. "testing"
  7. )
  8. func init() {
  9. // override this func to mock out the proxy server
  10. newProxy = proxy.NewStubProxy
  11. }
  12. func reset() {
  13. chain = nil
  14. currentMappings = make(map[string]*mapping)
  15. }
  16. func TestSetIptablesChain(t *testing.T) {
  17. defer reset()
  18. c := &iptables.Chain{
  19. Name: "TEST",
  20. Bridge: "192.168.1.1",
  21. }
  22. if chain != nil {
  23. t.Fatal("chain should be nil at init")
  24. }
  25. SetIptablesChain(c)
  26. if chain == nil {
  27. t.Fatal("chain should not be nil after set")
  28. }
  29. }
  30. func TestMapPorts(t *testing.T) {
  31. dstIp1 := net.ParseIP("192.168.0.1")
  32. dstIp2 := net.ParseIP("192.168.0.2")
  33. dstAddr1 := &net.TCPAddr{IP: dstIp1, Port: 80}
  34. dstAddr2 := &net.TCPAddr{IP: dstIp2, Port: 80}
  35. srcAddr1 := &net.TCPAddr{Port: 1080, IP: net.ParseIP("172.16.0.1")}
  36. srcAddr2 := &net.TCPAddr{Port: 1080, IP: net.ParseIP("172.16.0.2")}
  37. if err := Map(srcAddr1, dstIp1, 80); err != nil {
  38. t.Fatalf("Failed to allocate port: %s", err)
  39. }
  40. if Map(srcAddr1, dstIp1, 80) == nil {
  41. t.Fatalf("Port is in use - mapping should have failed")
  42. }
  43. if Map(srcAddr2, dstIp1, 80) == nil {
  44. t.Fatalf("Port is in use - mapping should have failed")
  45. }
  46. if err := Map(srcAddr2, dstIp2, 80); err != nil {
  47. t.Fatalf("Failed to allocate port: %s", err)
  48. }
  49. if Unmap(dstAddr1) != nil {
  50. t.Fatalf("Failed to release port")
  51. }
  52. if Unmap(dstAddr2) != nil {
  53. t.Fatalf("Failed to release port")
  54. }
  55. if Unmap(dstAddr2) == nil {
  56. t.Fatalf("Port already released, but no error reported")
  57. }
  58. }
  59. func TestGetUDPKey(t *testing.T) {
  60. addr := &net.UDPAddr{IP: net.ParseIP("192.168.1.5"), Port: 53}
  61. key := getKey(addr)
  62. if expected := "192.168.1.5:53/udp"; key != expected {
  63. t.Fatalf("expected key %s got %s", expected, key)
  64. }
  65. }
  66. func TestGetTCPKey(t *testing.T) {
  67. addr := &net.TCPAddr{IP: net.ParseIP("192.168.1.5"), Port: 80}
  68. key := getKey(addr)
  69. if expected := "192.168.1.5:80/tcp"; key != expected {
  70. t.Fatalf("expected key %s got %s", expected, key)
  71. }
  72. }
  73. func TestGetUDPIPAndPort(t *testing.T) {
  74. addr := &net.UDPAddr{IP: net.ParseIP("192.168.1.5"), Port: 53}
  75. ip, port := getIPAndPort(addr)
  76. if expected := "192.168.1.5"; ip.String() != expected {
  77. t.Fatalf("expected ip %s got %s", expected, ip)
  78. }
  79. if ep := 53; port != ep {
  80. t.Fatalf("expected port %d got %d", ep, port)
  81. }
  82. }