Repository: spidernet-io/spiderpool
Pull request #1157 (2022-12-08 10:39:51)

test: Add unit tests for pkg reservedipmanager
Signed-off-by: iiiceoo <ziqian.xue@daocloud.io>


sonarcloud[bot]: SonarCloud Quality Gate failed.&nbsp; &nbsp; [![Quality Gate failed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/failed-16px.png 'Quality Gate failed')](https://sonarcloud.io/dashboard?id=spidernet-io_spiderpool&pullRequest=1157)

[![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=BUG)  
[![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=VULNERABILITY)  
[![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=SECURITY_HOTSPOT) [![E](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/E-16px.png 'E')](https://sonarcloud.io/project/security_hotspots?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=SECURITY_HOTSPOT) [13 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=SECURITY_HOTSPOT)  
[![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=CODE_SMELL) [7 Code Smells](https://sonarcloud.io/project/issues?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=CODE_SMELL)

[![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=spidernet-io_spiderpool&pullRequest=1157) No Coverage information  
[![1.0%](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/3-16px.png '1.0%')](https://sonarcloud.io/component_measures?id=spidernet-io_spiderpool&pullRequest=1157&metric=new_duplicated_lines_density&view=list) [1.0% Duplication](https://sonarcloud.io/component_measures?id=spidernet-io_spiderpool&pullRequest=1157&metric=new_duplicated_lines_density&view=list)


sonarcloud[bot]: SonarCloud Quality Gate failed.&nbsp; &nbsp; [![Quality Gate failed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/failed-16px.png 'Quality Gate failed')](https://sonarcloud.io/dashboard?id=spidernet-io_spiderpool&pullRequest=1157)

[![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=BUG) [![C](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/C-16px.png 'C')](https://sonarcloud.io/project/issues?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=BUG) [1 Bug](https://sonarcloud.io/project/issues?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=BUG)  
[![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=VULNERABILITY)  
[![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=SECURITY_HOTSPOT) [![E](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/E-16px.png 'E')](https://sonarcloud.io/project/security_hotspots?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=SECURITY_HOTSPOT) [27 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=SECURITY_HOTSPOT)  
[![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=CODE_SMELL) [8 Code Smells](https://sonarcloud.io/project/issues?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=CODE_SMELL)

[![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=spidernet-io_spiderpool&pullRequest=1157) No Coverage information  
[![3.3%](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/5-16px.png '3.3%')](https://sonarcloud.io/component_measures?id=spidernet-io_spiderpool&pullRequest=1157&metric=new_duplicated_lines_density&view=list) [3.3% Duplication](https://sonarcloud.io/component_measures?id=spidernet-io_spiderpool&pullRequest=1157&metric=new_duplicated_lines_density&view=list)


sonarcloud[bot]: SonarCloud Quality Gate failed.&nbsp; &nbsp; [![Quality Gate failed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/failed-16px.png 'Quality Gate failed')](https://sonarcloud.io/dashboard?id=spidernet-io_spiderpool&pullRequest=1157)

[![Bug](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/bug-16px.png 'Bug')](https://sonarcloud.io/project/issues?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=BUG) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=BUG) [0 Bugs](https://sonarcloud.io/project/issues?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=BUG)  
[![Vulnerability](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/vulnerability-16px.png 'Vulnerability')](https://sonarcloud.io/project/issues?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=VULNERABILITY) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=VULNERABILITY) [0 Vulnerabilities](https://sonarcloud.io/project/issues?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=VULNERABILITY)  
[![Security Hotspot](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/security_hotspot-16px.png 'Security Hotspot')](https://sonarcloud.io/project/security_hotspots?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=SECURITY_HOTSPOT) [![E](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/E-16px.png 'E')](https://sonarcloud.io/project/security_hotspots?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=SECURITY_HOTSPOT) [27 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=SECURITY_HOTSPOT)  
[![Code Smell](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/code_smell-16px.png 'Code Smell')](https://sonarcloud.io/project/issues?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=CODE_SMELL) [![A](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/RatingBadge/A-16px.png 'A')](https://sonarcloud.io/project/issues?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=CODE_SMELL) [8 Code Smells](https://sonarcloud.io/project/issues?id=spidernet-io_spiderpool&pullRequest=1157&resolved=false&types=CODE_SMELL)

[![No Coverage information](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/CoverageChart/NoCoverageInfo-16px.png 'No Coverage information')](https://sonarcloud.io/component_measures?id=spidernet-io_spiderpool&pullRequest=1157) No Coverage information  
[![3.5%](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/Duplications/5-16px.png '3.5%')](https://sonarcloud.io/component_measures?id=spidernet-io_spiderpool&pullRequest=1157&metric=new_duplicated_lines_density&view=list) [3.5% Duplication](https://sonarcloud.io/component_measures?id=spidernet-io_spiderpool&pullRequest=1157&metric=new_duplicated_lines_density&view=list)



Patch:
diff --git a/cmd/spiderpool-agent/cmd/daemon.go b/cmd/spiderpool-agent/cmd/daemon.go
index 2e7d0caee..077adba90 100644
--- a/cmd/spiderpool-agent/cmd/daemon.go
+++ b/cmd/spiderpool-agent/cmd/daemon.go
@@ -271,24 +271,21 @@ func initAgentServiceManagers(ctx context.Context) {
 	}
 	agentContext.WEManager = weManager
 
-	logger.Debug("Begin to initialize ReservedIP Manager")
-	rIPManager, err := reservedipmanager.NewReservedIPManager(&reservedipmanager.ReservedIPManagerConfig{
-		EnableIPv4: agentContext.Cfg.EnableIPv4,
-		EnableIPv6: agentContext.Cfg.EnableIPv6,
-	}, agentContext.CRDManager)
+	logger.Debug("Begin to initialize ReservedIP manager")
+	rIPManager, err := reservedipmanager.NewReservedIPManager(agentContext.CRDManager.GetClient())
 	if err != nil {
 		logger.Fatal(err.Error())
 	}
 	agentContext.RIPManager = rIPManager
 
-	logger.Debug("Begin to initialize Node Manager")
+	logger.Debug("Begin to initialize Node manager")
 	nodeManager, err := nodemanager.NewNodeManager(agentContext.CRDManager.GetClient())
 	if err != nil {
 		logger.Fatal(err.Error())
 	}
 	agentContext.NodeManager = nodeManager
 
-	logger.Debug("Begin to initialize Namespace Manager")
+	logger.Debug("Begin to initialize Namespace manager")
 	nsManager, err := namespacemanager.NewNamespaceManager(agentContext.CRDManager.GetClient())
 	if err != nil {
 		logger.Fatal(err.Error())
diff --git a/cmd/spiderpool-controller/cmd/daemon.go b/cmd/spiderpool-controller/cmd/daemon.go
index 403f3cd17..3e114e23b 100644
--- a/cmd/spiderpool-controller/cmd/daemon.go
+++ b/cmd/spiderpool-controller/cmd/daemon.go
@@ -234,30 +234,30 @@ func initControllerServiceManagers(ctx context.Context) {
 		logger.Fatal(err.Error())
 	}
 
-	logger.Info("Begin to initialize ReservedIP Manager")
-	rIPManager, err := reservedipmanager.NewReservedIPManager(&reservedipmanager.ReservedIPManagerConfig{
-		EnableIPv4: controllerContext.Cfg.EnableIPv4,
-		EnableIPv6: controllerContext.Cfg.EnableIPv6,
-	}, controllerContext.CRDManager)
+	logger.Debug("Begin to initialize ReservedIP manager")
+	rIPManager, err := reservedipmanager.NewReservedIPManager(controllerContext.CRDManager.GetClient())
 	if err != nil {
 		logger.Fatal(err.Error())
 	}
 	controllerContext.RIPManager = rIPManager
 
-	logger.Info("Begin to set up ReservedIP webhook")
-	err = controllerContext.RIPManager.SetupWebhook()
-	if err != nil {
+	logger.Debug("Begin to set up ReservedIP webhook")
+	if err := (&reservedipmanager.ReservedIPWebhook{
+		ReservedIPManager: rIPManager,
+		EnableIPv4:        controllerContext.Cfg.EnableIPv4,
+		EnableIPv6:        controllerContext.Cfg.EnableIPv6,
+	}).SetupWebhookWithManager(controllerContext.CRDManager); err != nil {
 		logger.Fatal(err.Error())
 	}
 
-	logger.Info("Begin to initialize Node Manager")
+	logger.Debug("Begin to initialize Node manager")
 	nodeManager, err := nodemanager.NewNodeManager(controllerContext.CRDManager.GetClient())
 	if err != nil {
 		logger.Fatal(err.Error())
 	}
 	controllerContext.NodeManager = nodeManager
 
-	logger.Info("Begin to initialize Namespace Manager")
+	logger.Debug("Begin to initialize Namespace manager")
 	nsManager, err := namespacemanager.NewNamespaceManager(controllerContext.CRDManager.GetClient())
 	if err != nil {
 		logger.Fatal(err.Error())
diff --git a/go.mod b/go.mod
index a47afb594..ac5f90d23 100644
--- a/go.mod
+++ b/go.mod
@@ -48,6 +48,7 @@ require (
 
 require (
 	github.com/agiledragon/gomonkey/v2 v2.9.0
+	github.com/golang/mock v1.6.0
 	github.com/openkruise/kruise-api v1.3.0
 	go.uber.org/multierr v1.8.0
 )
diff --git a/go.sum b/go.sum
index 0ef3a5ab9..09c3c846e 100644
--- a/go.sum
+++ b/go.sum
@@ -270,6 +270,7 @@ github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt
 github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw=
 github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4=
 github.com/golang/mock v1.5.0/go.mod h1:CWnOUgYIOo4TcNZ0wHX3YZCqsaM1I1Jvs6v3mP3KVu8=
+github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc=
 github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs=
 github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
 github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
diff --git a/pkg/constant/ip.go b/pkg/constant/ip.go
index 8fcbc17fa..95e41d778 100644
--- a/pkg/constant/ip.go
+++ b/pkg/constant/ip.go
@@ -9,3 +9,14 @@ const (
 	IPv4 types.IPVersion = 4
 	IPv6 types.IPVersion = 6
 )
+
+const (
+	InvalidIPVersion = types.IPVersion(976)
+	InvalidCIDR      = "invalid CIDR"
+	InvalidIP        = "invalid IP"
+	InvalidIPRange   = "invalid IP range"
+	InvalidDst       = "invalid routing destination"
+	InvalidGateway   = "invalid routing gateway"
+)
+
+var InvalidIPRanges = []string{InvalidIPRange}
diff --git a/pkg/constant/k8s.go b/pkg/constant/k8s.go
index ff12e1aa3..fd096cf44 100644
--- a/pkg/constant/k8s.go
+++ b/pkg/constant/k8s.go
@@ -77,16 +77,20 @@ const (
 )
 
 const (
-	Spiderpool             = "spiderpool"
-	SpiderpoolAgent        = "spiderpool-agent"
-	SpiderpoolController   = "spiderpool-controller"
-	SpiderpoolAPIGroup     = "spiderpool.spidernet.io"
-	SpiderFinalizer        = SpiderpoolAPIGroup
-	SpiderpoolAPIVersionV1 = "v1"
-	SpiderIPPoolKind       = "SpiderIPPool"
-	SpiderEndpointKind     = "SpiderEndpoint"
-	SpiderReservedIPKind   = "SpiderReservedIP"
-	SpiderSubnetKind       = "SpiderSubnet"
+	Spiderpool               = "spiderpool"
+	SpiderpoolAgent          = "spiderpool-agent"
+	SpiderpoolController     = "spiderpool-controller"
+	SpiderpoolAPIGroup       = "spiderpool.spidernet.io"
+	SpiderFinalizer          = SpiderpoolAPIGroup
+	SpiderpoolAPIVersionV1   = "v1"
+	SpiderIPPoolKind         = "SpiderIPPool"
+	SpiderEndpointKind       = "SpiderEndpoint"
+	SpiderReservedIPKind     = "SpiderReservedIP"
+	SpiderSubnetKind         = "SpiderSubnet"
+	SpiderIPPoolListKind     = "SpiderIPPoolList"
+	SpiderEndpointListKind   = "SpiderEndpointList"
+	SpiderReservedIPListKind = "SpiderReservedIPList"
+	SpiderSubnetListKind     = "SpiderSubnetList"
 )
 
 const (
diff --git a/pkg/ippoolmanager/ippool_manager.go b/pkg/ippoolmanager/ippool_manager.go
index 3f8365581..1729dac10 100644
--- a/pkg/ippoolmanager/ippool_manager.go
+++ b/pkg/ippoolmanager/ippool_manager.go
@@ -178,7 +178,7 @@ func (im *ipPoolManager) genRandomIP(ctx context.Context, ipPool *spiderpoolv1.S
 	if err != nil {
 		return nil, err
 	}
-	reservedIPs, err := reservedipmanager.GetReservedIPsByIPVersion(*ipPool.Spec.IPVersion, rIPList)
+	reservedIPs, err := reservedipmanager.AssembleReservedIPs(*ipPool.Spec.IPVersion, rIPList)
 	if err != nil {
 		return nil, err
 	}
diff --git a/pkg/k8s/apis/spiderpool.spidernet.io/v1/spiderreservedip_types.go b/pkg/k8s/apis/spiderpool.spidernet.io/v1/spiderreservedip_types.go
index 3446e238e..926d84a6c 100644
--- a/pkg/k8s/apis/spiderpool.spidernet.io/v1/spiderreservedip_types.go
+++ b/pkg/k8s/apis/spiderpool.spidernet.io/v1/spiderreservedip_types.go
@@ -14,7 +14,7 @@ type ReservedIPSpec struct {
 	IPVersion *int64 `json:"ipVersion,omitempty"`
 
 	// +kubebuilder:validation:Optional
-	IPs []string `json:"ips"`
+	IPs []string `json:"ips,omitempty"`
 }
 
 // +kubebuilder:resource:categories={spiderpool},path="spiderreservedips",scope="Cluster",shortName={sr},singular="spiderreservedip"
diff --git a/pkg/namespacemanager/utils.go b/pkg/namespacemanager/utils.go
index 348bc6f8f..e2d13bf63 100644
--- a/pkg/namespacemanager/utils.go
+++ b/pkg/namespacemanager/utils.go
@@ -5,6 +5,7 @@ package namespacemanager
 
 import (
 	"encoding/json"
+	"fmt"
 
 	corev1 "k8s.io/api/core/v1"
 
@@ -13,6 +14,10 @@ import (
 )
 
 func GetNSDefaultPools(ns *corev1.Namespace) ([]string, []string, error) {
+	if ns == nil {
+		return nil, nil, fmt.Errorf("namespace %w", constant.ErrMissingRequiredParam)
+	}
+
 	var nsDefaultV4Pool types.AnnoNSDefautlV4PoolValue
 	var nsDefaultV6Pool types.AnnoNSDefautlV6PoolValue
 	if v, ok := ns.Annotations[constant.AnnoNSDefautlV4Pool]; ok {
diff --git a/pkg/reservedipmanager/config.go b/pkg/reservedipmanager/config.go
deleted file mode 100644
index 57c856fa6..000000000
--- a/pkg/reservedipmanager/config.go
+++ /dev/null
@@ -1,9 +0,0 @@
-// Copyright 2022 Authors of spidernet-io
-// SPDX-License-Identifier: Apache-2.0
-
-package reservedipmanager
-
-type ReservedIPManagerConfig struct {
-	EnableIPv4 bool
-	EnableIPv6 bool
-}
diff --git a/pkg/reservedipmanager/mock/reservedip_manager_mock.go b/pkg/reservedipmanager/mock/reservedip_manager_mock.go
new file mode 100644
index 000000000..ff22121ff
--- /dev/null
+++ b/pkg/reservedipmanager/mock/reservedip_manager_mock.go
@@ -0,0 +1,75 @@
+// Copyright 2022 Authors of spidernet-io
+// SPDX-License-Identifier: Apache-2.0
+
+// Code generated by MockGen. DO NOT EDIT.
+// Source: ./reservedip_manager.go
+
+// Package mock_reservedipmanager is a generated GoMock package.
+package mock_reservedipmanager
+
+import (
+	context "context"
+	reflect "reflect"
+
+	gomock "github.com/golang/mock/gomock"
+	v1 "github.com/spidernet-io/spiderpool/pkg/k8s/apis/spiderpool.spidernet.io/v1"
+	client "sigs.k8s.io/controller-runtime/pkg/client"
+)
+
+// MockReservedIPManager is a mock of ReservedIPManager interface.
+type MockReservedIPManager struct {
+	ctrl     *gomock.Controller
+	recorder *MockReservedIPManagerMockRecorder
+}
+
+// MockReservedIPManagerMockRecorder is the mock recorder for MockReservedIPManager.
+type MockReservedIPManagerMockRecorder struct {
+	mock *MockReservedIPManager
+}
+
+// NewMockReservedIPManager creates a new mock instance.
+func NewMockReservedIPManager(ctrl *gomock.Controller) *MockReservedIPManager {
+	mock := &MockReservedIPManager{ctrl: ctrl}
+	mock.recorder = &MockReservedIPManagerMockRecorder{mock}
+	return mock
+}
+
+// EXPECT returns an object that allows the caller to indicate expected use.
+func (m *MockReservedIPManager) EXPECT() *MockReservedIPManagerMockRecorder {
+	return m.recorder
+}
+
+// GetReservedIPByName mocks base method.
+func (m *MockReservedIPManager) GetReservedIPByName(ctx context.Context, rIPName string) (*v1.SpiderReservedIP, error) {
+	m.ctrl.T.Helper()
+	ret := m.ctrl.Call(m, "GetReservedIPByName", ctx, rIPName)
+	ret0, _ := ret[0].(*v1.SpiderReservedIP)
+	ret1, _ := ret[1].(error)
+	return ret0, ret1
+}
+
+// GetReservedIPByName indicates an expected call of GetReservedIPByName.
+func (mr *MockReservedIPManagerMockRecorder) GetReservedIPByName(ctx, rIPName interface{}) *gomock.Call {
+	mr.mock.ctrl.T.Helper()
+	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetReservedIPByName", reflect.TypeOf((*MockReservedIPManager)(nil).GetReservedIPByName), ctx, rIPName)
+}
+
+// ListReservedIPs mocks base method.
+func (m *MockReservedIPManager) ListReservedIPs(ctx context.Context, opts ...client.ListOption) (*v1.SpiderReservedIPList, error) {
+	m.ctrl.T.Helper()
+	varargs := []interface{}{ctx}
+	for _, a := range opts {
+		varargs = append(varargs, a)
+	}
+	ret := m.ctrl.Call(m, "ListReservedIPs", varargs...)
+	ret0, _ := ret[0].(*v1.SpiderReservedIPList)
+	ret1, _ := ret[1].(error)
+	return ret0, ret1
+}
+
+// ListReservedIPs indicates an expected call of ListReservedIPs.
+func (mr *MockReservedIPManagerMockRecorder) ListReservedIPs(ctx interface{}, opts ...interface{}) *gomock.Call {
+	mr.mock.ctrl.T.Helper()
+	varargs := append([]interface{}{ctx}, opts...)
+	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListReservedIPs", reflect.TypeOf((*MockReservedIPManager)(nil).ListReservedIPs), varargs...)
+}
diff --git a/pkg/reservedipmanager/reservedip_manager.go b/pkg/reservedipmanager/reservedip_manager.go
index 72217ab5a..632460027 100644
--- a/pkg/reservedipmanager/reservedip_manager.go
+++ b/pkg/reservedipmanager/reservedip_manager.go
@@ -5,39 +5,31 @@ package reservedipmanager
 
 import (
 	"context"
-	"errors"
+	"fmt"
 
 	apitypes "k8s.io/apimachinery/pkg/types"
-	ctrl "sigs.k8s.io/controller-runtime"
 	"sigs.k8s.io/controller-runtime/pkg/client"
 
+	"github.com/spidernet-io/spiderpool/pkg/constant"
 	spiderpoolv1 "github.com/spidernet-io/spiderpool/pkg/k8s/apis/spiderpool.spidernet.io/v1"
 )
 
 type ReservedIPManager interface {
-	SetupWebhook() error
 	GetReservedIPByName(ctx context.Context, rIPName string) (*spiderpoolv1.SpiderReservedIP, error)
 	ListReservedIPs(ctx context.Context, opts ...client.ListOption) (*spiderpoolv1.SpiderReservedIPList, error)
 }
 
 type reservedIPManager struct {
-	config     *ReservedIPManagerConfig
-	client     client.Client
-	runtimeMgr ctrl.Manager
+	client client.Client
 }
 
-func NewReservedIPManager(c *ReservedIPManagerConfig, mgr ctrl.Manager) (ReservedIPManager, error) {
-	if c == nil {
-		return nil, errors.New("reserved IP manager config must be specified")
-	}
-	if mgr == nil {
-		return nil, errors.New("k8s manager must be specified")
+func NewReservedIPManager(client client.Client) (ReservedIPManager, error) {
+	if client == nil {
+		return nil, fmt.Errorf("k8s client %w", constant.ErrMissingRequiredParam)
 	}
 
 	return &reservedIPManager{
-		config:     c,
-		client:     mgr.GetClient(),
-		runtimeMgr: mgr,
+		client: client,
 	}, nil
 }
 
diff --git a/pkg/reservedipmanager/reservedip_mutate.go b/pkg/reservedipmanager/reservedip_mutate.go
new file mode 100644
index 000000000..b24781b4c
--- /dev/null
+++ b/pkg/reservedipmanager/reservedip_mutate.go
@@ -0,0 +1,57 @@
+// Copyright 2022 Authors of spidernet-io
+// SPDX-License-Identifier: Apache-2.0
+
+package reservedipmanager
+
+import (
+	"context"
+	"errors"
+	"fmt"
+
+	"github.com/spidernet-io/spiderpool/pkg/constant"
+	spiderpoolip "github.com/spidernet-io/spiderpool/pkg/ip"
+	spiderpoolv1 "github.com/spidernet-io/spiderpool/pkg/k8s/apis/spiderpool.spidernet.io/v1"
+	"github.com/spidernet-io/spiderpool/pkg/logutils"
+	"github.com/spidernet-io/spiderpool/pkg/types"
+)
+
+func (rw *ReservedIPWebhook) mutateReservedIP(ctx context.Context, rIP *spiderpoolv1.SpiderReservedIP) error {
+	logger := logutils.FromContext(ctx)
+	logger.Info("Start to mutate ReservedIP")
+
+	if rIP.DeletionTimestamp != nil {
+		logger.Info("Deleting ReservedIP, noting to mutate")
+		return nil
+	}
+
+	if len(rIP.Spec.IPs) == 0 {
+		return errors.New("empty 'spec.ips', noting to mutate")
+	}
+
+	if rIP.Spec.IPVersion == nil {
+		var version types.IPVersion
+		if spiderpoolip.IsIPv4IPRange(rIP.Spec.IPs[0]) {
+			version = constant.IPv4
+		} else if spiderpoolip.IsIPv6IPRange(rIP.Spec.IPs[0]) {
+			version = constant.IPv6
+		} else {
+			return errors.New("invalid 'spec.ipVersion', noting to mutate")
+		}
+
+		rIP.Spec.IPVersion = new(types.IPVersion)
+		*rIP.Spec.IPVersion = version
+		logger.Sugar().Infof("Set 'spec.ipVersion' to %d", version)
+	}
+
+	if len(rIP.Spec.IPs) > 1 {
+		mergedIPs, err := spiderpoolip.MergeIPRanges(*rIP.Spec.IPVersion, rIP.Spec.IPs)
+		if err != nil {
+			return fmt.Errorf("failed to merge 'spec.ips': %v", err)
+		}
+
+		rIP.Spec.IPs = mergedIPs
+		logger.Sugar().Debugf("Merge 'spec.ips':\n%v\n\nto:\n\n%v", rIP.Spec.IPs, mergedIPs)
+	}
+
+	return nil
+}
diff --git a/pkg/reservedipmanager/reservedip_validate.go b/pkg/reservedipmanager/reservedip_validate.go
index 97383935a..b72777e1a 100644
--- a/pkg/reservedipmanager/reservedip_validate.go
+++ b/pkg/reservedipmanager/reservedip_validate.go
@@ -21,9 +21,9 @@ var (
 	ipsField       *field.Path = field.NewPath("spec").Child("ips")
 )
 
-func (rm *reservedIPManager) validateCreateReservedIP(ctx context.Context, rIP *spiderpoolv1.SpiderReservedIP) field.ErrorList {
+func (rw *ReservedIPWebhook) validateCreateReservedIP(ctx context.Context, rIP *spiderpoolv1.SpiderReservedIP) field.ErrorList {
 	var errs field.ErrorList
-	if err := rm.validateReservedIPSpec(ctx, rIP); err != nil {
+	if err := rw.validateReservedIPSpec(ctx, rIP); err != nil {
 		errs = append(errs, err)
 	}
 
@@ -34,13 +34,13 @@ func (rm *reservedIPManager) validateCreateReservedIP(ctx context.Context, rIP *
 	return errs
 }
 
-func (rm *reservedIPManager) validateUpdateReservedIP(ctx context.Context, oldRIP, newRIP *spiderpoolv1.SpiderReservedIP) field.ErrorList {
-	if err := validateReservedIPShouldNotBeChanged(oldRIP, newRIP); err != nil {
+func (rw *ReservedIPWebhook) validateUpdateReservedIP(ctx context.Context, oldRIP, newRIP *spiderpoolv1.SpiderReservedIP) field.ErrorList {
+	var errs field.ErrorList
+	if err := rw.validateReservedIPSpec(ctx, newRIP); err != nil {
 		return field.ErrorList{err}
 	}
 
-	var errs field.ErrorList
-	if err := rm.validateReservedIPSpec(ctx, newRIP); err != nil {
+	if err := validateReservedIPShouldNotBeChanged(oldRIP, newRIP); err != nil {
 		errs = append(errs, err)
 	}
 
@@ -62,18 +62,15 @@ func validateReservedIPShouldNotBeChanged(oldRIP, newRIP *spiderpoolv1.SpiderRes
 	return nil
 }
 
-func (rm *reservedIPManager) validateReservedIPSpec(ctx context.Context, rIP *spiderpoolv1.SpiderReservedIP) *field.Error {
-	if err := rm.validateReservedIPIPVersion(rIP.Spec.IPVersion); err != nil {
-		return err
-	}
-	if err := rm.validateReservedIPAvailableIP(ctx, *rIP.Spec.IPVersion, rIP); err != nil {
+func (rw *ReservedIPWebhook) validateReservedIPSpec(ctx context.Context, rIP *spiderpoolv1.SpiderReservedIP) *field.Error {
+	if err := rw.validateReservedIPIPVersion(rIP.Spec.IPVersion); err != nil {
 		return err
 	}
 
-	return nil
+	return rw.validateReservedIPAvailableIP(ctx, *rIP.Spec.IPVersion, rIP)
 }
 
-func (rm *reservedIPManager) validateReservedIPIPVersion(version *types.IPVersion) *field.Error {
+func (rw *ReservedIPWebhook) validateReservedIPIPVersion(version *types.IPVersion) *field.Error {
 	if version == nil {
 		return field.Invalid(
 			ipVersionField,
@@ -86,20 +83,21 @@ func (rm *reservedIPManager) validateReservedIPIPVersion(version *types.IPVersio
 		return field.NotSupported(
 			ipVersionField,
 			version,
-			[]string{strconv.FormatInt(constant.IPv4, 10),
+			[]string{
+				strconv.FormatInt(constant.IPv4, 10),
 				strconv.FormatInt(constant.IPv6, 10),
 			},
 		)
 	}
 
-	if *version == constant.IPv4 && !rm.config.EnableIPv4 {
+	if *version == constant.IPv4 && !rw.EnableIPv4 {
 		return field.Forbidden(
 			ipVersionField,
 			"IPv4 is disabled",
 		)
 	}
 
-	if *version == constant.IPv6 && !rm.config.EnableIPv6 {
+	if *version == constant.IPv6 && !rw.EnableIPv6 {
 		return field.Forbidden(
 			ipVersionField,
 			"IPv6 is disabled",
@@ -109,19 +107,23 @@ func (rm *reservedIPManager) validateReservedIPIPVersion(version *types.IPVersio
 	return nil
 }
 
-func (rm *reservedIPManager) validateReservedIPAvailableIP(ctx context.Context, version types.IPVersion, rIP *spiderpoolv1.SpiderReservedIP) *field.Error {
-	if err := validateReservedIPIPs(version, rIP.Spec.IPs); err != nil {
-		return err
+func (rw *ReservedIPWebhook) validateReservedIPAvailableIP(ctx context.Context, version types.IPVersion, rIP *spiderpoolv1.SpiderReservedIP) *field.Error {
+	if len(rIP.Spec.IPs) == 0 {
+		return nil
 	}
 
-	rIPList, err := rm.ListReservedIPs(ctx)
+	newReservedIPs, err := spiderpoolip.ParseIPRanges(version, rIP.Spec.IPs)
 	if err != nil {
-		return field.InternalError(ipsField, err)
+		return field.Invalid(
+			ipsField,
+			rIP.Spec.IPs,
+			err.Error(),
+		)
 	}
 
-	newReservedIPs, err := spiderpoolip.ParseIPRanges(version, rIP.Spec.IPs)
+	rIPList, err := rw.ListReservedIPs(ctx)
 	if err != nil {
-		return field.InternalError(ipsField, err)
+		return field.InternalError(ipsField, fmt.Errorf("failed to list ReservedIPs: %v", err))
 	}
 
 	for _, r := range rIPList.Items {
@@ -131,26 +133,12 @@ func (rm *reservedIPManager) validateReservedIPAvailableIP(ctx context.Context,
 
 		existReservedIPs, err := spiderpoolip.ParseIPRanges(version, r.Spec.IPs)
 		if err != nil {
-			return field.InternalError(ipsField, err)
+			return field.InternalError(ipsField, fmt.Errorf("failed to parse 'spec.ips':\n%v\n of the existing ReservedIP %s: %v", r.Spec.IPs, r.Name, err))
 		}
-		if len(newReservedIPs) > len(spiderpoolip.IPsDiffSet(newReservedIPs, existReservedIPs)) {
+		if len(spiderpoolip.IPsIntersectionSet(newReservedIPs, existReservedIPs)) > 0 {
 			return field.Forbidden(
 				ipsField,
-				fmt.Sprintf("overlaps with ReservedIP %s", r.Name),
-			)
-		}
-	}
-
-	return nil
-}
-
-func validateReservedIPIPs(version types.IPVersion, ips []string) *field.Error {
-	for i, r := range ips {
-		if err := spiderpoolip.IsIPRange(version, r); err != nil {
-			return field.Invalid(
-				ipsField.Index(i),
-				ips[i],
-				err.Error(),
+				fmt.Sprintf("overlaps with the existing ReservedIP %s", r.Name),
 			)
 		}
 	}
diff --git a/pkg/reservedipmanager/reservedip_webhook.go b/pkg/reservedipmanager/reservedip_webhook.go
index 6f46f2c0f..fd77978e3 100644
--- a/pkg/reservedipmanager/reservedip_webhook.go
+++ b/pkg/reservedipmanager/reservedip_webhook.go
@@ -5,7 +5,6 @@ package reservedipmanager
 
 import (
 	"context"
-	"fmt"
 
 	"go.uber.org/zap"
 	apierrors "k8s.io/apimachinery/pkg/api/errors"
@@ -15,98 +14,64 @@ import (
 	"sigs.k8s.io/controller-runtime/pkg/webhook"
 
 	"github.com/spidernet-io/spiderpool/pkg/constant"
-	spiderpoolip "github.com/spidernet-io/spiderpool/pkg/ip"
 	spiderpoolv1 "github.com/spidernet-io/spiderpool/pkg/k8s/apis/spiderpool.spidernet.io/v1"
 	"github.com/spidernet-io/spiderpool/pkg/logutils"
-	"github.com/spidernet-io/spiderpool/pkg/types"
 )
 
-var webhookLogger *zap.Logger
+var WebhookLogger *zap.Logger
 
-func (rm *reservedIPManager) SetupWebhook() error {
-	if webhookLogger == nil {
-		webhookLogger = logutils.Logger.Named("ReservedIP-Webhook")
+type ReservedIPWebhook struct {
+	ReservedIPManager
+
+	EnableIPv4 bool
+	EnableIPv6 bool
+}
+
+func (rm *ReservedIPWebhook) SetupWebhookWithManager(mgr ctrl.Manager) error {
+	if WebhookLogger == nil {
+		WebhookLogger = logutils.Logger.Named("ReservedIP-Webhook")
 	}
 
-	return ctrl.NewWebhookManagedBy(rm.runtimeMgr).
+	return ctrl.NewWebhookManagedBy(mgr).
 		For(&spiderpoolv1.SpiderReservedIP{}).
 		WithDefaulter(rm).
 		WithValidator(rm).
 		Complete()
 }
 
-var _ webhook.CustomDefaulter = (*reservedIPManager)(nil)
+var _ webhook.CustomDefaulter = (*ReservedIPWebhook)(nil)
 
-// Default implements webhook.CustomDefaulter so a webhook will be registered for the type
-func (rm *reservedIPManager) Default(ctx context.Context, obj runtime.Object) error {
-	rIP, ok := obj.(*spiderpoolv1.SpiderReservedIP)
-	if !ok {
-		return apierrors.NewBadRequest(fmt.Sprintf("mutating webhook of ReservedIP got an object with mismatched GVK: %+v", obj.GetObjectKind().GroupVersionKind()))
-	}
+// Default implements webhook.CustomDefaulter so a webhook will be registered for the type.
+func (rw *ReservedIPWebhook) Default(ctx context.Context, obj runtime.Object) error {
+	rIP := obj.(*spiderpoolv1.SpiderReservedIP)
 
-	logger := webhookLogger.Named("Mutating").With(
+	logger := WebhookLogger.Named("Mutating").With(
 		zap.String("ReservedIPName", rIP.Name),
 		zap.String("Operation", "DEFAULT"),
 	)
-	logger.Info("Start to mutate ReservedIP")
 	logger.Sugar().Debugf("Request ReservedIP: %+v", *rIP)
 
-	if rIP.DeletionTimestamp != nil {
-		logger.Info("Deleting ReservedIP, noting to mutate")
-		return nil
-	}
-
-	if len(rIP.Spec.IPs) == 0 {
-		logger.Error("Empty 'spec.ips', noting to mutate")
-		return nil
-	}
-
-	if rIP.Spec.IPVersion == nil {
-		var version types.IPVersion
-		if spiderpoolip.IsIPv4IPRange(rIP.Spec.IPs[0]) {
-			version = constant.IPv4
-		} else if spiderpoolip.IsIPv6IPRange(rIP.Spec.IPs[0]) {
-			version = constant.IPv6
-		} else {
-			logger.Error("Invalid 'spec.ipVersion', noting to mutate")
-			return nil
-		}
-
-		rIP.Spec.IPVersion = new(types.IPVersion)
-		*rIP.Spec.IPVersion = version
-		logger.Sugar().Infof("Set 'spec.ipVersion' to %d", version)
-	}
-
-	if len(rIP.Spec.IPs) > 1 {
-		mergedIPs, err := spiderpoolip.MergeIPRanges(*rIP.Spec.IPVersion, rIP.Spec.IPs)
-		if err != nil {
-			logger.Sugar().Errorf("Failed to merge 'spec.ips': %v", err)
-		} else {
-			rIP.Spec.IPs = mergedIPs
-			logger.Sugar().Debugf("Merge 'spec.ips':\n%v\n\nto:\n\n%v", rIP.Spec.IPs, mergedIPs)
-		}
+	if err := rw.mutateReservedIP(logutils.IntoContext(ctx, logger), rIP); err != nil {
+		logger.Sugar().Errorf("Failed to mutate ReservedIP: %v", err)
 	}
 
 	return nil
 }
 
-var _ webhook.CustomValidator = (*reservedIPManager)(nil)
+var _ webhook.CustomValidator = (*ReservedIPWebhook)(nil)
 
-// ValidateCreate implements webhook.CustomValidator so a webhook will be registered for the type
-func (rm *reservedIPManager) ValidateCreate(ctx context.Context, obj runtime.Object) error {
-	rIP, ok := obj.(*spiderpoolv1.SpiderReservedIP)
-	if !ok {
-		return apierrors.NewBadRequest(fmt.Sprintf("validating webhook of ReservedIP got an object with mismatched GVK: %+v", obj.GetObjectKind().GroupVersionKind()))
-	}
+// ValidateCreate implements webhook.CustomValidator so a webhook will be registered for the type.
+func (rw *ReservedIPWebhook) ValidateCreate(ctx context.Context, obj runtime.Object) error {
+	rIP := obj.(*spiderpoolv1.SpiderReservedIP)
 
-	logger := webhookLogger.Named("Validating").With(
+	logger := WebhookLogger.Named("Validating").With(
 		zap.String("ReservedIPNamespace", rIP.Namespace),
 		zap.String("ReservedIPName", rIP.Name),
 		zap.String("Operation", "CREATE"),
 	)
 	logger.Sugar().Debugf("Request ReservedIP: %+v", *rIP)
 
-	if errs := rm.validateCreateReservedIP(logutils.IntoContext(ctx, logger), rIP); len(errs) != 0 {
+	if errs := rw.validateCreateReservedIP(logutils.IntoContext(ctx, logger), rIP); len(errs) != 0 {
 		logger.Sugar().Errorf("Failed to create ReservedIP: %v", errs.ToAggregate().Error())
 		return apierrors.NewInvalid(
 			schema.GroupKind{Group: constant.SpiderpoolAPIGroup, Kind: constant.SpiderReservedIPKind},
@@ -118,15 +83,12 @@ func (rm *reservedIPManager) ValidateCreate(ctx context.Context, obj runtime.Obj
 	return nil
 }
 
-// ValidateUpdate implements webhook.CustomValidator so a webhook will be registered for the type
-func (rm *reservedIPManager) ValidateUpdate(ctx context.Context, oldObj, newObj runtime.Object) error {
-	oldRIP, _ := oldObj.(*spiderpoolv1.SpiderReservedIP)
-	newRIP, ok := newObj.(*spiderpoolv1.SpiderReservedIP)
-	if !ok {
-		return apierrors.NewBadRequest(fmt.Sprintf("validating webhook of ReservedIP got an object with mismatched GVK: %+v", newObj.GetObjectKind().GroupVersionKind()))
-	}
+// ValidateUpdate implements webhook.CustomValidator so a webhook will be registered for the type.
+func (rw *ReservedIPWebhook) ValidateUpdate(ctx context.Context, oldObj, newObj runtime.Object) error {
+	oldRIP := oldObj.(*spiderpoolv1.SpiderReservedIP)
+	newRIP := newObj.(*spiderpoolv1.SpiderReservedIP)
 
-	logger := webhookLogger.Named("Validating").With(
+	logger := WebhookLogger.Named("Validating").With(
 		zap.String("ReservedIPNamespace", newRIP.Namespace),
 		zap.String("ReservedIPName", newRIP.Name),
 		zap.String("Operation", "UPDATE"),
@@ -134,7 +96,7 @@ func (rm *reservedIPManager) ValidateUpdate(ctx context.Context, oldObj, newObj
 	logger.Sugar().Debugf("Request old ReservedIP: %+v", *oldRIP)
 	logger.Sugar().Debugf("Request new ReservedIP: %+v", *newRIP)
 
-	if errs := rm.validateUpdateReservedIP(logutils.IntoContext(ctx, logger), oldRIP, newRIP); len(errs) != 0 {
+	if errs := rw.validateUpdateReservedIP(logutils.IntoContext(ctx, logger), oldRIP, newRIP); len(errs) != 0 {
 		logger.Sugar().Errorf("Failed to update ReservedIP: %v", errs.ToAggregate().Error())
 		return apierrors.NewInvalid(
 			schema.GroupKind{Group: constant.SpiderpoolAPIGroup, Kind: constant.SpiderReservedIPKind},
@@ -146,7 +108,7 @@ func (rm *reservedIPManager) ValidateUpdate(ctx context.Context, oldObj, newObj
 	return nil
 }
 
-// ValidateDelete implements webhook.CustomValidator so a webhook will be registered for the type
-func (rm *reservedIPManager) ValidateDelete(ctx context.Context, obj runtime.Object) error {
+// ValidateDelete implements webhook.CustomValidator so a webhook will be registered for the type.
+func (rw *ReservedIPWebhook) ValidateDelete(ctx context.Context, obj runtime.Object) error {
 	return nil
 }
diff --git a/pkg/reservedipmanager/utils.go b/pkg/reservedipmanager/utils.go
index f60fad31f..00243d09b 100644
--- a/pkg/reservedipmanager/utils.go
+++ b/pkg/reservedipmanager/utils.go
@@ -4,14 +4,24 @@
 package reservedipmanager
 
 import (
+	"fmt"
 	"net"
 
+	"github.com/spidernet-io/spiderpool/pkg/constant"
 	spiderpoolip "github.com/spidernet-io/spiderpool/pkg/ip"
 	spiderpoolv1 "github.com/spidernet-io/spiderpool/pkg/k8s/apis/spiderpool.spidernet.io/v1"
-	spiderpooltypes "github.com/spidernet-io/spiderpool/pkg/types"
+	"github.com/spidernet-io/spiderpool/pkg/types"
 )
 
-func GetReservedIPsByIPVersion(version spiderpooltypes.IPVersion, rIPList *spiderpoolv1.SpiderReservedIPList) ([]net.IP, error) {
+func AssembleReservedIPs(version types.IPVersion, rIPList *spiderpoolv1.SpiderReservedIPList) ([]net.IP, error) {
+	if err := spiderpoolip.IsIPVersion(version); err != nil {
+		return nil, err
+	}
+
+	if rIPList == nil {
+		return nil, fmt.Errorf("reserved IP list %w", constant.ErrMissingRequiredParam)
+	}
+
 	var ips []net.IP
 	for _, r := range rIPList.Items {
 		if *r.Spec.IPVersion != version {
diff --git a/pkg/subnetmanager/subnet_manager.go b/pkg/subnetmanager/subnet_manager.go
index b8d6d7e00..95952f548 100644
--- a/pkg/subnetmanager/subnet_manager.go
+++ b/pkg/subnetmanager/subnet_manager.go
@@ -161,7 +161,7 @@ func (sm *subnetManager) GenerateIPsFromSubnetWhenScaleUpIP(ctx context.Context,
 		return nil, fmt.Errorf("failed to list reservedIPs, error: %v", err)
 	}
 
-	reservedIPs, err := reservedipmanager.GetReservedIPsByIPVersion(ipVersion, reservedIPList)
+	reservedIPs, err := reservedipmanager.AssembleReservedIPs(ipVersion, reservedIPList)
 	if nil != err {
 		return nil, fmt.Errorf("%w: failed to filter reservedIPs '%v' by IP version '%d', error: %v",
 			constant.ErrWrongInput, reservedIPs, ipVersion, err)
diff --git a/vendor/github.com/golang/mock/AUTHORS b/vendor/github.com/golang/mock/AUTHORS
new file mode 100644
index 000000000..660b8ccc8
--- /dev/null
+++ b/vendor/github.com/golang/mock/AUTHORS
@@ -0,0 +1,12 @@
+# This is the official list of GoMock authors for copyright purposes.
+# This file is distinct from the CONTRIBUTORS files.
+# See the latter for an explanation.
+
+# Names should be added to this file as
+#	Name or Organization <email address>
+# The email address is not required for organizations.
+
+# Please keep the list sorted.
+
+Alex Reece <awreece@gmail.com>
+Google Inc.
diff --git a/vendor/github.com/golang/mock/CONTRIBUTORS b/vendor/github.com/golang/mock/CONTRIBUTORS
new file mode 100644
index 000000000..def849cab
--- /dev/null
+++ b/vendor/github.com/golang/mock/CONTRIBUTORS
@@ -0,0 +1,37 @@
+# This is the official list of people who can contribute (and typically
+# have contributed) code to the gomock repository.
+# The AUTHORS file lists the copyright holders; this file
+# lists people.  For example, Google employees are listed here
+# but not in AUTHORS, because Google holds the copyright.
+#
+# The submission process automatically checks to make sure
+# that people submitting code are listed in this file (by email address).
+#
+# Names should be added to this file only after verifying that
+# the individual or the individual's organization has agreed to
+# the appropriate Contributor License Agreement, found here:
+#
+#     http://code.google.com/legal/individual-cla-v1.0.html
+#     http://code.google.com/legal/corporate-cla-v1.0.html
+#
+# The agreement for individuals can be filled out on the web.
+#
+# When adding J Random Contributor's name to this file,
+# either J's name or J's organization's name should be
+# added to the AUTHORS file, depending on whether the
+# individual or corporate CLA was used.
+
+# Names should be added to this file like so:
+#     Name <email address>
+#
+# An entry with two email addresses specifies that the
+# first address should be used in the submit logs and
+# that the second address should be recognized as the
+# same person when interacting with Rietveld.
+
+# Please keep the list sorted.
+
+Aaron Jacobs <jacobsa@google.com> <aaronjjacobs@gmail.com>
+Alex Reece <awreece@gmail.com>
+David Symonds <dsymonds@golang.org>
+Ryan Barrett <ryanb@google.com>
diff --git a/vendor/github.com/golang/mock/LICENSE b/vendor/github.com/golang/mock/LICENSE
new file mode 100644
index 000000000..d64569567
--- /dev/null
+++ b/vendor/github.com/golang/mock/LICENSE
@@ -0,0 +1,202 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
diff --git a/vendor/github.com/golang/mock/gomock/call.go b/vendor/github.com/golang/mock/gomock/call.go
new file mode 100644
index 000000000..13c9f44b1
--- /dev/null
+++ b/vendor/github.com/golang/mock/gomock/call.go
@@ -0,0 +1,445 @@
+// Copyright 2010 Google Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package gomock
+
+import (
+	"fmt"
+	"reflect"
+	"strconv"
+	"strings"
+)
+
+// Call represents an expected call to a mock.
+type Call struct {
+	t TestHelper // for triggering test failures on invalid call setup
+
+	receiver   interface{}  // the receiver of the method call
+	method     string       // the name of the method
+	methodType reflect.Type // the type of the method
+	args       []Matcher    // the args
+	origin     string       // file and line number of call setup
+
+	preReqs []*Call // prerequisite calls
+
+	// Expectations
+	minCalls, maxCalls int
+
+	numCalls int // actual number made
+
+	// actions are called when this Call is called. Each action gets the args and
+	// can set the return values by returning a non-nil slice. Actions run in the
+	// order they are created.
+	actions []func([]interface{}) []interface{}
+}
+
+// newCall creates a *Call. It requires the method type in order to support
+// unexported methods.
+func newCall(t TestHelper, receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call {
+	t.Helper()
+
+	// TODO: check arity, types.
+	mArgs := make([]Matcher, len(args))
+	for i, arg := range args {
+		if m, ok := arg.(Matcher); ok {
+			mArgs[i] = m
+		} else if arg == nil {
+			// Handle nil specially so that passing a nil interface value
+			// will match the typed nils of concrete args.
+			mArgs[i] = Nil()
+		} else {
+			mArgs[i] = Eq(arg)
+		}
+	}
+
+	// callerInfo's skip should be updated if the number of calls between the user's test
+	// and this line changes, i.e. this code is wrapped in another anonymous function.
+	// 0 is us, 1 is RecordCallWithMethodType(), 2 is the generated recorder, and 3 is the user's test.
+	origin := callerInfo(3)
+	actions := []func([]interface{}) []interface{}{func([]interface{}) []interface{} {
+		// Synthesize the zero value for each of the return args' types.
+		rets := make([]interface{}, methodType.NumOut())
+		for i := 0; i < methodType.NumOut(); i++ {
+			rets[i] = reflect.Zero(methodType.Out(i)).Interface()
+		}
+		return rets
+	}}
+	return &Call{t: t, receiver: receiver, method: method, methodType: methodType,
+		args: mArgs, origin: origin, minCalls: 1, maxCalls: 1, actions: actions}
+}
+
+// AnyTimes allows the expectation to be called 0 or more times
+func (c *Call) AnyTimes() *Call {
+	c.minCalls, c.maxCalls = 0, 1e8 // close enough to infinity
+	return c
+}
+
+// MinTimes requires the call to occur at least n times. If AnyTimes or MaxTimes have not been called or if MaxTimes
+// was previously called with 1, MinTimes also sets the maximum number of calls to infinity.
+func (c *Call) MinTimes(n int) *Call {
+	c.minCalls = n
+	if c.maxCalls == 1 {
+		c.maxCalls = 1e8
+	}
+	return c
+}
+
+// MaxTimes limits the number of calls to n times. If AnyTimes or MinTimes have not been called or if MinTimes was
+// previously called with 1, MaxTimes also sets the minimum number of calls to 0.
+func (c *Call) MaxTimes(n int) *Call {
+	c.maxCalls = n
+	if c.minCalls == 1 {
+		c.minCalls = 0
+	}
+	return c
+}
+
+// DoAndReturn declares the action to run when the call is matched.
+// The return values from this function are returned by the mocked function.
+// It takes an interface{} argument to support n-arity functions.
+func (c *Call) DoAndReturn(f interface{}) *Call {
+	// TODO: Check arity and types here, rather than dying badly elsewhere.
+	v := reflect.ValueOf(f)
+
+	c.addAction(func(args []interface{}) []interface{} {
+		c.t.Helper()
+		vArgs := make([]reflect.Value, len(args))
+		ft := v.Type()
+		if c.methodType.NumIn() != ft.NumIn() {
+			c.t.Fatalf("wrong number of arguments in DoAndReturn func for %T.%v: got %d, want %d [%s]",
+				c.receiver, c.method, ft.NumIn(), c.methodType.NumIn(), c.origin)
+			return nil
+		}
+		for i := 0; i < len(args); i++ {
+			if args[i] != nil {
+				vArgs[i] = reflect.ValueOf(args[i])
+			} else {
+				// Use the zero value for the arg.
+				vArgs[i] = reflect.Zero(ft.In(i))
+			}
+		}
+		vRets := v.Call(vArgs)
+		rets := make([]interface{}, len(vRets))
+		for i, ret := range vRets {
+			rets[i] = ret.Interface()
+		}
+		return rets
+	})
+	return c
+}
+
+// Do declares the action to run when the call is matched. The function's
+// return values are ignored to retain backward compatibility. To use the
+// return values call DoAndReturn.
+// It takes an interface{} argument to support n-arity functions.
+func (c *Call) Do(f interface{}) *Call {
+	// TODO: Check arity and types here, rather than dying badly elsewhere.
+	v := reflect.ValueOf(f)
+
+	c.addAction(func(args []interface{}) []interface{} {
+		c.t.Helper()
+		if c.methodType.NumIn() != v.Type().NumIn() {
+			c.t.Fatalf("wrong number of arguments in Do func for %T.%v: got %d, want %d [%s]",
+				c.receiver, c.method, v.Type().NumIn(), c.methodType.NumIn(), c.origin)
+			return nil
+		}
+		vArgs := make([]reflect.Value, len(args))
+		ft := v.Type()
+		for i := 0; i < len(args); i++ {
+			if args[i] != nil {
+				vArgs[i] = reflect.ValueOf(args[i])
+			} else {
+				// Use the zero value for the arg.
+				vArgs[i] = reflect.Zero(ft.In(i))
+			}
+		}
+		v.Call(vArgs)
+		return nil
+	})
+	return c
+}
+
+// Return declares the values to be returned by the mocked function call.
+func (c *Call) Return(rets ...interface{}) *Call {
+	c.t.Helper()
+
+	mt := c.methodType
+	if len(rets) != mt.NumOut() {
+		c.t.Fatalf("wrong number of arguments to Return for %T.%v: got %d, want %d [%s]",
+			c.receiver, c.method, len(rets), mt.NumOut(), c.origin)
+	}
+	for i, ret := range rets {
+		if got, want := reflect.TypeOf(ret), mt.Out(i); got == want {
+			// Identical types; nothing to do.
+		} else if got == nil {
+			// Nil needs special handling.
+			switch want.Kind() {
+			case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
+				// ok
+			default:
+				c.t.Fatalf("argument %d to Return for %T.%v is nil, but %v is not nillable [%s]",
+					i, c.receiver, c.method, want, c.origin)
+			}
+		} else if got.AssignableTo(want) {
+			// Assignable type relation. Make the assignment now so that the generated code
+			// can return the values with a type assertion.
+			v := reflect.New(want).Elem()
+			v.Set(reflect.ValueOf(ret))
+			rets[i] = v.Interface()
+		} else {
+			c.t.Fatalf("wrong type of argument %d to Return for %T.%v: %v is not assignable to %v [%s]",
+				i, c.receiver, c.method, got, want, c.origin)
+		}
+	}
+
+	c.addAction(func([]interface{}) []interface{} {
+		return rets
+	})
+
+	return c
+}
+
+// Times declares the exact number of times a function call is expected to be executed.
+func (c *Call) Times(n int) *Call {
+	c.minCalls, c.maxCalls = n, n
+	return c
+}
+
+// SetArg declares an action that will set the nth argument's value,
+// indirected through a pointer. Or, in the case of a slice, SetArg
+// will copy value's elements into the nth argument.
+func (c *Call) SetArg(n int, value interface{}) *Call {
+	c.t.Helper()
+
+	mt := c.methodType
+	// TODO: This will break on variadic methods.
+	// We will need to check those at invocation time.
+	if n < 0 || n >= mt.NumIn() {
+		c.t.Fatalf("SetArg(%d, ...) called for a method with %d args [%s]",
+			n, mt.NumIn(), c.origin)
+	}
+	// Permit setting argument through an interface.
+	// In the interface case, we don't (nay, can't) check the type here.
+	at := mt.In(n)
+	switch at.Kind() {
+	case reflect.Ptr:
+		dt := at.Elem()
+		if vt := reflect.TypeOf(value); !vt.AssignableTo(dt) {
+			c.t.Fatalf("SetArg(%d, ...) argument is a %v, not assignable to %v [%s]",
+				n, vt, dt, c.origin)
+		}
+	case reflect.Interface:
+		// nothing to do
+	case reflect.Slice:
+		// nothing to do
+	default:
+		c.t.Fatalf("SetArg(%d, ...) referring to argument of non-pointer non-interface non-slice type %v [%s]",
+			n, at, c.origin)
+	}
+
+	c.addAction(func(args []interface{}) []interface{} {
+		v := reflect.ValueOf(value)
+		switch reflect.TypeOf(args[n]).Kind() {
+		case reflect.Slice:
+			setSlice(args[n], v)
+		default:
+			reflect.ValueOf(args[n]).Elem().Set(v)
+		}
+		return nil
+	})
+	return c
+}
+
+// isPreReq returns true if other is a direct or indirect prerequisite to c.
+func (c *Call) isPreReq(other *Call) bool {
+	for _, preReq := range c.preReqs {
+		if other == preReq || preReq.isPreReq(other) {
+			return true
+		}
+	}
+	return false
+}
+
+// After declares that the call may only match after preReq has been exhausted.
+func (c *Call) After(preReq *Call) *Call {
+	c.t.Helper()
+
+	if c == preReq {
+		c.t.Fatalf("A call isn't allowed to be its own prerequisite")
+	}
+	if preReq.isPreReq(c) {
+		c.t.Fatalf("Loop in call order: %v is a prerequisite to %v (possibly indirectly).", c, preReq)
+	}
+
+	c.preReqs = append(c.preReqs, preReq)
+	return c
+}
+
+// Returns true if the minimum number of calls have been made.
+func (c *Call) satisfied() bool {
+	return c.numCalls >= c.minCalls
+}
+
+// Returns true if the maximum number of calls have been made.
+func (c *Call) exhausted() bool {
+	return c.numCalls >= c.maxCalls
+}
+
+func (c *Call) String() string {
+	args := make([]string, len(c.args))
+	for i, arg := range c.args {
+		args[i] = arg.String()
+	}
+	arguments := strings.Join(args, ", ")
+	return fmt.Sprintf("%T.%v(%s) %s", c.receiver, c.method, arguments, c.origin)
+}
+
+// Tests if the given call matches the expected call.
+// If yes, returns nil. If no, returns error with message explaining why it does not match.
+func (c *Call) matches(args []interface{}) error {
+	if !c.methodType.IsVariadic() {
+		if len(args) != len(c.args) {
+			return fmt.Errorf("expected call at %s has the wrong number of arguments. Got: %d, want: %d",
+				c.origin, len(args), len(c.args))
+		}
+
+		for i, m := range c.args {
+			if !m.Matches(args[i]) {
+				return fmt.Errorf(
+					"expected call at %s doesn't match the argument at index %d.\nGot: %v\nWant: %v",
+					c.origin, i, formatGottenArg(m, args[i]), m,
+				)
+			}
+		}
+	} else {
+		if len(c.args) < c.methodType.NumIn()-1 {
+			return fmt.Errorf("expected call at %s has the wrong number of matchers. Got: %d, want: %d",
+				c.origin, len(c.args), c.methodType.NumIn()-1)
+		}
+		if len(c.args) != c.methodType.NumIn() && len(args) != len(c.args) {
+			return fmt.Errorf("expected call at %s has the wrong number of arguments. Got: %d, want: %d",
+				c.origin, len(args), len(c.args))
+		}
+		if len(args) < len(c.args)-1 {
+			return fmt.Errorf("expected call at %s has the wrong number of arguments. Got: %d, want: greater than or equal to %d",
+				c.origin, len(args), len(c.args)-1)
+		}
+
+		for i, m := range c.args {
+			if i < c.methodType.NumIn()-1 {
+				// Non-variadic args
+				if !m.Matches(args[i]) {
+					return fmt.Errorf("expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
+						c.origin, strconv.Itoa(i), formatGottenArg(m, args[i]), m)
+				}
+				continue
+			}
+			// The last arg has a possibility of a variadic argument, so let it branch
+
+			// sample: Foo(a int, b int, c ...int)
+			if i < len(c.args) && i < len(args) {
+				if m.Matches(args[i]) {
+					// Got Foo(a, b, c) want Foo(matcherA, matcherB, gomock.Any())
+					// Got Foo(a, b, c) want Foo(matcherA, matcherB, someSliceMatcher)
+					// Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC)
+					// Got Foo(a, b) want Foo(matcherA, matcherB)
+					// Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD)
+					continue
+				}
+			}
+
+			// The number of actual args don't match the number of matchers,
+			// or the last matcher is a slice and the last arg is not.
+			// If this function still matches it is because the last matcher
+			// matches all the remaining arguments or the lack of any.
+			// Convert the remaining arguments, if any, into a slice of the
+			// expected type.
+			vArgsType := c.methodType.In(c.methodType.NumIn() - 1)
+			vArgs := reflect.MakeSlice(vArgsType, 0, len(args)-i)
+			for _, arg := range args[i:] {
+				vArgs = reflect.Append(vArgs, reflect.ValueOf(arg))
+			}
+			if m.Matches(vArgs.Interface()) {
+				// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, gomock.Any())
+				// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, someSliceMatcher)
+				// Got Foo(a, b) want Foo(matcherA, matcherB, gomock.Any())
+				// Got Foo(a, b) want Foo(matcherA, matcherB, someEmptySliceMatcher)
+				break
+			}
+			// Wrong number of matchers or not match. Fail.
+			// Got Foo(a, b) want Foo(matcherA, matcherB, matcherC, matcherD)
+			// Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC, matcherD)
+			// Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD, matcherE)
+			// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, matcherC, matcherD)
+			// Got Foo(a, b, c) want Foo(matcherA, matcherB)
+
+			return fmt.Errorf("expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
+				c.origin, strconv.Itoa(i), formatGottenArg(m, args[i:]), c.args[i])
+		}
+	}
+
+	// Check that all prerequisite calls have been satisfied.
+	for _, preReqCall := range c.preReqs {
+		if !preReqCall.satisfied() {
+			return fmt.Errorf("expected call at %s doesn't have a prerequisite call satisfied:\n%v\nshould be called before:\n%v",
+				c.origin, preReqCall, c)
+		}
+	}
+
+	// Check that the call is not exhausted.
+	if c.exhausted() {
+		return fmt.Errorf("expected call at %s has already been called the max number of times", c.origin)
+	}
+
+	return nil
+}
+
+// dropPrereqs tells the expected Call to not re-check prerequisite calls any
+// longer, and to return its current set.
+func (c *Call) dropPrereqs() (preReqs []*Call) {
+	preReqs = c.preReqs
+	c.preReqs = nil
+	return
+}
+
+func (c *Call) call() []func([]interface{}) []interface{} {
+	c.numCalls++
+	return c.actions
+}
+
+// InOrder declares that the given calls should occur in order.
+func InOrder(calls ...*Call) {
+	for i := 1; i < len(calls); i++ {
+		calls[i].After(calls[i-1])
+	}
+}
+
+func setSlice(arg interface{}, v reflect.Value) {
+	va := reflect.ValueOf(arg)
+	for i := 0; i < v.Len(); i++ {
+		va.Index(i).Set(v.Index(i))
+	}
+}
+
+func (c *Call) addAction(action func([]interface{}) []interface{}) {
+	c.actions = append(c.actions, action)
+}
+
+func formatGottenArg(m Matcher, arg interface{}) string {
+	got := fmt.Sprintf("%v (%T)", arg, arg)
+	if gs, ok := m.(GotFormatter); ok {
+		got = gs.Got(arg)
+	}
+	return got
+}
diff --git a/vendor/github.com/golang/mock/gomock/callset.go b/vendor/github.com/golang/mock/gomock/callset.go
new file mode 100644
index 000000000..49dba787a
--- /dev/null
+++ b/vendor/github.com/golang/mock/gomock/callset.go
@@ -0,0 +1,113 @@
+// Copyright 2011 Google Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package gomock
+
+import (
+	"bytes"
+	"errors"
+	"fmt"
+)
+
+// callSet represents a set of expected calls, indexed by receiver and method
+// name.
+type callSet struct {
+	// Calls that are still expected.
+	expected map[callSetKey][]*Call
+	// Calls that have been exhausted.
+	exhausted map[callSetKey][]*Call
+}
+
+// callSetKey is the key in the maps in callSet
+type callSetKey struct {
+	receiver interface{}
+	fname    string
+}
+
+func newCallSet() *callSet {
+	return &callSet{make(map[callSetKey][]*Call), make(map[callSetKey][]*Call)}
+}
+
+// Add adds a new expected call.
+func (cs callSet) Add(call *Call) {
+	key := callSetKey{call.receiver, call.method}
+	m := cs.expected
+	if call.exhausted() {
+		m = cs.exhausted
+	}
+	m[key] = append(m[key], call)
+}
+
+// Remove removes an expected call.
+func (cs callSet) Remove(call *Call) {
+	key := callSetKey{call.receiver, call.method}
+	calls := cs.expected[key]
+	for i, c := range calls {
+		if c == call {
+			// maintain order for remaining calls
+			cs.expected[key] = append(calls[:i], calls[i+1:]...)
+			cs.exhausted[key] = append(cs.exhausted[key], call)
+			break
+		}
+	}
+}
+
+// FindMatch searches for a matching call. Returns error with explanation message if no call matched.
+func (cs callSet) FindMatch(receiver interface{}, method string, args []interface{}) (*Call, error) {
+	key := callSetKey{receiver, method}
+
+	// Search through the expected calls.
+	expected := cs.expected[key]
+	var callsErrors bytes.Buffer
+	for _, call := range expected {
+		err := call.matches(args)
+		if err != nil {
+			_, _ = fmt.Fprintf(&callsErrors, "\n%v", err)
+		} else {
+			return call, nil
+		}
+	}
+
+	// If we haven't found a match then search through the exhausted calls so we
+	// get useful error messages.
+	exhausted := cs.exhausted[key]
+	for _, call := range exhausted {
+		if err := call.matches(args); err != nil {
+			_, _ = fmt.Fprintf(&callsErrors, "\n%v", err)
+			continue
+		}
+		_, _ = fmt.Fprintf(
+			&callsErrors, "all expected calls for method %q have been exhausted", method,
+		)
+	}
+
+	if len(expected)+len(exhausted) == 0 {
+		_, _ = fmt.Fprintf(&callsErrors, "there are no expected calls of the method %q for that receiver", method)
+	}
+
+	return nil, errors.New(callsErrors.String())
+}
+
+// Failures returns the calls that are not satisfied.
+func (cs callSet) Failures() []*Call {
+	failures := make([]*Call, 0, len(cs.expected))
+	for _, calls := range cs.expected {
+		for _, call := range calls {
+			if !call.satisfied() {
+				failures = append(failures, call)
+			}
+		}
+	}
+	return failures
+}
diff --git a/vendor/github.com/golang/mock/gomock/controller.go b/vendor/github.com/golang/mock/gomock/controller.go
new file mode 100644
index 000000000..f054200d5
--- /dev/null
+++ b/vendor/github.com/golang/mock/gomock/controller.go
@@ -0,0 +1,336 @@
+// Copyright 2010 Google Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package gomock is a mock framework for Go.
+//
+// Standard usage:
+//   (1) Define an interface that you wish to mock.
+//         type MyInterface interface {
+//           SomeMethod(x int64, y string)
+//         }
+//   (2) Use mockgen to generate a mock from the interface.
+//   (3) Use the mock in a test:
+//         func TestMyThing(t *testing.T) {
+//           mockCtrl := gomock.NewController(t)
+//           defer mockCtrl.Finish()
+//
+//           mockObj := something.NewMockMyInterface(mockCtrl)
+//           mockObj.EXPECT().SomeMethod(4, "blah")
+//           // pass mockObj to a real object and play with it.
+//         }
+//
+// By default, expected calls are not enforced to run in any particular order.
+// Call order dependency can be enforced by use of InOrder and/or Call.After.
+// Call.After can create more varied call order dependencies, but InOrder is
+// often more convenient.
+//
+// The following examples create equivalent call order dependencies.
+//
+// Example of using Call.After to chain expected call order:
+//
+//     firstCall := mockObj.EXPECT().SomeMethod(1, "first")
+//     secondCall := mockObj.EXPECT().SomeMethod(2, "second").After(firstCall)
+//     mockObj.EXPECT().SomeMethod(3, "third").After(secondCall)
+//
+// Example of using InOrder to declare expected call order:
+//
+//     gomock.InOrder(
+//         mockObj.EXPECT().SomeMethod(1, "first"),
+//         mockObj.EXPECT().SomeMethod(2, "second"),
+//         mockObj.EXPECT().SomeMethod(3, "third"),
+//     )
+package gomock
+
+import (
+	"context"
+	"fmt"
+	"reflect"
+	"runtime"
+	"sync"
+)
+
+// A TestReporter is something that can be used to report test failures.  It
+// is satisfied by the standard library's *testing.T.
+type TestReporter interface {
+	Errorf(format string, args ...interface{})
+	Fatalf(format string, args ...interface{})
+}
+
+// TestHelper is a TestReporter that has the Helper method.  It is satisfied
+// by the standard library's *testing.T.
+type TestHelper interface {
+	TestReporter
+	Helper()
+}
+
+// cleanuper is used to check if TestHelper also has the `Cleanup` method. A
+// common pattern is to pass in a `*testing.T` to
+// `NewController(t TestReporter)`. In Go 1.14+, `*testing.T` has a cleanup
+// method. This can be utilized to call `Finish()` so the caller of this library
+// does not have to.
+type cleanuper interface {
+	Cleanup(func())
+}
+
+// A Controller represents the top-level control of a mock ecosystem.  It
+// defines the scope and lifetime of mock objects, as well as their
+// expectations.  It is safe to call Controller's methods from multiple
+// goroutines. Each test should create a new Controller and invoke Finish via
+// defer.
+//
+//   func TestFoo(t *testing.T) {
+//     ctrl := gomock.NewController(t)
+//     defer ctrl.Finish()
+//     // ..
+//   }
+//
+//   func TestBar(t *testing.T) {
+//     t.Run("Sub-Test-1", st) {
+//       ctrl := gomock.NewController(st)
+//       defer ctrl.Finish()
+//       // ..
+//     })
+//     t.Run("Sub-Test-2", st) {
+//       ctrl := gomock.NewController(st)
+//       defer ctrl.Finish()
+//       // ..
+//     })
+//   })
+type Controller struct {
+	// T should only be called within a generated mock. It is not intended to
+	// be used in user code and may be changed in future versions. T is the
+	// TestReporter passed in when creating the Controller via NewController.
+	// If the TestReporter does not implement a TestHelper it will be wrapped
+	// with a nopTestHelper.
+	T             TestHelper
+	mu            sync.Mutex
+	expectedCalls *callSet
+	finished      bool
+}
+
+// NewController returns a new Controller. It is the preferred way to create a
+// Controller.
+//
+// New in go1.14+, if you are passing a *testing.T into this function you no
+// longer need to call ctrl.Finish() in your test methods.
+func NewController(t TestReporter) *Controller {
+	h, ok := t.(TestHelper)
+	if !ok {
+		h = &nopTestHelper{t}
+	}
+	ctrl := &Controller{
+		T:             h,
+		expectedCalls: newCallSet(),
+	}
+	if c, ok := isCleanuper(ctrl.T); ok {
+		c.Cleanup(func() {
+			ctrl.T.Helper()
+			ctrl.finish(true, nil)
+		})
+	}
+
+	return ctrl
+}
+
+type cancelReporter struct {
+	t      TestHelper
+	cancel func()
+}
+
+func (r *cancelReporter) Errorf(format string, args ...interface{}) {
+	r.t.Errorf(format, args...)
+}
+func (r *cancelReporter) Fatalf(format string, args ...interface{}) {
+	defer r.cancel()
+	r.t.Fatalf(format, args...)
+}
+
+func (r *cancelReporter) Helper() {
+	r.t.Helper()
+}
+
+// WithContext returns a new Controller and a Context, which is cancelled on any
+// fatal failure.
+func WithContext(ctx context.Context, t TestReporter) (*Controller, context.Context) {
+	h, ok := t.(TestHelper)
+	if !ok {
+		h = &nopTestHelper{t: t}
+	}
+
+	ctx, cancel := context.WithCancel(ctx)
+	return NewController(&cancelReporter{t: h, cancel: cancel}), ctx
+}
+
+type nopTestHelper struct {
+	t TestReporter
+}
+
+func (h *nopTestHelper) Errorf(format string, args ...interface{}) {
+	h.t.Errorf(format, args...)
+}
+func (h *nopTestHelper) Fatalf(format string, args ...interface{}) {
+	h.t.Fatalf(format, args...)
+}
+
+func (h nopTestHelper) Helper() {}
+
+// RecordCall is called by a mock. It should not be called by user code.
+func (ctrl *Controller) RecordCall(receiver interface{}, method string, args ...interface{}) *Call {
+	ctrl.T.Helper()
+
+	recv := reflect.ValueOf(receiver)
+	for i := 0; i < recv.Type().NumMethod(); i++ {
+		if recv.Type().Method(i).Name == method {
+			return ctrl.RecordCallWithMethodType(receiver, method, recv.Method(i).Type(), args...)
+		}
+	}
+	ctrl.T.Fatalf("gomock: failed finding method %s on %T", method, receiver)
+	panic("unreachable")
+}
+
+// RecordCallWithMethodType is called by a mock. It should not be called by user code.
+func (ctrl *Controller) RecordCallWithMethodType(receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call {
+	ctrl.T.Helper()
+
+	call := newCall(ctrl.T, receiver, method, methodType, args...)
+
+	ctrl.mu.Lock()
+	defer ctrl.mu.Unlock()
+	ctrl.expectedCalls.Add(call)
+
+	return call
+}
+
+// Call is called by a mock. It should not be called by user code.
+func (ctrl *Controller) Call(receiver interface{}, method string, args ...interface{}) []interface{} {
+	ctrl.T.Helper()
+
+	// Nest this code so we can use defer to make sure the lock is released.
+	actions := func() []func([]interface{}) []interface{} {
+		ctrl.T.Helper()
+		ctrl.mu.Lock()
+		defer ctrl.mu.Unlock()
+
+		expected, err := ctrl.expectedCalls.FindMatch(receiver, method, args)
+		if err != nil {
+			// callerInfo's skip should be updated if the number of calls between the user's test
+			// and this line changes, i.e. this code is wrapped in another anonymous function.
+			// 0 is us, 1 is controller.Call(), 2 is the generated mock, and 3 is the user's test.
+			origin := callerInfo(3)
+			ctrl.T.Fatalf("Unexpected call to %T.%v(%v) at %s because: %s", receiver, method, args, origin, err)
+		}
+
+		// Two things happen here:
+		// * the matching call no longer needs to check prerequite calls,
+		// * and the prerequite calls are no longer expected, so remove them.
+		preReqCalls := expected.dropPrereqs()
+		for _, preReqCall := range preReqCalls {
+			ctrl.expectedCalls.Remove(preReqCall)
+		}
+
+		actions := expected.call()
+		if expected.exhausted() {
+			ctrl.expectedCalls.Remove(expected)
+		}
+		return actions
+	}()
+
+	var rets []interface{}
+	for _, action := range actions {
+		if r := action(args); r != nil {
+			rets = r
+		}
+	}
+
+	return rets
+}
+
+// Finish checks to see if all the methods that were expected to be called
+// were called. It should be invoked for each Controller. It is not idempotent
+// and therefore can only be invoked once.
+//
+// New in go1.14+, if you are passing a *testing.T into NewController function you no
+// longer need to call ctrl.Finish() in your test methods.
+func (ctrl *Controller) Finish() {
+	// If we're currently panicking, probably because this is a deferred call.
+	// This must be recovered in the deferred function.
+	err := recover()
+	ctrl.finish(false, err)
+}
+
+func (ctrl *Controller) finish(cleanup bool, panicErr interface{}) {
+	ctrl.T.Helper()
+
+	ctrl.mu.Lock()
+	defer ctrl.mu.Unlock()
+
+	if ctrl.finished {
+		if _, ok := isCleanuper(ctrl.T); !ok {
+			ctrl.T.Fatalf("Controller.Finish was called more than once. It has to be called exactly once.")
+		}
+		return
+	}
+	ctrl.finished = true
+
+	// Short-circuit, pass through the panic.
+	if panicErr != nil {
+		panic(panicErr)
+	}
+
+	// Check that all remaining expected calls are satisfied.
+	failures := ctrl.expectedCalls.Failures()
+	for _, call := range failures {
+		ctrl.T.Errorf("missing call(s) to %v", call)
+	}
+	if len(failures) != 0 {
+		if !cleanup {
+			ctrl.T.Fatalf("aborting test due to missing call(s)")
+			return
+		}
+		ctrl.T.Errorf("aborting test due to missing call(s)")
+	}
+}
+
+// callerInfo returns the file:line of the call site. skip is the number
+// of stack frames to skip when reporting. 0 is callerInfo's call site.
+func callerInfo(skip int) string {
+	if _, file, line, ok := runtime.Caller(skip + 1); ok {
+		return fmt.Sprintf("%s:%d", file, line)
+	}
+	return "unknown file"
+}
+
+// isCleanuper checks it if t's base TestReporter has a Cleanup method.
+func isCleanuper(t TestReporter) (cleanuper, bool) {
+	tr := unwrapTestReporter(t)
+	c, ok := tr.(cleanuper)
+	return c, ok
+}
+
+// unwrapTestReporter unwraps TestReporter to the base implementation.
+func unwrapTestReporter(t TestReporter) TestReporter {
+	tr := t
+	switch nt := t.(type) {
+	case *cancelReporter:
+		tr = nt.t
+		if h, check := tr.(*nopTestHelper); check {
+			tr = h.t
+		}
+	case *nopTestHelper:
+		tr = nt.t
+	default:
+		// not wrapped
+	}
+	return tr
+}
diff --git a/vendor/github.com/golang/mock/gomock/matchers.go b/vendor/github.com/golang/mock/gomock/matchers.go
new file mode 100644
index 000000000..2822fb2c8
--- /dev/null
+++ b/vendor/github.com/golang/mock/gomock/matchers.go
@@ -0,0 +1,341 @@
+// Copyright 2010 Google Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package gomock
+
+import (
+	"fmt"
+	"reflect"
+	"strings"
+)
+
+// A Matcher is a representation of a class of values.
+// It is used to represent the valid or expected arguments to a mocked method.
+type Matcher interface {
+	// Matches returns whether x is a match.
+	Matches(x interface{}) bool
+
+	// String describes what the matcher matches.
+	String() string
+}
+
+// WantFormatter modifies the given Matcher's String() method to the given
+// Stringer. This allows for control on how the "Want" is formatted when
+// printing .
+func WantFormatter(s fmt.Stringer, m Matcher) Matcher {
+	type matcher interface {
+		Matches(x interface{}) bool
+	}
+
+	return struct {
+		matcher
+		fmt.Stringer
+	}{
+		matcher:  m,
+		Stringer: s,
+	}
+}
+
+// StringerFunc type is an adapter to allow the use of ordinary functions as
+// a Stringer. If f is a function with the appropriate signature,
+// StringerFunc(f) is a Stringer that calls f.
+type StringerFunc func() string
+
+// String implements fmt.Stringer.
+func (f StringerFunc) String() string {
+	return f()
+}
+
+// GotFormatter is used to better print failure messages. If a matcher
+// implements GotFormatter, it will use the result from Got when printing
+// the failure message.
+type GotFormatter interface {
+	// Got is invoked with the received value. The result is used when
+	// printing the failure message.
+	Got(got interface{}) string
+}
+
+// GotFormatterFunc type is an adapter to allow the use of ordinary
+// functions as a GotFormatter. If f is a function with the appropriate
+// signature, GotFormatterFunc(f) is a GotFormatter that calls f.
+type GotFormatterFunc func(got interface{}) string
+
+// Got implements GotFormatter.
+func (f GotFormatterFunc) Got(got interface{}) string {
+	return f(got)
+}
+
+// GotFormatterAdapter attaches a GotFormatter to a Matcher.
+func GotFormatterAdapter(s GotFormatter, m Matcher) Matcher {
+	return struct {
+		GotFormatter
+		Matcher
+	}{
+		GotFormatter: s,
+		Matcher:      m,
+	}
+}
+
+type anyMatcher struct{}
+
+func (anyMatcher) Matches(interface{}) bool {
+	return true
+}
+
+func (anyMatcher) String() string {
+	return "is anything"
+}
+
+type eqMatcher struct {
+	x interface{}
+}
+
+func (e eqMatcher) Matches(x interface{}) bool {
+	// In case, some value is nil
+	if e.x == nil || x == nil {
+		return reflect.DeepEqual(e.x, x)
+	}
+
+	// Check if types assignable and convert them to common type
+	x1Val := reflect.ValueOf(e.x)
+	x2Val := reflect.ValueOf(x)
+
+	if x1Val.Type().AssignableTo(x2Val.Type()) {
+		x1ValConverted := x1Val.Convert(x2Val.Type())
+		return reflect.DeepEqual(x1ValConverted.Interface(), x2Val.Interface())
+	}
+
+	return false
+}
+
+func (e eqMatcher) String() string {
+	return fmt.Sprintf("is equal to %v (%T)", e.x, e.x)
+}
+
+type nilMatcher struct{}
+
+func (nilMatcher) Matches(x interface{}) bool {
+	if x == nil {
+		return true
+	}
+
+	v := reflect.ValueOf(x)
+	switch v.Kind() {
+	case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map,
+		reflect.Ptr, reflect.Slice:
+		return v.IsNil()
+	}
+
+	return false
+}
+
+func (nilMatcher) String() string {
+	return "is nil"
+}
+
+type notMatcher struct {
+	m Matcher
+}
+
+func (n notMatcher) Matches(x interface{}) bool {
+	return !n.m.Matches(x)
+}
+
+func (n notMatcher) String() string {
+	return "not(" + n.m.String() + ")"
+}
+
+type assignableToTypeOfMatcher struct {
+	targetType reflect.Type
+}
+
+func (m assignableToTypeOfMatcher) Matches(x interface{}) bool {
+	return reflect.TypeOf(x).AssignableTo(m.targetType)
+}
+
+func (m assignableToTypeOfMatcher) String() string {
+	return "is assignable to " + m.targetType.Name()
+}
+
+type allMatcher struct {
+	matchers []Matcher
+}
+
+func (am allMatcher) Matches(x interface{}) bool {
+	for _, m := range am.matchers {
+		if !m.Matches(x) {
+			return false
+		}
+	}
+	return true
+}
+
+func (am allMatcher) String() string {
+	ss := make([]string, 0, len(am.matchers))
+	for _, matcher := range am.matchers {
+		ss = append(ss, matcher.String())
+	}
+	return strings.Join(ss, "; ")
+}
+
+type lenMatcher struct {
+	i int
+}
+
+func (m lenMatcher) Matches(x interface{}) bool {
+	v := reflect.ValueOf(x)
+	switch v.Kind() {
+	case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String:
+		return v.Len() == m.i
+	default:
+		return false
+	}
+}
+
+func (m lenMatcher) String() string {
+	return fmt.Sprintf("has length %d", m.i)
+}
+
+type inAnyOrderMatcher struct {
+	x interface{}
+}
+
+func (m inAnyOrderMatcher) Matches(x interface{}) bool {
+	given, ok := m.prepareValue(x)
+	if !ok {
+		return false
+	}
+	wanted, ok := m.prepareValue(m.x)
+	if !ok {
+		return false
+	}
+
+	if given.Len() != wanted.Len() {
+		return false
+	}
+
+	usedFromGiven := make([]bool, given.Len())
+	foundFromWanted := make([]bool, wanted.Len())
+	for i := 0; i < wanted.Len(); i++ {
+		wantedMatcher := Eq(wanted.Index(i).Interface())
+		for j := 0; j < given.Len(); j++ {
+			if usedFromGiven[j] {
+				continue
+			}
+			if wantedMatcher.Matches(given.Index(j).Interface()) {
+				foundFromWanted[i] = true
+				usedFromGiven[j] = true
+				break
+			}
+		}
+	}
+
+	missingFromWanted := 0
+	for _, found := range foundFromWanted {
+		if !found {
+			missingFromWanted++
+		}
+	}
+	extraInGiven := 0
+	for _, used := range usedFromGiven {
+		if !used {
+			extraInGiven++
+		}
+	}
+
+	return extraInGiven == 0 && missingFromWanted == 0
+}
+
+func (m inAnyOrderMatcher) prepareValue(x interface{}) (reflect.Value, bool) {
+	xValue := reflect.ValueOf(x)
+	switch xValue.Kind() {
+	case reflect.Slice, reflect.Array:
+		return xValue, true
+	default:
+		return reflect.Value{}, false
+	}
+}
+
+func (m inAnyOrderMatcher) String() string {
+	return fmt.Sprintf("has the same elements as %v", m.x)
+}
+
+// Constructors
+
+// All returns a composite Matcher that returns true if and only all of the
+// matchers return true.
+func All(ms ...Matcher) Matcher { return allMatcher{ms} }
+
+// Any returns a matcher that always matches.
+func Any() Matcher { return anyMatcher{} }
+
+// Eq returns a matcher that matches on equality.
+//
+// Example usage:
+//   Eq(5).Matches(5) // returns true
+//   Eq(5).Matches(4) // returns false
+func Eq(x interface{}) Matcher { return eqMatcher{x} }
+
+// Len returns a matcher that matches on length. This matcher returns false if
+// is compared to a type that is not an array, chan, map, slice, or string.
+func Len(i int) Matcher {
+	return lenMatcher{i}
+}
+
+// Nil returns a matcher that matches if the received value is nil.
+//
+// Example usage:
+//   var x *bytes.Buffer
+//   Nil().Matches(x) // returns true
+//   x = &bytes.Buffer{}
+//   Nil().Matches(x) // returns false
+func Nil() Matcher { return nilMatcher{} }
+
+// Not reverses the results of its given child matcher.
+//
+// Example usage:
+//   Not(Eq(5)).Matches(4) // returns true
+//   Not(Eq(5)).Matches(5) // returns false
+func Not(x interface{}) Matcher {
+	if m, ok := x.(Matcher); ok {
+		return notMatcher{m}
+	}
+	return notMatcher{Eq(x)}
+}
+
+// AssignableToTypeOf is a Matcher that matches if the parameter to the mock
+// function is assignable to the type of the parameter to this function.
+//
+// Example usage:
+//   var s fmt.Stringer = &bytes.Buffer{}
+//   AssignableToTypeOf(s).Matches(time.Second) // returns true
+//   AssignableToTypeOf(s).Matches(99) // returns false
+//
+//   var ctx = reflect.TypeOf((*context.Context)(nil)).Elem()
+//   AssignableToTypeOf(ctx).Matches(context.Background()) // returns true
+func AssignableToTypeOf(x interface{}) Matcher {
+	if xt, ok := x.(reflect.Type); ok {
+		return assignableToTypeOfMatcher{xt}
+	}
+	return assignableToTypeOfMatcher{reflect.TypeOf(x)}
+}
+
+// InAnyOrder is a Matcher that returns true for collections of the same elements ignoring the order.
+//
+// Example usage:
+//   InAnyOrder([]int{1, 2, 3}).Matches([]int{1, 3, 2}) // returns true
+//   InAnyOrder([]int{1, 2, 3}).Matches([]int{1, 2}) // returns false
+func InAnyOrder(x interface{}) Matcher {
+	return inAnyOrderMatcher{x}
+}
diff --git a/vendor/modules.txt b/vendor/modules.txt
index 67dd58479..c7af6c35a 100644
--- a/vendor/modules.txt
+++ b/vendor/modules.txt
@@ -170,6 +170,9 @@ github.com/golang-jwt/jwt/v4
 # github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da
 ## explicit
 github.com/golang/groupcache/lru
+# github.com/golang/mock v1.6.0
+## explicit; go 1.11
+github.com/golang/mock/gomock
 # github.com/golang/protobuf v1.5.2
 ## explicit; go 1.9
 github.com/golang/protobuf/proto


Test patch:
diff --git a/pkg/ip/cidr_test.go b/pkg/ip/cidr_test.go
index dcf209b7a..898aca571 100644
--- a/pkg/ip/cidr_test.go
+++ b/pkg/ip/cidr_test.go
@@ -17,13 +17,13 @@ var _ = Describe("CIDR", Label("cidr_test"), func() {
 	Describe("Test ParseCIDR", func() {
 		When("Verifying", func() {
 			It("inputs invalid IP version", func() {
-				ip, err := spiderpoolip.ParseCIDR(invalidIPVersion, "172.18.40.40/24")
+				ip, err := spiderpoolip.ParseCIDR(constant.InvalidIPVersion, "172.18.40.40/24")
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPVersion))
 				Expect(ip).To(BeNil())
 			})
 
 			It("inputs invalid CIDR address", func() {
-				ip, err := spiderpoolip.ParseCIDR(constant.IPv4, invalidCIDR)
+				ip, err := spiderpoolip.ParseCIDR(constant.IPv4, constant.InvalidCIDR)
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidCIDRFormat))
 				Expect(ip).To(BeNil())
 			})
@@ -55,17 +55,17 @@ var _ = Describe("CIDR", Label("cidr_test"), func() {
 	Describe("Test ContainsCIDR", func() {
 		When("Verifying", func() {
 			It("inputs invalid IP version", func() {
-				contains, err := spiderpoolip.ContainsCIDR(invalidIPVersion, "172.18.40.0/24", "172.18.40.0/25")
+				contains, err := spiderpoolip.ContainsCIDR(constant.InvalidIPVersion, "172.18.40.0/24", "172.18.40.0/25")
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPVersion))
 				Expect(contains).To(BeFalse())
 			})
 
 			It("inputs invalid CIDR address", func() {
-				contains, err := spiderpoolip.ContainsCIDR(constant.IPv4, invalidCIDR, "172.18.40.0/25")
+				contains, err := spiderpoolip.ContainsCIDR(constant.IPv4, constant.InvalidCIDR, "172.18.40.0/25")
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidCIDRFormat))
 				Expect(contains).To(BeFalse())
 
-				contains, err = spiderpoolip.ContainsCIDR(constant.IPv4, "172.18.40.0/24", invalidCIDR)
+				contains, err = spiderpoolip.ContainsCIDR(constant.IPv4, "172.18.40.0/24", constant.InvalidCIDR)
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidCIDRFormat))
 				Expect(contains).To(BeFalse())
 			})
@@ -103,17 +103,17 @@ var _ = Describe("CIDR", Label("cidr_test"), func() {
 	Describe("Test IsCIDROverlap", func() {
 		When("Verifying", func() {
 			It("inputs invalid IP version", func() {
-				overlap, err := spiderpoolip.IsCIDROverlap(invalidIPVersion, "172.18.40.0/24", "172.18.40.0/25")
+				overlap, err := spiderpoolip.IsCIDROverlap(constant.InvalidIPVersion, "172.18.40.0/24", "172.18.40.0/25")
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPVersion))
 				Expect(overlap).To(BeFalse())
 			})
 
 			It("inputs invalid CIDR address", func() {
-				overlap, err := spiderpoolip.IsCIDROverlap(constant.IPv4, invalidCIDR, "172.18.40.0/25")
+				overlap, err := spiderpoolip.IsCIDROverlap(constant.IPv4, constant.InvalidCIDR, "172.18.40.0/25")
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidCIDRFormat))
 				Expect(overlap).To(BeFalse())
 
-				overlap, err = spiderpoolip.IsCIDROverlap(constant.IPv4, "172.18.40.0/24", invalidCIDR)
+				overlap, err = spiderpoolip.IsCIDROverlap(constant.IPv4, "172.18.40.0/24", constant.InvalidCIDR)
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidCIDRFormat))
 				Expect(overlap).To(BeFalse())
 			})
@@ -151,12 +151,12 @@ var _ = Describe("CIDR", Label("cidr_test"), func() {
 	Describe("Test IsCIDR", func() {
 		When("Verifying", func() {
 			It("inputs invalid IP version", func() {
-				err := spiderpoolip.IsCIDR(invalidIPVersion, "172.18.40.0/24")
+				err := spiderpoolip.IsCIDR(constant.InvalidIPVersion, "172.18.40.0/24")
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPVersion))
 			})
 
 			It("inputs invalid CIDR address", func() {
-				err := spiderpoolip.IsCIDR(constant.IPv4, invalidCIDR)
+				err := spiderpoolip.IsCIDR(constant.IPv4, constant.InvalidCIDR)
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidCIDRFormat))
 			})
 		})
@@ -172,14 +172,14 @@ var _ = Describe("CIDR", Label("cidr_test"), func() {
 
 	Describe("Test IsIPv4CIDR", func() {
 		It("tests whether it is an IPv4 CIDR address", func() {
-			Expect(spiderpoolip.IsIPv4CIDR(invalidCIDR)).To(BeFalse())
+			Expect(spiderpoolip.IsIPv4CIDR(constant.InvalidCIDR)).To(BeFalse())
 			Expect(spiderpoolip.IsIPv4CIDR("172.18.40.0/24")).To(BeTrue())
 		})
 	})
 
 	Describe("Test IsIPv6CIDR", func() {
 		It("tests whether it is an IPv6 CIDR address", func() {
-			Expect(spiderpoolip.IsIPv6CIDR(invalidCIDR)).To(BeFalse())
+			Expect(spiderpoolip.IsIPv6CIDR(constant.InvalidCIDR)).To(BeFalse())
 			Expect(spiderpoolip.IsIPv6CIDR("abcd:1234::/120")).To(BeTrue())
 		})
 	})
diff --git a/pkg/ip/ip_suite_test.go b/pkg/ip/ip_suite_test.go
index c562108d4..e7db9352b 100644
--- a/pkg/ip/ip_suite_test.go
+++ b/pkg/ip/ip_suite_test.go
@@ -8,21 +8,8 @@ import (
 
 	. "github.com/onsi/ginkgo/v2"
 	. "github.com/onsi/gomega"
-
-	"github.com/spidernet-io/spiderpool/pkg/types"
-)
-
-const (
-	invalidIPVersion = types.IPVersion(976)
-	invalidCIDR      = "invalid CIDR"
-	invalidIP        = "invalid IP"
-	invalidIPRange   = "invalid IP range"
-	invalidDst       = "invalid routing destination"
-	invalidGateway   = "invalid routing gateway"
 )
 
-var invalidIPRanges = []string{invalidIPRange}
-
 func TestIP(t *testing.T) {
 	RegisterFailHandler(Fail)
 	RunSpecs(t, "IP Suite", Label("ip", "unitest"))
diff --git a/pkg/ip/ip_test.go b/pkg/ip/ip_test.go
index 2c3aeb477..49d13a408 100644
--- a/pkg/ip/ip_test.go
+++ b/pkg/ip/ip_test.go
@@ -16,7 +16,7 @@ import (
 var _ = Describe("IP", Label("ip_test"), func() {
 	Describe("Test IsIPVersion", func() {
 		It("inputs invalid IP version", func() {
-			err := spiderpoolip.IsIPVersion(invalidIPVersion)
+			err := spiderpoolip.IsIPVersion(constant.InvalidIPVersion)
 			Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPVersion))
 		})
 
@@ -33,24 +33,24 @@ var _ = Describe("IP", Label("ip_test"), func() {
 		Describe("IP format", func() {
 			When("Verifying", func() {
 				It("inputs invalid IP version", func() {
-					ip, err := spiderpoolip.ParseIP(invalidIPVersion, "172.18.40.40", false)
+					ip, err := spiderpoolip.ParseIP(constant.InvalidIPVersion, "172.18.40.10", false)
 					Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPVersion))
 					Expect(ip).To(BeNil())
 				})
 
 				It("inputs invalid IP address", func() {
-					ip, err := spiderpoolip.ParseIP(constant.IPv4, invalidIP, false)
+					ip, err := spiderpoolip.ParseIP(constant.IPv4, constant.InvalidIP, false)
 					Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPFormat))
 					Expect(ip).To(BeNil())
 				})
 			})
 
 			It("parses IPv4 IP address", func() {
-				ip, err := spiderpoolip.ParseIP(constant.IPv4, "172.18.40.40", false)
+				ip, err := spiderpoolip.ParseIP(constant.IPv4, "172.18.40.10", false)
 				Expect(err).NotTo(HaveOccurred())
 				Expect(ip).To(Equal(
 					&net.IPNet{
-						IP:   net.IPv4(172, 18, 40, 40),
+						IP:   net.IPv4(172, 18, 40, 10),
 						Mask: net.CIDRMask(32, 32),
 					},
 				))
@@ -71,24 +71,24 @@ var _ = Describe("IP", Label("ip_test"), func() {
 		Describe("CIDR format", func() {
 			When("Verifying", func() {
 				It("inputs invalid IP version", func() {
-					ip, err := spiderpoolip.ParseIP(invalidIPVersion, "172.18.40.40/24", true)
+					ip, err := spiderpoolip.ParseIP(constant.InvalidIPVersion, "172.18.40.10/24", true)
 					Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPVersion))
 					Expect(ip).To(BeNil())
 				})
 
 				It("inputs invalid CIDR address", func() {
-					ip, err := spiderpoolip.ParseIP(constant.IPv4, invalidCIDR, true)
+					ip, err := spiderpoolip.ParseIP(constant.IPv4, constant.InvalidCIDR, true)
 					Expect(err).To(MatchError(spiderpoolip.ErrInvalidCIDRFormat))
 					Expect(ip).To(BeNil())
 				})
 			})
 
 			It("parses IPv4 CIDR address", func() {
-				ip, err := spiderpoolip.ParseIP(constant.IPv4, "172.18.40.40/24", true)
+				ip, err := spiderpoolip.ParseIP(constant.IPv4, "172.18.40.10/24", true)
 				Expect(err).NotTo(HaveOccurred())
 				Expect(ip).To(Equal(
 					&net.IPNet{
-						IP:   net.IPv4(172, 18, 40, 40),
+						IP:   net.IPv4(172, 18, 40, 10),
 						Mask: net.CIDRMask(24, 32),
 					},
 				))
@@ -110,19 +110,19 @@ var _ = Describe("IP", Label("ip_test"), func() {
 	Describe("Test ContainsIP", func() {
 		When("Verifying", func() {
 			It("inputs invalid IP version", func() {
-				contains, err := spiderpoolip.ContainsIP(invalidIPVersion, "172.18.40.0/24", "172.18.40.40")
+				contains, err := spiderpoolip.ContainsIP(constant.InvalidIPVersion, "172.18.40.0/24", "172.18.40.10")
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPVersion))
 				Expect(contains).To(BeFalse())
 			})
 
 			It("inputs invalid subnet", func() {
-				contains, err := spiderpoolip.ContainsIP(constant.IPv4, invalidCIDR, "172.18.40.40")
+				contains, err := spiderpoolip.ContainsIP(constant.IPv4, constant.InvalidCIDR, "172.18.40.10")
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidCIDRFormat))
 				Expect(contains).To(BeFalse())
 			})
 
 			It("inputs invalid IP address", func() {
-				contains, err := spiderpoolip.ContainsIP(constant.IPv4, "172.18.40.0/24", invalidIP)
+				contains, err := spiderpoolip.ContainsIP(constant.IPv4, "172.18.40.0/24", constant.InvalidIP)
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPFormat))
 				Expect(contains).To(BeFalse())
 			})
@@ -130,13 +130,13 @@ var _ = Describe("IP", Label("ip_test"), func() {
 
 		When("IPv4", func() {
 			It("tests that a subnet contains the IP address", func() {
-				contains, err := spiderpoolip.ContainsIP(constant.IPv4, "172.18.40.0/24", "172.18.40.40")
+				contains, err := spiderpoolip.ContainsIP(constant.IPv4, "172.18.40.0/24", "172.18.40.10")
 				Expect(err).NotTo(HaveOccurred())
 				Expect(contains).To(BeTrue())
 			})
 
 			It("test that a subnet does not contain the IP address", func() {
-				contains, err := spiderpoolip.ContainsIP(constant.IPv4, "172.18.41.0/24", "172.18.40.40")
+				contains, err := spiderpoolip.ContainsIP(constant.IPv4, "172.18.41.0/24", "172.18.40.10")
 				Expect(err).NotTo(HaveOccurred())
 				Expect(contains).To(BeFalse())
 			})
@@ -160,18 +160,18 @@ var _ = Describe("IP", Label("ip_test"), func() {
 	Describe("Test IsIP", func() {
 		When("Verifying", func() {
 			It("inputs invalid IP version", func() {
-				err := spiderpoolip.IsIP(invalidIPVersion, "172.18.40.40")
+				err := spiderpoolip.IsIP(constant.InvalidIPVersion, "172.18.40.10")
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPVersion))
 			})
 
 			It("inputs invalid IP address", func() {
-				err := spiderpoolip.IsIP(constant.IPv4, invalidIP)
+				err := spiderpoolip.IsIP(constant.IPv4, constant.InvalidIP)
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPFormat))
 			})
 		})
 
 		It("is IPv4 IP address", func() {
-			Expect(spiderpoolip.IsIP(constant.IPv4, "172.18.40.40")).To(Succeed())
+			Expect(spiderpoolip.IsIP(constant.IPv4, "172.18.40.10")).To(Succeed())
 		})
 
 		It("is IPv6 IP address", func() {
diff --git a/pkg/ip/iprange_test.go b/pkg/ip/iprange_test.go
index 887aabab4..46dd59d77 100644
--- a/pkg/ip/iprange_test.go
+++ b/pkg/ip/iprange_test.go
@@ -17,13 +17,13 @@ var _ = Describe("IP range", Label("ip_range_test"), func() {
 	Describe("Test MergeIPRanges", func() {
 		When("Verifying", func() {
 			It("inputs invalid IP version", func() {
-				ranges, err := spiderpoolip.MergeIPRanges(invalidIPVersion, []string{"172.18.40.10"})
+				ranges, err := spiderpoolip.MergeIPRanges(constant.InvalidIPVersion, []string{"172.18.40.10"})
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPVersion))
 				Expect(ranges).To(BeEmpty())
 			})
 
 			It("inputs invalid IP ranges", func() {
-				ranges, err := spiderpoolip.MergeIPRanges(constant.IPv4, invalidIPRanges)
+				ranges, err := spiderpoolip.MergeIPRanges(constant.IPv4, constant.InvalidIPRanges)
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPRangeFormat))
 				Expect(ranges).To(BeEmpty())
 			})
@@ -33,14 +33,14 @@ var _ = Describe("IP range", Label("ip_range_test"), func() {
 			ranges, err := spiderpoolip.MergeIPRanges(constant.IPv4,
 				[]string{
 					"172.18.40.10",
-					"172.18.40.1-172.18.40.3",
-					"172.18.40.2-172.18.40.5",
+					"172.18.40.1-172.18.40.2",
+					"172.18.40.2-172.18.40.3",
 				},
 			)
 			Expect(err).NotTo(HaveOccurred())
 			Expect(ranges).To(Equal(
 				[]string{
-					"172.18.40.1-172.18.40.5",
+					"172.18.40.1-172.18.40.3",
 					"172.18.40.10",
 				},
 			))
@@ -50,14 +50,14 @@ var _ = Describe("IP range", Label("ip_range_test"), func() {
 			ranges, err := spiderpoolip.MergeIPRanges(constant.IPv6,
 				[]string{
 					"abcd:1234::a",
-					"abcd:1234::1-abcd:1234::3",
-					"abcd:1234::2-abcd:1234::5",
+					"abcd:1234::1-abcd:1234::2",
+					"abcd:1234::2-abcd:1234::3",
 				},
 			)
 			Expect(err).NotTo(HaveOccurred())
 			Expect(ranges).To(Equal(
 				[]string{
-					"abcd:1234::1-abcd:1234::5",
+					"abcd:1234::1-abcd:1234::3",
 					"abcd:1234::a",
 				},
 			))
@@ -67,13 +67,13 @@ var _ = Describe("IP range", Label("ip_range_test"), func() {
 	Describe("Test ParseIPRanges", func() {
 		When("Verifying", func() {
 			It("inputs invalid IP version", func() {
-				ips, err := spiderpoolip.ParseIPRanges(invalidIPVersion, []string{"172.18.40.10"})
+				ips, err := spiderpoolip.ParseIPRanges(constant.InvalidIPVersion, []string{"172.18.40.10"})
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPVersion))
 				Expect(ips).To(BeEmpty())
 			})
 
 			It("inputs invalid IP ranges", func() {
-				ips, err := spiderpoolip.ParseIPRanges(constant.IPv4, invalidIPRanges)
+				ips, err := spiderpoolip.ParseIPRanges(constant.IPv4, constant.InvalidIPRanges)
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPRangeFormat))
 				Expect(ips).To(BeEmpty())
 			})
@@ -125,13 +125,13 @@ var _ = Describe("IP range", Label("ip_range_test"), func() {
 	Describe("Test ParseIPRange", func() {
 		When("Verifying", func() {
 			It("inputs invalid IP version", func() {
-				ips, err := spiderpoolip.ParseIPRange(invalidIPVersion, "172.18.40.10")
+				ips, err := spiderpoolip.ParseIPRange(constant.InvalidIPVersion, "172.18.40.10")
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPVersion))
 				Expect(ips).To(BeEmpty())
 			})
 
 			It("inputs invalid IP ranges", func() {
-				ips, err := spiderpoolip.ParseIPRange(constant.IPv4, invalidIPRange)
+				ips, err := spiderpoolip.ParseIPRange(constant.IPv4, constant.InvalidIPRange)
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPRangeFormat))
 				Expect(ips).To(BeEmpty())
 			})
@@ -171,7 +171,7 @@ var _ = Describe("IP range", Label("ip_range_test"), func() {
 	Describe("Test ConvertIPsToIPRanges", func() {
 		When("Verifying", func() {
 			It("inputs invalid IP version", func() {
-				ranges, err := spiderpoolip.ConvertIPsToIPRanges(invalidIPVersion, []net.IP{net.IPv4(172, 18, 40, 10)})
+				ranges, err := spiderpoolip.ConvertIPsToIPRanges(constant.InvalidIPVersion, []net.IP{net.IPv4(172, 18, 40, 10)})
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPVersion))
 				Expect(ranges).To(BeEmpty())
 			})
@@ -229,19 +229,19 @@ var _ = Describe("IP range", Label("ip_range_test"), func() {
 	Describe("Test ContainsIPRange", func() {
 		When("Verifying", func() {
 			It("inputs invalid IP version", func() {
-				contains, err := spiderpoolip.ContainsIPRange(invalidIPVersion, "172.18.40.0/24", "172.18.40.10")
+				contains, err := spiderpoolip.ContainsIPRange(constant.InvalidIPVersion, "172.18.40.0/24", "172.18.40.10")
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPVersion))
 				Expect(contains).To(BeFalse())
 			})
 
 			It("inputs invalid subnet", func() {
-				contains, err := spiderpoolip.ContainsIPRange(constant.IPv4, invalidCIDR, "172.18.40.10")
+				contains, err := spiderpoolip.ContainsIPRange(constant.IPv4, constant.InvalidCIDR, "172.18.40.10")
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidCIDRFormat))
 				Expect(contains).To(BeFalse())
 			})
 
 			It("inputs invalid IP range", func() {
-				contains, err := spiderpoolip.ContainsIPRange(constant.IPv4, "172.18.40.0/24", invalidIPRange)
+				contains, err := spiderpoolip.ContainsIPRange(constant.IPv4, "172.18.40.0/24", constant.InvalidIPRange)
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPRangeFormat))
 				Expect(contains).To(BeFalse())
 			})
@@ -287,17 +287,17 @@ var _ = Describe("IP range", Label("ip_range_test"), func() {
 	Describe("Test IsIPRangeOverlap", func() {
 		When("Verifying", func() {
 			It("inputs invalid IP version", func() {
-				overlap, err := spiderpoolip.IsIPRangeOverlap(invalidIPVersion, "172.18.40.1-172.18.40.2", "172.18.40.2-172.18.40.3")
+				overlap, err := spiderpoolip.IsIPRangeOverlap(constant.InvalidIPVersion, "172.18.40.1-172.18.40.2", "172.18.40.2-172.18.40.3")
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPVersion))
 				Expect(overlap).To(BeFalse())
 			})
 
 			It("inputs invalid IP range", func() {
-				overlap, err := spiderpoolip.IsIPRangeOverlap(constant.IPv4, invalidIPRange, "172.18.40.2-172.18.40.3")
+				overlap, err := spiderpoolip.IsIPRangeOverlap(constant.IPv4, constant.InvalidIPRange, "172.18.40.2-172.18.40.3")
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPRangeFormat))
 				Expect(overlap).To(BeFalse())
 
-				overlap, err = spiderpoolip.IsIPRangeOverlap(constant.IPv4, "172.18.40.1-172.18.40.2", invalidIPRange)
+				overlap, err = spiderpoolip.IsIPRangeOverlap(constant.IPv4, "172.18.40.1-172.18.40.2", constant.InvalidIPRange)
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPRangeFormat))
 				Expect(overlap).To(BeFalse())
 			})
@@ -335,12 +335,12 @@ var _ = Describe("IP range", Label("ip_range_test"), func() {
 	Describe("Test IsIPRange", func() {
 		When("Verifying", func() {
 			It("inputs invalid IP version", func() {
-				err := spiderpoolip.IsIPRange(invalidIPVersion, "172.18.40.1-172.18.40.2")
+				err := spiderpoolip.IsIPRange(constant.InvalidIPVersion, "172.18.40.1-172.18.40.2")
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPVersion))
 			})
 
 			It("inputs invalid IP range", func() {
-				err := spiderpoolip.IsIPRange(constant.IPv4, invalidIPRange)
+				err := spiderpoolip.IsIPRange(constant.IPv4, constant.InvalidIPRange)
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPRangeFormat))
 			})
 		})
@@ -358,7 +358,7 @@ var _ = Describe("IP range", Label("ip_range_test"), func() {
 
 	Describe("Test IsIPv4IPRange", func() {
 		It("tests whether it is an IPv4 IP range", func() {
-			Expect(spiderpoolip.IsIPv4IPRange(invalidIPRange)).To(BeFalse())
+			Expect(spiderpoolip.IsIPv4IPRange(constant.InvalidIPRange)).To(BeFalse())
 			Expect(spiderpoolip.IsIPv4IPRange("172.18.40.1-invalid IP range")).To(BeFalse())
 			Expect(spiderpoolip.IsIPv4IPRange("invalid IP range-172.18.40.2")).To(BeFalse())
 			Expect(spiderpoolip.IsIPv4IPRange("172.18.40.2-172.18.40.1")).To(BeFalse())
@@ -371,7 +371,7 @@ var _ = Describe("IP range", Label("ip_range_test"), func() {
 
 	Describe("Test IsIPv6IPRange", func() {
 		It("tests whether it is an IPv6 IP range", func() {
-			Expect(spiderpoolip.IsIPv6IPRange(invalidIPRange)).To(BeFalse())
+			Expect(spiderpoolip.IsIPv6IPRange(constant.InvalidIPRange)).To(BeFalse())
 			Expect(spiderpoolip.IsIPv6IPRange("abcd:1234::1-invalid IP range")).To(BeFalse())
 			Expect(spiderpoolip.IsIPv6IPRange("invalid IP range-abcd:1234::2")).To(BeFalse())
 			Expect(spiderpoolip.IsIPv6IPRange("abcd:1234::2-abcd:1234::1")).To(BeFalse())
diff --git a/pkg/ip/route_test.go b/pkg/ip/route_test.go
index f8d64001c..816b559a9 100644
--- a/pkg/ip/route_test.go
+++ b/pkg/ip/route_test.go
@@ -15,17 +15,17 @@ var _ = Describe("Route", Label("route_test"), func() {
 	Describe("Test IsRoute", func() {
 		When("Verifying", func() {
 			It("inputs invalid IP version", func() {
-				err := spiderpoolip.IsRoute(invalidIPVersion, "192.168.40.0/24", "172.18.40.1")
+				err := spiderpoolip.IsRoute(constant.InvalidIPVersion, "192.168.40.0/24", "172.18.40.1")
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPVersion))
 			})
 
 			It("inputs invalid routing destination", func() {
-				err := spiderpoolip.IsRoute(constant.IPv4, invalidDst, "172.18.40.1")
+				err := spiderpoolip.IsRoute(constant.IPv4, constant.InvalidDst, "172.18.40.1")
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidRouteFormat))
 			})
 
 			It("inputs invalid routing gateway", func() {
-				err := spiderpoolip.IsRoute(constant.IPv4, "192.168.40.0/24", invalidGateway)
+				err := spiderpoolip.IsRoute(constant.IPv4, "192.168.40.0/24", constant.InvalidGateway)
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidRouteFormat))
 			})
 		})
@@ -44,12 +44,12 @@ var _ = Describe("Route", Label("route_test"), func() {
 	Describe("Test IsRouteWithoutIPVersion", func() {
 		When("Verifying", func() {
 			It("inputs invalid routing destination", func() {
-				err := spiderpoolip.IsRouteWithoutIPVersion(invalidDst, "172.18.40.1")
+				err := spiderpoolip.IsRouteWithoutIPVersion(constant.InvalidDst, "172.18.40.1")
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidRouteFormat))
 			})
 
 			It("inputs invalid routing gateway", func() {
-				err := spiderpoolip.IsRouteWithoutIPVersion("192.168.40.0/24", invalidGateway)
+				err := spiderpoolip.IsRouteWithoutIPVersion("192.168.40.0/24", constant.InvalidGateway)
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidRouteFormat))
 			})
 		})
@@ -65,16 +65,16 @@ var _ = Describe("Route", Label("route_test"), func() {
 
 	Describe("Test IsIPv4Route", func() {
 		It("tests whether it is an IPv4 route", func() {
-			Expect(spiderpoolip.IsIPv4Route(invalidDst, "172.18.40.1")).To(BeFalse())
-			Expect(spiderpoolip.IsIPv4Route("192.168.40.0/24", invalidGateway)).To(BeFalse())
+			Expect(spiderpoolip.IsIPv4Route(constant.InvalidDst, "172.18.40.1")).To(BeFalse())
+			Expect(spiderpoolip.IsIPv4Route("192.168.40.0/24", constant.InvalidGateway)).To(BeFalse())
 			Expect(spiderpoolip.IsIPv4Route("192.168.40.0/24", "172.18.40.1")).To(BeTrue())
 		})
 	})
 
 	Describe("Test IsIPv6Route", func() {
 		It("tests whether it is an IPv6 route", func() {
-			Expect(spiderpoolip.IsIPv6Route(invalidDst, "abcd:1234::1")).To(BeFalse())
-			Expect(spiderpoolip.IsIPv6Route("fd00:40::/120", invalidGateway)).To(BeFalse())
+			Expect(spiderpoolip.IsIPv6Route(constant.InvalidDst, "abcd:1234::1")).To(BeFalse())
+			Expect(spiderpoolip.IsIPv6Route("fd00:40::/120", constant.InvalidGateway)).To(BeFalse())
 			Expect(spiderpoolip.IsIPv6Route("fd00:40::/120", "abcd:1234::1")).To(BeTrue())
 		})
 	})
diff --git a/pkg/ip/utils_test.go b/pkg/ip/utils_test.go
index b68e4c414..6631300c1 100644
--- a/pkg/ip/utils_test.go
+++ b/pkg/ip/utils_test.go
@@ -17,19 +17,19 @@ var _ = Describe("IP utils", Label("ip_utils_test"), func() {
 	Describe("Test AssembleTotalIPs", func() {
 		When("Verifying", func() {
 			It("inputs invalid IP version", func() {
-				ips, err := spiderpoolip.AssembleTotalIPs(invalidIPVersion, []string{"172.18.40.1-172.18.40.2"}, []string{"172.18.40.2"})
+				ips, err := spiderpoolip.AssembleTotalIPs(constant.InvalidIPVersion, []string{"172.18.40.1-172.18.40.2"}, []string{"172.18.40.2"})
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPVersion))
 				Expect(ips).To(BeEmpty())
 			})
 
 			It("inputs invalid IP ranges", func() {
-				ips, err := spiderpoolip.AssembleTotalIPs(constant.IPv4, invalidIPRanges, []string{"172.18.40.2"})
+				ips, err := spiderpoolip.AssembleTotalIPs(constant.IPv4, constant.InvalidIPRanges, []string{"172.18.40.2"})
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPRangeFormat))
 				Expect(ips).To(BeEmpty())
 			})
 
 			It("inputs invalid excluded IP ranges", func() {
-				ips, err := spiderpoolip.AssembleTotalIPs(constant.IPv4, []string{"172.18.40.1-172.18.40.2"}, invalidIPRanges)
+				ips, err := spiderpoolip.AssembleTotalIPs(constant.IPv4, []string{"172.18.40.1-172.18.40.2"}, constant.InvalidIPRanges)
 				Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPRangeFormat))
 				Expect(ips).To(BeEmpty())
 			})
diff --git a/pkg/namespacemanager/utils_test.go b/pkg/namespacemanager/utils_test.go
index c1af36b1d..e49f77654 100644
--- a/pkg/namespacemanager/utils_test.go
+++ b/pkg/namespacemanager/utils_test.go
@@ -26,6 +26,10 @@ var _ = Describe("NamespaceManager utils", Label("namespace_manager_utils_test")
 			v6Pool1, v6Pool2 = "ns-default-ipv6-ippool1", "ns-default-ipv6-ippool2"
 
 			nsT = &corev1.Namespace{
+				TypeMeta: metav1.TypeMeta{
+					Kind:       "Namespace",
+					APIVersion: "v1",
+				},
 				ObjectMeta: metav1.ObjectMeta{
 					Name: "namespace",
 				},
@@ -33,6 +37,13 @@ var _ = Describe("NamespaceManager utils", Label("namespace_manager_utils_test")
 			}
 		})
 
+		It("inputs nil Namespace", func() {
+			nsDefaultV4Pools, nsDefaultV6Pools, err := namespacemanager.GetNSDefaultPools(nil)
+			Expect(err).To(MatchError(constant.ErrMissingRequiredParam))
+			Expect(nsDefaultV4Pools).To(BeEmpty())
+			Expect(nsDefaultV6Pools).To(BeEmpty())
+		})
+
 		It("inputs invalid annotation ipam.spidernet.io/default-ipv4-ippool", func() {
 			nsT.SetAnnotations(map[string]string{
 				constant.AnnoNSDefautlV4Pool: "invalid value",
diff --git a/pkg/reservedipmanager/reservedip_manager_suite_test.go b/pkg/reservedipmanager/reservedip_manager_suite_test.go
new file mode 100644
index 000000000..5a378d117
--- /dev/null
+++ b/pkg/reservedipmanager/reservedip_manager_suite_test.go
@@ -0,0 +1,53 @@
+// Copyright 2022 Authors of spidernet-io
+// SPDX-License-Identifier: Apache-2.0
+
+package reservedipmanager_test
+
+import (
+	"testing"
+
+	"github.com/golang/mock/gomock"
+	. "github.com/onsi/ginkgo/v2"
+	. "github.com/onsi/gomega"
+	"k8s.io/apimachinery/pkg/runtime"
+	"sigs.k8s.io/controller-runtime/pkg/client"
+	"sigs.k8s.io/controller-runtime/pkg/client/fake"
+
+	spiderpoolv1 "github.com/spidernet-io/spiderpool/pkg/k8s/apis/spiderpool.spidernet.io/v1"
+	"github.com/spidernet-io/spiderpool/pkg/reservedipmanager"
+	mock "github.com/spidernet-io/spiderpool/pkg/reservedipmanager/mock"
+)
+
+var mockCtrl *gomock.Controller
+var mockRIPManager *mock.MockReservedIPManager
+
+var scheme *runtime.Scheme
+var fakeClient client.Client
+var rIPManager reservedipmanager.ReservedIPManager
+var rIPWebhook *reservedipmanager.ReservedIPWebhook
+
+func TestReservedIPManager(t *testing.T) {
+	mockCtrl = gomock.NewController(t)
+	defer mockCtrl.Finish()
+
+	RegisterFailHandler(Fail)
+	RunSpecs(t, "ReservedIPManager Suite", Label("reservedipmanager", "unitest"))
+}
+
+var _ = BeforeSuite(func() {
+	scheme = runtime.NewScheme()
+	err := spiderpoolv1.AddToScheme(scheme)
+	Expect(err).NotTo(HaveOccurred())
+
+	fakeClient = fake.NewClientBuilder().
+		WithScheme(scheme).
+		Build()
+
+	rIPManager, err = reservedipmanager.NewReservedIPManager(fakeClient)
+	Expect(err).NotTo(HaveOccurred())
+
+	mockRIPManager = mock.NewMockReservedIPManager(mockCtrl)
+	rIPWebhook = &reservedipmanager.ReservedIPWebhook{
+		ReservedIPManager: mockRIPManager,
+	}
+})
diff --git a/pkg/reservedipmanager/reservedip_manager_test.go b/pkg/reservedipmanager/reservedip_manager_test.go
new file mode 100644
index 000000000..cee7ec11d
--- /dev/null
+++ b/pkg/reservedipmanager/reservedip_manager_test.go
@@ -0,0 +1,163 @@
+// Copyright 2022 Authors of spidernet-io
+// SPDX-License-Identifier: Apache-2.0
+
+package reservedipmanager_test
+
+import (
+	"context"
+	"fmt"
+	"sync/atomic"
+
+	"github.com/agiledragon/gomonkey/v2"
+	. "github.com/onsi/ginkgo/v2"
+	. "github.com/onsi/gomega"
+	apierrors "k8s.io/apimachinery/pkg/api/errors"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"sigs.k8s.io/controller-runtime/pkg/client"
+
+	"github.com/spidernet-io/spiderpool/pkg/constant"
+	spiderpoolv1 "github.com/spidernet-io/spiderpool/pkg/k8s/apis/spiderpool.spidernet.io/v1"
+	"github.com/spidernet-io/spiderpool/pkg/reservedipmanager"
+)
+
+var _ = Describe("ReservedIPManager", Label("reservedip_manager_test"), func() {
+	Describe("New ReservedIPManager", func() {
+		It("inputs nil client", func() {
+			manager, err := reservedipmanager.NewReservedIPManager(nil)
+			Expect(err).To(MatchError(constant.ErrMissingRequiredParam))
+			Expect(manager).To(BeNil())
+		})
+	})
+
+	Describe("Test ReservedIPManager's method", func() {
+		var count uint64
+		var rIPName string
+		var labels map[string]string
+		var rIPT *spiderpoolv1.SpiderReservedIP
+
+		BeforeEach(func() {
+			atomic.AddUint64(&count, 1)
+			rIPName = fmt.Sprintf("reservedip-%v", count)
+			labels = map[string]string{"foo": fmt.Sprintf("bar-%v", count)}
+			rIPT = &spiderpoolv1.SpiderReservedIP{
+				TypeMeta: metav1.TypeMeta{
+					Kind:       constant.SpiderReservedIPKind,
+					APIVersion: fmt.Sprintf("%s/%s", constant.SpiderpoolAPIGroup, constant.SpiderpoolAPIVersionV1),
+				},
+				ObjectMeta: metav1.ObjectMeta{
+					Name:   rIPName,
+					Labels: labels,
+				},
+				Spec: spiderpoolv1.ReservedIPSpec{},
+			}
+		})
+
+		var deleteOption *client.DeleteOptions
+
+		AfterEach(func() {
+			zero := int64(0)
+			policy := metav1.DeletePropagationForeground
+			deleteOption = &client.DeleteOptions{
+				GracePeriodSeconds: &zero,
+				PropagationPolicy:  &policy,
+			}
+
+			ctx := context.TODO()
+			err := fakeClient.Delete(ctx, rIPT, deleteOption)
+			Expect(client.IgnoreNotFound(err)).NotTo(HaveOccurred())
+		})
+
+		Describe("GetReservedIPByName", func() {
+			It("gets non-existent ReservedIP", func() {
+				ctx := context.TODO()
+				rIP, err := rIPManager.GetReservedIPByName(ctx, rIPName)
+				Expect(apierrors.IsNotFound(err)).To(BeTrue())
+				Expect(rIP).To(BeNil())
+			})
+
+			It("gets an existing ReservedIP", func() {
+				ctx := context.TODO()
+				err := fakeClient.Create(ctx, rIPT)
+				Expect(err).NotTo(HaveOccurred())
+
+				rIP, err := rIPManager.GetReservedIPByName(ctx, rIPName)
+				Expect(err).NotTo(HaveOccurred())
+				Expect(rIP).NotTo(BeNil())
+
+				Expect(rIP).To(Equal(rIPT))
+			})
+		})
+
+		Describe("ListReservedIPs", func() {
+			It("failed to list ReservedIPs due to some unknown errors", func() {
+				patches := gomonkey.ApplyMethodReturn(fakeClient, "List", constant.ErrUnknown)
+				defer patches.Reset()
+
+				ctx := context.TODO()
+				err := fakeClient.Create(ctx, rIPT)
+				Expect(err).NotTo(HaveOccurred())
+
+				rIPList, err := rIPManager.ListReservedIPs(ctx)
+				Expect(err).To(MatchError(constant.ErrUnknown))
+				Expect(rIPList).To(BeNil())
+			})
+
+			It("lists all ReservedIPs", func() {
+				ctx := context.TODO()
+				err := fakeClient.Create(ctx, rIPT)
+				Expect(err).NotTo(HaveOccurred())
+
+				rIPList, err := rIPManager.ListReservedIPs(ctx)
+				Expect(err).NotTo(HaveOccurred())
+				Expect(rIPList.Items).NotTo(BeEmpty())
+
+				hasRIP := false
+				for _, rIP := range rIPList.Items {
+					if rIP.Name == rIPName {
+						hasRIP = true
+						break
+					}
+				}
+				Expect(hasRIP).To(BeTrue())
+			})
+
+			It("filters results by label selector", func() {
+				ctx := context.TODO()
+				err := fakeClient.Create(ctx, rIPT)
+				Expect(err).NotTo(HaveOccurred())
+
+				rIPList, err := rIPManager.ListReservedIPs(ctx, client.MatchingLabels(labels))
+				Expect(err).NotTo(HaveOccurred())
+				Expect(rIPList.Items).NotTo(BeEmpty())
+
+				hasRIP := false
+				for _, rIP := range rIPList.Items {
+					if rIP.Name == rIPName {
+						hasRIP = true
+						break
+					}
+				}
+				Expect(hasRIP).To(BeTrue())
+			})
+
+			It("filters results by field selector", func() {
+				ctx := context.TODO()
+				err := fakeClient.Create(ctx, rIPT)
+				Expect(err).NotTo(HaveOccurred())
+
+				rIPList, err := rIPManager.ListReservedIPs(ctx, client.MatchingFields{metav1.ObjectNameField: rIPName})
+				Expect(err).NotTo(HaveOccurred())
+				Expect(rIPList.Items).NotTo(BeEmpty())
+
+				hasRIP := false
+				for _, rIP := range rIPList.Items {
+					if rIP.Name == rIPName {
+						hasRIP = true
+						break
+					}
+				}
+				Expect(hasRIP).To(BeTrue())
+			})
+		})
+	})
+})
diff --git a/pkg/reservedipmanager/reservedip_webhook_test.go b/pkg/reservedipmanager/reservedip_webhook_test.go
new file mode 100644
index 000000000..93cc656a4
--- /dev/null
+++ b/pkg/reservedipmanager/reservedip_webhook_test.go
@@ -0,0 +1,579 @@
+// Copyright 2022 Authors of spidernet-io
+// SPDX-License-Identifier: Apache-2.0
+
+package reservedipmanager_test
+
+import (
+	"context"
+	"fmt"
+	"time"
+
+	"github.com/golang/mock/gomock"
+	. "github.com/onsi/ginkgo/v2"
+	. "github.com/onsi/gomega"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	ctrl "sigs.k8s.io/controller-runtime"
+	"sigs.k8s.io/controller-runtime/pkg/client/config"
+	"sigs.k8s.io/controller-runtime/pkg/manager"
+
+	"github.com/spidernet-io/spiderpool/pkg/constant"
+	spiderpoolv1 "github.com/spidernet-io/spiderpool/pkg/k8s/apis/spiderpool.spidernet.io/v1"
+	"github.com/spidernet-io/spiderpool/pkg/logutils"
+	"github.com/spidernet-io/spiderpool/pkg/reservedipmanager"
+)
+
+var _ = Describe("ReservedIPWebhook", Label("reservedip_webhook_test"), func() {
+	Describe("Set up ReservedIPWebhook", func() {
+		PIt("talks to a Kubernetes API server", func() {
+			cfg, err := config.GetConfig()
+			Expect(err).NotTo(HaveOccurred())
+			Expect(cfg).NotTo(BeNil())
+
+			mgr, err := ctrl.NewManager(cfg, manager.Options{Scheme: scheme})
+			Expect(err).NotTo(HaveOccurred())
+
+			err = rIPWebhook.SetupWebhookWithManager(mgr)
+			Expect(err).NotTo(HaveOccurred())
+		})
+	})
+
+	Describe("Test ReservedIPWebhook's method", func() {
+		var rIPT *spiderpoolv1.SpiderReservedIP
+		var rIPListT *spiderpoolv1.SpiderReservedIPList
+
+		BeforeEach(func() {
+			reservedipmanager.WebhookLogger = logutils.Logger.Named("ReservedIP-Webhook")
+			rIPT = &spiderpoolv1.SpiderReservedIP{
+				TypeMeta: metav1.TypeMeta{
+					Kind:       constant.SpiderReservedIPKind,
+					APIVersion: fmt.Sprintf("%s/%s", constant.SpiderpoolAPIGroup, constant.SpiderpoolAPIVersionV1),
+				},
+				ObjectMeta: metav1.ObjectMeta{
+					Name: "reservedip",
+				},
+				Spec: spiderpoolv1.ReservedIPSpec{},
+			}
+
+			rIPListT = &spiderpoolv1.SpiderReservedIPList{
+				TypeMeta: metav1.TypeMeta{
+					Kind:       constant.SpiderReservedIPListKind,
+					APIVersion: fmt.Sprintf("%s/%s", constant.SpiderpoolAPIGroup, constant.SpiderpoolAPIVersionV1),
+				},
+				ListMeta: metav1.ListMeta{},
+			}
+		})
+
+		Describe("Default", func() {
+			It("avoids modifying the terminating ReservedIP", func() {
+				deletionTimestamp := metav1.NewTime(time.Now().Add(30 * time.Second))
+				rIPT.SetDeletionTimestamp(&deletionTimestamp)
+
+				ctx := context.TODO()
+				err := rIPWebhook.Default(ctx, rIPT)
+				Expect(err).NotTo(HaveOccurred())
+			})
+
+			It("avoids modifying the ReservedIP whose 'spec.ips' is empty", func() {
+				ctx := context.TODO()
+				err := rIPWebhook.Default(ctx, rIPT)
+				Expect(err).NotTo(HaveOccurred())
+			})
+
+			It("failed to set 'spec.ipVersion' due to the first IP range of 'spec.ips' is invalid", func() {
+				rIPT.Spec.IPs = append(rIPT.Spec.IPs, constant.InvalidIPRange)
+
+				ctx := context.TODO()
+				err := rIPWebhook.Default(ctx, rIPT)
+				Expect(err).NotTo(HaveOccurred())
+				Expect(rIPT.Spec.IPVersion).To(BeNil())
+			})
+
+			It("sets 'spec.ipVersion' to 4", func() {
+				rIPT.Spec.IPs = append(rIPT.Spec.IPs, "172.18.40.1-172.18.40.2")
+
+				ctx := context.TODO()
+				err := rIPWebhook.Default(ctx, rIPT)
+				Expect(err).NotTo(HaveOccurred())
+				Expect(*rIPT.Spec.IPVersion).To(Equal(constant.IPv4))
+			})
+
+			It("sets 'spec.ipVersion' to 6", func() {
+				rIPT.Spec.IPs = append(rIPT.Spec.IPs, "abcd:1234::1-abcd:1234::2")
+
+				ctx := context.TODO()
+				err := rIPWebhook.Default(ctx, rIPT)
+				Expect(err).NotTo(HaveOccurred())
+				Expect(*rIPT.Spec.IPVersion).To(Equal(constant.IPv6))
+			})
+
+			It("failed to merge 'spec.ips' due to the invalid 'spec.ipVersion'", func() {
+				ipVersion := constant.InvalidIPVersion
+				rIPT.Spec.IPVersion = &ipVersion
+				rIPT.Spec.IPs = append(rIPT.Spec.IPs,
+					[]string{
+						"172.18.40.10",
+						"172.18.40.1-172.18.40.2",
+						"172.18.40.2-172.18.40.3",
+					}...,
+				)
+
+				ctx := context.TODO()
+				err := rIPWebhook.Default(ctx, rIPT)
+				Expect(err).NotTo(HaveOccurred())
+				Expect(rIPT.Spec.IPs).To(Equal(
+					[]string{
+						"172.18.40.10",
+						"172.18.40.1-172.18.40.2",
+						"172.18.40.2-172.18.40.3",
+					},
+				))
+			})
+
+			It("failed to merge 'spec.ips' due to the invalid 'spec.ips'", func() {
+				ipv4 := constant.IPv4
+				rIPT.Spec.IPVersion = &ipv4
+				rIPT.Spec.IPs = append(rIPT.Spec.IPs,
+					[]string{
+						constant.InvalidIPRange,
+						"172.18.40.10",
+						"172.18.40.1-172.18.40.2",
+						"172.18.40.2-172.18.40.3",
+					}...,
+				)
+
+				ctx := context.TODO()
+				err := rIPWebhook.Default(ctx, rIPT)
+				Expect(err).NotTo(HaveOccurred())
+				Expect(rIPT.Spec.IPs).To(Equal(
+					[]string{
+						constant.InvalidIPRange,
+						"172.18.40.10",
+						"172.18.40.1-172.18.40.2",
+						"172.18.40.2-172.18.40.3",
+					},
+				))
+			})
+
+			It("merges IPv4 'spec.ips'", func() {
+				ipv4 := constant.IPv4
+				rIPT.Spec.IPVersion = &ipv4
+				rIPT.Spec.IPs = append(rIPT.Spec.IPs,
+					[]string{
+						"172.18.40.10",
+						"172.18.40.1-172.18.40.2",
+						"172.18.40.2-172.18.40.3",
+					}...,
+				)
+
+				ctx := context.TODO()
+				err := rIPWebhook.Default(ctx, rIPT)
+				Expect(err).NotTo(HaveOccurred())
+				Expect(rIPT.Spec.IPs).To(Equal(
+					[]string{
+						"172.18.40.1-172.18.40.3",
+						"172.18.40.10",
+					},
+				))
+			})
+
+			It("merges IPv6 'spec.ips'", func() {
+				ipv6 := constant.IPv6
+				rIPT.Spec.IPVersion = &ipv6
+				rIPT.Spec.IPs = append(rIPT.Spec.IPs,
+					[]string{
+						"abcd:1234::a",
+						"abcd:1234::1-abcd:1234::2",
+						"abcd:1234::2-abcd:1234::3",
+					}...,
+				)
+
+				ctx := context.TODO()
+				err := rIPWebhook.Default(ctx, rIPT)
+				Expect(err).NotTo(HaveOccurred())
+				Expect(rIPT.Spec.IPs).To(Equal(
+					[]string{
+						"abcd:1234::1-abcd:1234::3",
+						"abcd:1234::a",
+					},
+				))
+			})
+		})
+
+		Describe("ValidateCreate", func() {
+			BeforeEach(func() {
+				rIPWebhook.EnableIPv4 = true
+				rIPWebhook.EnableIPv6 = true
+			})
+
+			When("Validating 'spec.ipVersion'", func() {
+				It("inputs nil 'spec.ipVersion'", func() {
+					ctx := context.TODO()
+					err := rIPWebhook.ValidateCreate(ctx, rIPT)
+					Expect(err).To(HaveOccurred())
+				})
+
+				It("inputs invalid 'spec.ipVersion'", func() {
+					ipVersion := constant.InvalidIPVersion
+					rIPT.Spec.IPVersion = &ipVersion
+
+					ctx := context.TODO()
+					err := rIPWebhook.ValidateCreate(ctx, rIPT)
+					Expect(err).To(HaveOccurred())
+				})
+
+				It("creates IPv4 ReservedIP but IPv4 is disbale'", func() {
+					rIPWebhook.EnableIPv4 = false
+					ipVersion := constant.IPv4
+					rIPT.Spec.IPVersion = &ipVersion
+
+					ctx := context.TODO()
+					err := rIPWebhook.ValidateCreate(ctx, rIPT)
+					Expect(err).To(HaveOccurred())
+				})
+
+				It("creates IPv6 ReservedIP but IPv6 is disbale'", func() {
+					rIPWebhook.EnableIPv6 = false
+					ipVersion := constant.IPv6
+					rIPT.Spec.IPVersion = &ipVersion
+
+					ctx := context.TODO()
+					err := rIPWebhook.ValidateCreate(ctx, rIPT)
+					Expect(err).To(HaveOccurred())
+				})
+			})
+
+			When("Validating 'spec.ips'", func() {
+				It("failed to list ReservedIPs due to some unknown errors", func() {
+					mockRIPManager.EXPECT().
+						ListReservedIPs(gomock.All()).
+						Return(nil, constant.ErrUnknown).
+						Times(1)
+
+					ipVersion := constant.IPv4
+					rIPT.Spec.IPVersion = &ipVersion
+					rIPT.Spec.IPs = append(rIPT.Spec.IPs,
+						[]string{
+							"172.18.40.1-172.18.40.2",
+							"172.18.40.10",
+						}...,
+					)
+
+					ctx := context.TODO()
+					err := rIPWebhook.ValidateCreate(ctx, rIPT)
+					Expect(err).To(HaveOccurred())
+				})
+
+				It("inputs empty 'spec.ips'", func() {
+					ipVersion := constant.IPv4
+					rIPT.Spec.IPVersion = &ipVersion
+
+					ctx := context.TODO()
+					err := rIPWebhook.ValidateCreate(ctx, rIPT)
+					Expect(err).NotTo(HaveOccurred())
+				})
+
+				It("inputs invalid 'spec.ips'", func() {
+					ipVersion := constant.IPv4
+					rIPT.Spec.IPVersion = &ipVersion
+					rIPT.Spec.IPs = append(rIPT.Spec.IPs, constant.InvalidIPRange)
+
+					ctx := context.TODO()
+					err := rIPWebhook.ValidateCreate(ctx, rIPT)
+					Expect(err).To(HaveOccurred())
+				})
+
+				It("exists invalid ReservedIPs in the cluster", func() {
+					existRIPT := rIPT.DeepCopy()
+					existRIPT.Name = "exist-reservedip"
+					ipVersion := constant.IPv4
+					existRIPT.Spec.IPVersion = &ipVersion
+					existRIPT.Spec.IPs = append(existRIPT.Spec.IPs, constant.InvalidIPRange)
+					rIPListT.Items = append(rIPListT.Items, *existRIPT)
+
+					mockRIPManager.EXPECT().
+						ListReservedIPs(gomock.All()).
+						Return(rIPListT, nil).
+						Times(1)
+
+					rIPT.Spec.IPVersion = &ipVersion
+					rIPT.Spec.IPs = append(rIPT.Spec.IPs,
+						[]string{
+							"172.18.40.1-172.18.40.2",
+							"172.18.40.10",
+						}...,
+					)
+
+					ctx := context.TODO()
+					err := rIPWebhook.ValidateCreate(ctx, rIPT)
+					Expect(err).To(HaveOccurred())
+				})
+
+				It("overlaps with the existing ReservedIP", func() {
+					existRIPT := rIPT.DeepCopy()
+					existRIPT.Name = "exist-reservedip"
+					ipVersion := constant.IPv4
+					existRIPT.Spec.IPVersion = &ipVersion
+					existRIPT.Spec.IPs = append(existRIPT.Spec.IPs, "172.18.40.10")
+					rIPListT.Items = append(rIPListT.Items, *existRIPT)
+
+					mockRIPManager.EXPECT().
+						ListReservedIPs(gomock.All()).
+						Return(rIPListT, nil).
+						Times(1)
+
+					rIPT.Spec.IPVersion = &ipVersion
+					rIPT.Spec.IPs = append(rIPT.Spec.IPs,
+						[]string{
+							"172.18.40.1-172.18.40.2",
+							"172.18.40.10",
+						}...,
+					)
+
+					ctx := context.TODO()
+					err := rIPWebhook.ValidateCreate(ctx, rIPT)
+					Expect(err).To(HaveOccurred())
+				})
+			})
+
+			It("creates IPv4 ReservedIP with all fields valid", func() {
+				mockRIPManager.EXPECT().
+					ListReservedIPs(gomock.All()).
+					Return(rIPListT, nil).
+					Times(1)
+
+				ipVersion := constant.IPv4
+				rIPT.Spec.IPVersion = &ipVersion
+				rIPT.Spec.IPs = append(rIPT.Spec.IPs,
+					[]string{
+						"172.18.40.1-172.18.40.2",
+						"172.18.40.10",
+					}...,
+				)
+
+				ctx := context.TODO()
+				err := rIPWebhook.ValidateCreate(ctx, rIPT)
+				Expect(err).NotTo(HaveOccurred())
+			})
+
+			It("creates IPv6 ReservedIP with all fields valid", func() {
+				mockRIPManager.EXPECT().
+					ListReservedIPs(gomock.All()).
+					Return(rIPListT, nil).
+					Times(1)
+
+				ipVersion := constant.IPv6
+				rIPT.Spec.IPVersion = &ipVersion
+				rIPT.Spec.IPs = append(rIPT.Spec.IPs,
+					[]string{
+						"abcd:1234::1-abcd:1234::2",
+						"abcd:1234::a",
+					}...,
+				)
+
+				ctx := context.TODO()
+				err := rIPWebhook.ValidateCreate(ctx, rIPT)
+				Expect(err).NotTo(HaveOccurred())
+			})
+		})
+
+		Describe("ValidateUpdate", func() {
+			BeforeEach(func() {
+				rIPWebhook.EnableIPv4 = true
+				rIPWebhook.EnableIPv6 = true
+			})
+
+			When("Validating 'spec.ipVersion'", func() {
+				It("updates 'spec.ipVersion' to nil", func() {
+					rIPWebhook.EnableIPv4 = false
+					ipVersion := constant.IPv4
+					rIPT.Spec.IPVersion = &ipVersion
+
+					newRIPT := rIPT.DeepCopy()
+					newRIPT.Spec.IPVersion = nil
+
+					ctx := context.TODO()
+					err := rIPWebhook.ValidateUpdate(ctx, rIPT, newRIPT)
+					Expect(err).To(HaveOccurred())
+				})
+
+				It("updates 'spec.ipVersion' to invalid IP version", func() {
+					rIPWebhook.EnableIPv4 = false
+					ipVersion := constant.IPv4
+					rIPT.Spec.IPVersion = &ipVersion
+
+					newRIPT := rIPT.DeepCopy()
+					invalidIPVersion := constant.InvalidIPVersion
+					newRIPT.Spec.IPVersion = &invalidIPVersion
+
+					ctx := context.TODO()
+					err := rIPWebhook.ValidateUpdate(ctx, rIPT, newRIPT)
+					Expect(err).To(HaveOccurred())
+				})
+
+				It("changes 'spec.ipVersion'", func() {
+					rIPWebhook.EnableIPv4 = false
+					ipv4 := constant.IPv4
+					rIPT.Spec.IPVersion = &ipv4
+
+					newRIPT := rIPT.DeepCopy()
+					ipv6 := constant.IPv6
+					newRIPT.Spec.IPVersion = &ipv6
+
+					ctx := context.TODO()
+					err := rIPWebhook.ValidateUpdate(ctx, rIPT, newRIPT)
+					Expect(err).To(HaveOccurred())
+				})
+
+				It("updates IPv4 ReservedIP but IPv4 is disbale'", func() {
+					rIPWebhook.EnableIPv4 = false
+					ipVersion := constant.IPv4
+					rIPT.Spec.IPVersion = &ipVersion
+
+					newRIPT := rIPT.DeepCopy()
+					newRIPT.Spec.IPs = append(newRIPT.Spec.IPs, "172.18.40.10")
+
+					ctx := context.TODO()
+					err := rIPWebhook.ValidateUpdate(ctx, rIPT, newRIPT)
+					Expect(err).To(HaveOccurred())
+				})
+
+				It("updates IPv6 ReservedIP but IPv6 is disbale'", func() {
+					rIPWebhook.EnableIPv6 = false
+					ipVersion := constant.IPv6
+					rIPT.Spec.IPVersion = &ipVersion
+
+					newRIPT := rIPT.DeepCopy()
+					newRIPT.Spec.IPs = append(newRIPT.Spec.IPs, "adbc:1234::a")
+
+					ctx := context.TODO()
+					err := rIPWebhook.ValidateUpdate(ctx, rIPT, newRIPT)
+					Expect(err).To(HaveOccurred())
+				})
+			})
+
+			When("Validating 'spec.ips'", func() {
+				It("failed to list ReservedIPs due to some unknown errors", func() {
+					mockRIPManager.EXPECT().
+						ListReservedIPs(gomock.All()).
+						Return(nil, constant.ErrUnknown).
+						Times(1)
+
+					ipVersion := constant.IPv4
+					rIPT.Spec.IPVersion = &ipVersion
+					rIPT.Spec.IPs = append(rIPT.Spec.IPs, "172.18.40.1-172.18.40.2")
+
+					newRIPT := rIPT.DeepCopy()
+					newRIPT.Spec.IPs = append(newRIPT.Spec.IPs, "172.18.40.10")
+
+					ctx := context.TODO()
+					err := rIPWebhook.ValidateUpdate(ctx, rIPT, newRIPT)
+					Expect(err).To(HaveOccurred())
+				})
+
+				It("appends an invalid IP range to 'spec.ips'", func() {
+					ipVersion := constant.IPv4
+					rIPT.Spec.IPVersion = &ipVersion
+
+					newRIPT := rIPT.DeepCopy()
+					newRIPT.Spec.IPs = append(newRIPT.Spec.IPs, constant.InvalidIPRange)
+
+					ctx := context.TODO()
+					err := rIPWebhook.ValidateUpdate(ctx, rIPT, newRIPT)
+					Expect(err).To(HaveOccurred())
+				})
+
+				It("exists invalid ReservedIPs in the cluster", func() {
+					existRIPT := rIPT.DeepCopy()
+					existRIPT.Name = "exist-reservedip"
+					ipVersion := constant.IPv4
+					existRIPT.Spec.IPVersion = &ipVersion
+					existRIPT.Spec.IPs = append(existRIPT.Spec.IPs, constant.InvalidIPRange)
+					rIPListT.Items = append(rIPListT.Items, *existRIPT)
+
+					mockRIPManager.EXPECT().
+						ListReservedIPs(gomock.All()).
+						Return(rIPListT, nil).
+						Times(1)
+
+					rIPT.Spec.IPVersion = &ipVersion
+					rIPT.Spec.IPs = append(rIPT.Spec.IPs, "172.18.40.1-172.18.40.2")
+
+					newRIPT := rIPT.DeepCopy()
+					newRIPT.Spec.IPs = append(newRIPT.Spec.IPs, "172.18.40.10")
+
+					ctx := context.TODO()
+					err := rIPWebhook.ValidateUpdate(ctx, rIPT, newRIPT)
+					Expect(err).To(HaveOccurred())
+				})
+
+				It("overlaps with the existing ReservedIP", func() {
+					existRIPT := rIPT.DeepCopy()
+					existRIPT.Name = "exist-reservedip"
+					ipVersion := constant.IPv4
+					existRIPT.Spec.IPVersion = &ipVersion
+					existRIPT.Spec.IPs = append(existRIPT.Spec.IPs, "172.18.40.10")
+
+					rIPT.Spec.IPVersion = &ipVersion
+					rIPT.Spec.IPs = append(rIPT.Spec.IPs, "172.18.40.1-172.18.40.2")
+					rIPListT.Items = append(rIPListT.Items, *rIPT, *existRIPT)
+
+					mockRIPManager.EXPECT().
+						ListReservedIPs(gomock.All()).
+						Return(rIPListT, nil).
+						Times(1)
+
+					newRIPT := rIPT.DeepCopy()
+					newRIPT.Spec.IPs = append(newRIPT.Spec.IPs, "172.18.40.10")
+
+					ctx := context.TODO()
+					err := rIPWebhook.ValidateUpdate(ctx, rIPT, newRIPT)
+					Expect(err).To(HaveOccurred())
+				})
+			})
+
+			It("updates IPv4 ReservedIP with all fields valid", func() {
+				mockRIPManager.EXPECT().
+					ListReservedIPs(gomock.All()).
+					Return(rIPListT, nil).
+					Times(1)
+
+				ipVersion := constant.IPv4
+				rIPT.Spec.IPVersion = &ipVersion
+				rIPT.Spec.IPs = append(rIPT.Spec.IPs, "172.18.40.1-172.18.40.2")
+
+				newRIPT := rIPT.DeepCopy()
+				newRIPT.Spec.IPs = append(newRIPT.Spec.IPs, "172.18.40.10")
+
+				ctx := context.TODO()
+				err := rIPWebhook.ValidateUpdate(ctx, rIPT, newRIPT)
+				Expect(err).NotTo(HaveOccurred())
+			})
+
+			It("updates IPv6 ReservedIP with all fields valid", func() {
+				mockRIPManager.EXPECT().
+					ListReservedIPs(gomock.All()).
+					Return(rIPListT, nil).
+					Times(1)
+
+				ipVersion := constant.IPv6
+				rIPT.Spec.IPVersion = &ipVersion
+				rIPT.Spec.IPs = append(rIPT.Spec.IPs, "abcd:1234::1-abcd:1234::2")
+
+				newRIPT := rIPT.DeepCopy()
+				newRIPT.Spec.IPs = append(newRIPT.Spec.IPs, "abcd:1234::a")
+
+				ctx := context.TODO()
+				err := rIPWebhook.ValidateUpdate(ctx, rIPT, newRIPT)
+				Expect(err).NotTo(HaveOccurred())
+			})
+		})
+
+		Describe("ValidateDelete", func() {
+			It("passes", func() {
+				ctx := context.TODO()
+				err := rIPWebhook.ValidateDelete(ctx, rIPT)
+				Expect(err).NotTo(HaveOccurred())
+			})
+		})
+	})
+})
diff --git a/pkg/reservedipmanager/utils_test.go b/pkg/reservedipmanager/utils_test.go
new file mode 100644
index 000000000..28809c098
--- /dev/null
+++ b/pkg/reservedipmanager/utils_test.go
@@ -0,0 +1,123 @@
+// Copyright 2022 Authors of spidernet-io
+// SPDX-License-Identifier: Apache-2.0
+
+package reservedipmanager_test
+
+import (
+	"fmt"
+	"net"
+
+	. "github.com/onsi/ginkgo/v2"
+	. "github.com/onsi/gomega"
+
+	"github.com/spidernet-io/spiderpool/pkg/constant"
+	spiderpoolip "github.com/spidernet-io/spiderpool/pkg/ip"
+	spiderpoolv1 "github.com/spidernet-io/spiderpool/pkg/k8s/apis/spiderpool.spidernet.io/v1"
+	"github.com/spidernet-io/spiderpool/pkg/reservedipmanager"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+)
+
+var _ = Describe("ReservedIPManager utils", Label("reservedip_manager_utils_test"), func() {
+	Describe("Test AssembleReservedIPs", func() {
+		var v4RIPT spiderpoolv1.SpiderReservedIP
+		var v6RIPT spiderpoolv1.SpiderReservedIP
+		var rIPListT *spiderpoolv1.SpiderReservedIPList
+
+		BeforeEach(func() {
+			ipv4 := constant.IPv4
+			ipv6 := constant.IPv6
+
+			v4RIPT = spiderpoolv1.SpiderReservedIP{
+				TypeMeta: metav1.TypeMeta{
+					Kind:       constant.SpiderReservedIPKind,
+					APIVersion: fmt.Sprintf("%s/%s", constant.SpiderpoolAPIGroup, constant.SpiderpoolAPIVersionV1),
+				},
+				ObjectMeta: metav1.ObjectMeta{
+					Name: "ipv4-reservedip",
+				},
+				Spec: spiderpoolv1.ReservedIPSpec{
+					IPVersion: &ipv4,
+					IPs: []string{
+						"172.18.40.1-172.18.40.2",
+						"172.18.40.10",
+					},
+				},
+			}
+
+			v6RIPT = spiderpoolv1.SpiderReservedIP{
+				TypeMeta: metav1.TypeMeta{
+					Kind:       constant.SpiderReservedIPKind,
+					APIVersion: fmt.Sprintf("%s/%s", constant.SpiderpoolAPIGroup, constant.SpiderpoolAPIVersionV1),
+				},
+				ObjectMeta: metav1.ObjectMeta{
+					Name: "ipv6-reservedip",
+				},
+				Spec: spiderpoolv1.ReservedIPSpec{
+					IPVersion: &ipv6,
+					IPs: []string{
+						"abcd:1234::1-abcd:1234::2",
+						"abcd:1234::a",
+					},
+				},
+			}
+
+			rIPListT = &spiderpoolv1.SpiderReservedIPList{
+				TypeMeta: metav1.TypeMeta{
+					Kind:       constant.SpiderReservedIPListKind,
+					APIVersion: fmt.Sprintf("%s/%s", constant.SpiderpoolAPIGroup, constant.SpiderpoolAPIVersionV1),
+				},
+				ListMeta: metav1.ListMeta{},
+				Items:    []spiderpoolv1.SpiderReservedIP{},
+			}
+		})
+
+		It("inputs invalid IP version", func() {
+			ips, err := reservedipmanager.AssembleReservedIPs(constant.InvalidIPVersion, rIPListT)
+			Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPVersion))
+			Expect(ips).To(BeEmpty())
+		})
+
+		It("inputs nil ReservedIP list", func() {
+			ips, err := reservedipmanager.AssembleReservedIPs(constant.IPv4, nil)
+			Expect(err).To(MatchError(constant.ErrMissingRequiredParam))
+			Expect(ips).To(BeEmpty())
+		})
+
+		It("inputs invalid IP ranges", func() {
+			v4RIPT.Spec.IPs = append(v4RIPT.Spec.IPs, constant.InvalidIPRange)
+			rIPListT.Items = append(rIPListT.Items, v4RIPT)
+
+			ips, err := reservedipmanager.AssembleReservedIPs(constant.IPv4, rIPListT)
+			Expect(err).To(MatchError(spiderpoolip.ErrInvalidIPRangeFormat))
+			Expect(ips).To(BeEmpty())
+		})
+
+		It("assembles IPv4 reserved IP addresses", func() {
+			rIPListT.Items = append(rIPListT.Items, v4RIPT, v6RIPT)
+
+			ips, err := reservedipmanager.AssembleReservedIPs(constant.IPv4, rIPListT)
+			Expect(err).NotTo(HaveOccurred())
+			Expect(ips).To(Equal(
+				[]net.IP{
+					net.IPv4(172, 18, 40, 1),
+					net.IPv4(172, 18, 40, 2),
+					net.IPv4(172, 18, 40, 10),
+				},
+			))
+		})
+
+		It("assembles IPv6 reserved IP addresses", func() {
+			rIPListT.Items = append(rIPListT.Items, v4RIPT, v6RIPT)
+
+			ips, err := reservedipmanager.AssembleReservedIPs(constant.IPv6, rIPListT)
+			Expect(err).NotTo(HaveOccurred())
+			Expect(ips).To(Equal(
+				[]net.IP{
+					net.ParseIP("abcd:1234::1"),
+					net.ParseIP("abcd:1234::2"),
+					net.ParseIP("abcd:1234::a"),
+				},
+			))
+		})
+	})
+})