ip_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2019 the Kilo authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package mesh
  15. import (
  16. "net"
  17. "testing"
  18. )
  19. func TestSortIPs(t *testing.T) {
  20. ip1 := oneAddressCIDR(net.ParseIP("10.0.0.1"))
  21. ip2 := oneAddressCIDR(net.ParseIP("10.0.0.2"))
  22. ip3 := oneAddressCIDR(net.ParseIP("192.168.0.1"))
  23. ip4 := oneAddressCIDR(net.ParseIP("2001::7"))
  24. ip5 := oneAddressCIDR(net.ParseIP("fd68:da49:09da:b27f::"))
  25. for _, tc := range []struct {
  26. name string
  27. ips []*net.IPNet
  28. out []*net.IPNet
  29. }{
  30. {
  31. name: "single",
  32. ips: []*net.IPNet{ip1},
  33. out: []*net.IPNet{ip1},
  34. },
  35. {
  36. name: "IPv4s",
  37. ips: []*net.IPNet{ip2, ip3, ip1},
  38. out: []*net.IPNet{ip1, ip2, ip3},
  39. },
  40. {
  41. name: "IPv4 and IPv6",
  42. ips: []*net.IPNet{ip4, ip1},
  43. out: []*net.IPNet{ip1, ip4},
  44. },
  45. {
  46. name: "IPv6s",
  47. ips: []*net.IPNet{ip5, ip4},
  48. out: []*net.IPNet{ip4, ip5},
  49. },
  50. {
  51. name: "all",
  52. ips: []*net.IPNet{ip3, ip4, ip2, ip5, ip1},
  53. out: []*net.IPNet{ip1, ip2, ip3, ip4, ip5},
  54. },
  55. } {
  56. sortIPs(tc.ips)
  57. equal := true
  58. if len(tc.ips) != len(tc.out) {
  59. equal = false
  60. } else {
  61. for i := range tc.ips {
  62. if !ipNetsEqual(tc.ips[i], tc.out[i]) {
  63. equal = false
  64. break
  65. }
  66. }
  67. }
  68. if !equal {
  69. t.Errorf("test case %q: expected %s, got %s", tc.name, tc.out, tc.ips)
  70. }
  71. }
  72. }