route_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. // Copyright 2019 Yunion
  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 iproute2
  15. import (
  16. "net"
  17. "testing"
  18. "github.com/vishvananda/netlink"
  19. )
  20. func TestRoute(t *testing.T) {
  21. t.Run("ensure non-nil route.dst", func(t *testing.T) {
  22. dstStr := "114.114.114.114"
  23. routes, err := RouteGetByDst(dstStr)
  24. if err != nil {
  25. t.Skipf("route get: %v", err)
  26. }
  27. if len(routes) == 0 {
  28. t.Skipf("no route to %s", dstStr)
  29. }
  30. for _, r := range routes {
  31. if r.LinkIndex <= 0 {
  32. continue
  33. }
  34. nllink, err := netlink.LinkByIndex(r.LinkIndex)
  35. if err != nil {
  36. t.Errorf("link by index: %v", err)
  37. continue
  38. }
  39. routes2, err := NewRoute(nllink.Attrs().Name).List4()
  40. for _, r2 := range routes2 {
  41. if r2.Dst.String() == "0.0.0.0/0" {
  42. t.Logf("yeah, dst of default route is not nil: %s", r2)
  43. }
  44. }
  45. }
  46. })
  47. t.Run("route del", func(t *testing.T) {
  48. ifname := genDummyName(t)
  49. dum := addDummy(t, ifname)
  50. defer delDummy(t, dum)
  51. r := NewRoute(ifname)
  52. r.DelByCidr("10.1.1.30/32")
  53. if err := r.Err(); !IsErrSrch(err) {
  54. t.Errorf("expecting ESRCH, got %v", err)
  55. }
  56. })
  57. t.Run("route add", func(t *testing.T) {
  58. ifname1 := genDummyName(t)
  59. dum := addDummy(t, ifname1)
  60. defer delDummy(t, dum)
  61. ifname := "lo"
  62. for _, cidr := range [][]string{
  63. []string{
  64. "127.1.0.1/24",
  65. "127.0.0.2",
  66. },
  67. []string{
  68. "192.168.120.243/24",
  69. "127.0.0.2",
  70. },
  71. } {
  72. _, ipnet, err := net.ParseCIDR(cidr[0])
  73. if err != nil {
  74. t.Errorf("ParseCIDR error %s", err)
  75. continue
  76. }
  77. gw := net.ParseIP(cidr[1])
  78. r := NewRoute(ifname)
  79. r.AddByIPNet(ipnet, gw)
  80. if err := r.Err(); err != nil {
  81. t.Errorf("got error %v", err)
  82. }
  83. r.DelByIPNet(ipnet)
  84. if err := r.Err(); err != nil {
  85. t.Errorf("del error %v", err)
  86. }
  87. }
  88. })
  89. }