diff --git a/pkg/netutils/netutils.go b/pkg/netutils/netutils.go index 84e35128b..9f71d83da 100644 --- a/pkg/netutils/netutils.go +++ b/pkg/netutils/netutils.go @@ -139,6 +139,7 @@ func deleteDefaultGWCacheBytes(cacheFile []byte, ipv4, ipv6 bool) ([]byte, error } func deleteDefaultGWResultRoutes(routes []interface{}, dstGW string) ([]interface{}, error) { + var newRoutes []interface{} for i, r := range routes { route, ok := r.(map[string]interface{}) if !ok { @@ -150,12 +151,12 @@ func deleteDefaultGWResultRoutes(routes []interface{}, dstGW string) ([]interfac if !ok { return nil, fmt.Errorf("wrong dst format: %v", route["dst"]) } - if dst == dstGW { - routes = append(routes[:i], routes[i+1:]...) + if dst != dstGW { + newRoutes = append(newRoutes, routes[i]) } } } - return routes, nil + return newRoutes, nil } func deleteDefaultGWResult(result map[string]interface{}, ipv4, ipv6 bool) (map[string]interface{}, error) { diff --git a/pkg/netutils/netutils_test.go b/pkg/netutils/netutils_test.go index e91d38b98..d907184e1 100644 --- a/pkg/netutils/netutils_test.go +++ b/pkg/netutils/netutils_test.go @@ -1421,3 +1421,23 @@ var _ = Describe("netutil cnicache function testing", func() { }) }) + +var _ = Describe("other function unit testing", func() { + It("deleteDefaultGWResultRoutes with invalid config", func() { + cniRouteConfig := []byte(`[ + { "dst": "0.0.0.0/0", "gw": "10.1.1.1" }, + { "dst": "10.1.1.0/24" }, + { "dst": "0.0.0.0/0", "gw": "10.1.1.1" } + ]`) + + var routes []interface{} + err := json.Unmarshal(cniRouteConfig, &routes) + Expect(err).NotTo(HaveOccurred()) + + newRoute, err := deleteDefaultGWResultRoutes(routes, "0.0.0.0/0") + Expect(err).NotTo(HaveOccurred()) + routeJSON, err := json.Marshal(newRoute) + Expect(err).NotTo(HaveOccurred()) + Expect(routeJSON).Should(MatchJSON(`[{"dst":"10.1.1.0/24"}]`)) + }) +})