tree6_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package cidr
  2. import (
  3. "encoding/binary"
  4. "net"
  5. "testing"
  6. "github.com/stretchr/testify/assert"
  7. )
  8. func TestCIDR6Tree_MostSpecificContains(t *testing.T) {
  9. tree := NewTree6()
  10. tree.AddCIDR(Parse("1.0.0.0/8"), "1")
  11. tree.AddCIDR(Parse("2.1.0.0/16"), "2")
  12. tree.AddCIDR(Parse("3.1.1.0/24"), "3")
  13. tree.AddCIDR(Parse("4.1.1.1/24"), "4a")
  14. tree.AddCIDR(Parse("4.1.1.1/30"), "4b")
  15. tree.AddCIDR(Parse("4.1.1.1/32"), "4c")
  16. tree.AddCIDR(Parse("254.0.0.0/4"), "5")
  17. tree.AddCIDR(Parse("1:2:0:4:5:0:0:0/64"), "6a")
  18. tree.AddCIDR(Parse("1:2:0:4:5:0:0:0/80"), "6b")
  19. tree.AddCIDR(Parse("1:2:0:4:5:0:0:0/96"), "6c")
  20. tests := []struct {
  21. Result interface{}
  22. IP string
  23. }{
  24. {"1", "1.0.0.0"},
  25. {"1", "1.255.255.255"},
  26. {"2", "2.1.0.0"},
  27. {"2", "2.1.255.255"},
  28. {"3", "3.1.1.0"},
  29. {"3", "3.1.1.255"},
  30. {"4a", "4.1.1.255"},
  31. {"4b", "4.1.1.2"},
  32. {"4c", "4.1.1.1"},
  33. {"5", "240.0.0.0"},
  34. {"5", "255.255.255.255"},
  35. {"6a", "1:2:0:4:1:1:1:1"},
  36. {"6b", "1:2:0:4:5:1:1:1"},
  37. {"6c", "1:2:0:4:5:0:0:0"},
  38. {nil, "239.0.0.0"},
  39. {nil, "4.1.2.2"},
  40. }
  41. for _, tt := range tests {
  42. assert.Equal(t, tt.Result, tree.MostSpecificContains(net.ParseIP(tt.IP)))
  43. }
  44. tree = NewTree6()
  45. tree.AddCIDR(Parse("1.1.1.1/0"), "cool")
  46. tree.AddCIDR(Parse("::/0"), "cool6")
  47. assert.Equal(t, "cool", tree.MostSpecificContains(net.ParseIP("0.0.0.0")))
  48. assert.Equal(t, "cool", tree.MostSpecificContains(net.ParseIP("255.255.255.255")))
  49. assert.Equal(t, "cool6", tree.MostSpecificContains(net.ParseIP("::")))
  50. assert.Equal(t, "cool6", tree.MostSpecificContains(net.ParseIP("1:2:3:4:5:6:7:8")))
  51. }
  52. func TestCIDR6Tree_MostSpecificContainsIpV6(t *testing.T) {
  53. tree := NewTree6()
  54. tree.AddCIDR(Parse("1:2:0:4:5:0:0:0/64"), "6a")
  55. tree.AddCIDR(Parse("1:2:0:4:5:0:0:0/80"), "6b")
  56. tree.AddCIDR(Parse("1:2:0:4:5:0:0:0/96"), "6c")
  57. tests := []struct {
  58. Result interface{}
  59. IP string
  60. }{
  61. {"6a", "1:2:0:4:1:1:1:1"},
  62. {"6b", "1:2:0:4:5:1:1:1"},
  63. {"6c", "1:2:0:4:5:0:0:0"},
  64. }
  65. for _, tt := range tests {
  66. ip := net.ParseIP(tt.IP)
  67. hi := binary.BigEndian.Uint64(ip[:8])
  68. lo := binary.BigEndian.Uint64(ip[8:])
  69. assert.Equal(t, tt.Result, tree.MostSpecificContainsIpV6(hi, lo))
  70. }
  71. }