Add UT for pkg/cmd/cli/backup (#6400)

Signed-off-by: danfengl <danfengl@vmware.com>
This commit is contained in:
danfengliu
2023-06-21 11:10:13 +08:00
committed by GitHub
parent 6f3adcf728
commit ef443fece0
33 changed files with 2984 additions and 32 deletions

View File

@@ -0,0 +1,34 @@
/*
Copyright The Velero Contributors.
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 backuplocation
import (
"testing"
"github.com/stretchr/testify/assert"
factorymocks "github.com/vmware-tanzu/velero/pkg/client/mocks"
)
func TestNewCommand(t *testing.T) {
// create a factory
f := &factorymocks.Factory{}
// create command
c := NewCommand(f)
assert.Equal(t, "Work with backup storage locations", c.Short)
}

View File

@@ -17,12 +17,28 @@ limitations under the License.
package backuplocation
import (
"fmt"
"reflect"
"strings"
"testing"
"time"
flag "github.com/spf13/pflag"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
veleroflag "github.com/vmware-tanzu/velero/pkg/cmd/util/flag"
"github.com/vmware-tanzu/velero/pkg/test"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
velerov1api "github.com/vmware-tanzu/velero/pkg/apis/velero/v1"
factorymocks "github.com/vmware-tanzu/velero/pkg/client/mocks"
versionedmocks "github.com/vmware-tanzu/velero/pkg/generated/clientset/versioned/mocks"
"github.com/vmware-tanzu/velero/pkg/generated/clientset/versioned/scheme"
velerov1mocks "github.com/vmware-tanzu/velero/pkg/generated/clientset/versioned/typed/velero/v1/mocks"
)
func TestBuildBackupStorageLocationSetsNamespace(t *testing.T) {
@@ -87,3 +103,99 @@ func TestBuildBackupStorageLocationSetsLabels(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, map[string]string{"key": "value"}, bsl.Labels)
}
func TestCreateCommand_Run(t *testing.T) {
// create a factory
f := &factorymocks.Factory{}
// create command
c := NewCreateCommand(f, "")
assert.Equal(t, "Create a backup storage location", c.Short)
// create a CreateOptions with full options set and then run this backup command
name := "bsl-name-to-be-created"
provider := "aws"
bucket := "velero123456"
credential := veleroflag.NewMap()
credential.Set("secret=a")
defaultBackupStorageLocation := true
prefix := "builds"
backupSyncPeriod := "1m30s"
validationFrequency := "128h1m6s"
bslConfig := veleroflag.NewMap()
bslConfigStr := "region=minio"
bslConfig.Set(bslConfigStr)
labels := "a=too,b=woo"
caCertFile := "bsl-name-1"
accessMode := "ReadWrite"
flags := new(flag.FlagSet)
o := NewCreateOptions()
o.BindFlags(flags)
flags.Parse([]string{"--provider", provider})
flags.Parse([]string{"--bucket", bucket})
flags.Parse([]string{"--credential", credential.String()})
flags.Parse([]string{"--default"})
flags.Parse([]string{"--prefix", prefix})
flags.Parse([]string{"--backup-sync-period", backupSyncPeriod})
flags.Parse([]string{"--validation-frequency", validationFrequency})
flags.Parse([]string{"--config", bslConfigStr})
flags.Parse([]string{"--labels", labels})
flags.Parse([]string{"--cacert", caCertFile})
flags.Parse([]string{"--access-mode", accessMode})
args := []string{name, "arg2"}
backups := &velerov1mocks.BackupInterface{}
veleroV1 := &velerov1mocks.VeleroV1Interface{}
client := &versionedmocks.Interface{}
bk := &velerov1api.Backup{}
kbclient := fake.NewClientBuilder().WithScheme(scheme.Scheme).Build()
backups.On("Create", mock.Anything, mock.Anything, mock.Anything).Return(bk, nil)
veleroV1.On("Backups", mock.Anything).Return(backups, nil)
client.On("VeleroV1").Return(veleroV1, nil)
f.On("Client").Return(client, nil)
f.On("Namespace").Return(mock.Anything)
f.On("KubebuilderClient").Return(kbclient, nil)
o.Complete(args, f)
e := o.Validate(c, args, f)
assert.Equal(t, e, nil)
e = o.Run(c, f)
assert.Contains(t, e.Error(), fmt.Sprintf("%s: no such file or directory", caCertFile))
// verify all options are set as expected
assert.Equal(t, name, o.Name)
assert.Equal(t, provider, o.Provider)
assert.Equal(t, bucket, o.Bucket)
assert.Equal(t, true, reflect.DeepEqual(credential, o.Credential))
assert.Equal(t, defaultBackupStorageLocation, o.DefaultBackupStorageLocation)
assert.Equal(t, prefix, o.Prefix)
assert.Equal(t, backupSyncPeriod, o.BackupSyncPeriod.String())
assert.Equal(t, validationFrequency, o.ValidationFrequency.String())
assert.Equal(t, true, reflect.DeepEqual(bslConfig, o.Config))
assert.Equal(t, true, test.CompareSlice(strings.Split(labels, ","), strings.Split(o.Labels.String(), ",")))
assert.Equal(t, caCertFile, o.CACertFile)
assert.Equal(t, accessMode, o.AccessMode.String())
// create the other create command without fromSchedule option for Run() other branches
c = NewCreateCommand(f, "velero backup-location create")
assert.Equal(t, "Create a backup storage location", c.Short)
o = NewCreateOptions()
o.Labels.Set("velero.io/test=true")
args = []string{"backup-name-2", "arg2"}
o.Complete(args, f)
e = o.Run(c, f)
assert.NoError(t, e)
c.SetArgs([]string{"bsl-1", "--provider=aws", "--bucket=bk1", "--default"})
e = c.Execute()
assert.NoError(t, e)
}

View File

@@ -0,0 +1,125 @@
/*
Copyright The Velero Contributors.
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 backuplocation
import (
"fmt"
"os"
"os/exec"
"testing"
flag "github.com/spf13/pflag"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
velerov1api "github.com/vmware-tanzu/velero/pkg/apis/velero/v1"
factorymocks "github.com/vmware-tanzu/velero/pkg/client/mocks"
"github.com/vmware-tanzu/velero/pkg/cmd/cli"
cmdtest "github.com/vmware-tanzu/velero/pkg/cmd/test"
versionedmocks "github.com/vmware-tanzu/velero/pkg/generated/clientset/versioned/mocks"
"github.com/vmware-tanzu/velero/pkg/generated/clientset/versioned/scheme"
veleroexec "github.com/vmware-tanzu/velero/pkg/util/exec"
)
func TestNewDeleteCommand(t *testing.T) {
// create a factory
f := &factorymocks.Factory{}
client := &versionedmocks.Interface{}
kbclient := fake.NewClientBuilder().WithScheme(scheme.Scheme).Build()
f.On("Client").Return(client, nil)
f.On("Namespace").Return(mock.Anything)
f.On("KubebuilderClient").Return(kbclient, nil)
// create command
c := NewDeleteCommand(f, "velero backup-location delete")
assert.Equal(t, "Delete backup storage locations", c.Short)
o := cli.NewDeleteOptions("backup")
flags := new(flag.FlagSet)
o.BindFlags(flags)
flags.Parse([]string{"--confirm"})
args := []string{"bk-loc-1", "bk-loc-2"}
e := o.Complete(f, args)
assert.NoError(t, e)
e = o.Validate(c, f, args)
assert.NoError(t, e)
c.SetArgs([]string{"bk-1", "--confirm"})
e = c.Execute()
assert.NoError(t, e)
e = Run(f, o)
assert.NoError(t, e)
if os.Getenv(cmdtest.CaptureFlag) == "1" {
return
}
cmd := exec.Command(os.Args[0], []string{"-test.run=TestNewDeleteCommand"}...)
cmd.Env = append(os.Environ(), fmt.Sprintf("%s=1", cmdtest.CaptureFlag))
stdout, _, err := veleroexec.RunCommand(cmd)
if err == nil {
assert.Contains(t, stdout, "No backup-locations found")
return
}
t.Fatalf("process ran with err %v, want backups by get()", err)
}
func TestDeleteFunctions(t *testing.T) {
//t.Run("create the other create command with fromSchedule option for Run() other branches", func(t *testing.T) {
// create a factory
f := &factorymocks.Factory{}
client := &versionedmocks.Interface{}
kbclient := fake.NewClientBuilder().WithScheme(scheme.Scheme).Build()
f.On("Client").Return(client, nil)
f.On("Namespace").Return(mock.Anything)
f.On("KubebuilderClient").Return(kbclient, nil)
bkList := velerov1api.BackupList{}
bkrepoList := velerov1api.BackupRepositoryList{}
t.Run("findAssociatedBackups", func(t *testing.T) {
bkList, e := findAssociatedBackups(kbclient, "bk-loc-1", "ns1")
assert.Equal(t, 0, len(bkList.Items))
assert.NoError(t, e)
})
t.Run("findAssociatedBackupRepos", func(t *testing.T) {
bkrepoList, e := findAssociatedBackupRepos(kbclient, "bk-loc-1", "ns1")
assert.Equal(t, 0, len(bkrepoList.Items))
assert.NoError(t, e)
})
t.Run("deleteBackups", func(t *testing.T) {
bk := velerov1api.Backup{}
bk.Name = "bk-name-last"
bkList.Items = append(bkList.Items, bk)
errList := deleteBackups(kbclient, bkList)
assert.Equal(t, 1, len(errList))
assert.Contains(t, errList[0].Error(), fmt.Sprintf("delete backup \"%s\" associated with deleted BSL: backups.velero.io \"%s\" not found", bk.Name, bk.Name))
})
t.Run("deleteBackupRepos", func(t *testing.T) {
bkrepo := velerov1api.BackupRepository{}
bkrepo.Name = "bk-repo-name-last"
bkrepoList.Items = append(bkrepoList.Items, bkrepo)
errList := deleteBackupRepos(kbclient, bkrepoList)
assert.Equal(t, 1, len(errList))
assert.Contains(t, errList[0].Error(), fmt.Sprintf("delete backup repository \"%s\" associated with deleted BSL: backuprepositories.velero.io \"%s\" not found", bkrepo.Name, bkrepo.Name))
})
}

View File

@@ -0,0 +1,63 @@
/*
Copyright The Velero Contributors.
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 backuplocation
import (
"fmt"
"os"
"os/exec"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
factorymocks "github.com/vmware-tanzu/velero/pkg/client/mocks"
cmdtest "github.com/vmware-tanzu/velero/pkg/cmd/test"
"github.com/vmware-tanzu/velero/pkg/generated/clientset/versioned/scheme"
veleroexec "github.com/vmware-tanzu/velero/pkg/util/exec"
)
func TestNewGetCommand(t *testing.T) {
bkList := []string{"b1", "b2"}
f := &factorymocks.Factory{}
kbclient := fake.NewClientBuilder().WithScheme(scheme.Scheme).Build()
f.On("Namespace").Return(mock.Anything)
f.On("KubebuilderClient").Return(kbclient, nil)
// get command
c := NewGetCommand(f, "velero backup-location get")
assert.Equal(t, "Get backup storage locations", c.Short)
c.Execute()
if os.Getenv(cmdtest.CaptureFlag) == "1" {
c.SetArgs([]string{"b1", "b2", "--default"})
c.Execute()
return
}
cmd := exec.Command(os.Args[0], []string{"-test.run=TestNewGetCommand"}...)
cmd.Env = append(os.Environ(), fmt.Sprintf("%s=1", cmdtest.CaptureFlag))
_, stderr, err := veleroexec.RunCommand(cmd)
if err != nil {
assert.Contains(t, stderr, fmt.Sprintf("backupstoragelocations.velero.io \"%s\" not found", bkList[0]))
return
}
t.Fatalf("process ran with err %v, want backup delete successfully", err)
}

View File

@@ -0,0 +1,129 @@
/*
Copyright The Velero Contributors.
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 backuplocation
import (
"fmt"
"os"
"os/exec"
"reflect"
"testing"
flag "github.com/spf13/pflag"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
cmdtest "github.com/vmware-tanzu/velero/pkg/cmd/test"
veleroflag "github.com/vmware-tanzu/velero/pkg/cmd/util/flag"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
velerov1api "github.com/vmware-tanzu/velero/pkg/apis/velero/v1"
factorymocks "github.com/vmware-tanzu/velero/pkg/client/mocks"
versionedmocks "github.com/vmware-tanzu/velero/pkg/generated/clientset/versioned/mocks"
"github.com/vmware-tanzu/velero/pkg/generated/clientset/versioned/scheme"
velerov1mocks "github.com/vmware-tanzu/velero/pkg/generated/clientset/versioned/typed/velero/v1/mocks"
veleroexec "github.com/vmware-tanzu/velero/pkg/util/exec"
)
func TestNewSetCommand(t *testing.T) {
backupName := "arg2"
// create a config for factory
f := &factorymocks.Factory{}
backups := &velerov1mocks.BackupInterface{}
veleroV1 := &velerov1mocks.VeleroV1Interface{}
client := &versionedmocks.Interface{}
bk := &velerov1api.Backup{}
kbclient := fake.NewClientBuilder().WithScheme(scheme.Scheme).Build()
backups.On("Create", mock.Anything, mock.Anything, mock.Anything).Return(bk, nil)
veleroV1.On("Backups", mock.Anything).Return(backups, nil)
client.On("VeleroV1").Return(veleroV1, nil)
f.On("Client").Return(client, nil)
f.On("Namespace").Return(mock.Anything)
f.On("KubebuilderClient").Return(kbclient, nil)
// create command
c := NewSetCommand(f, "")
assert.Equal(t, "Set specific features for a backup storage location", c.Short)
// create a SetOptions with full options set and then run this backup command
cacert := "a/b/c/ut-cert.ca"
defaultBackupStorageLocation := true
credential := veleroflag.NewMap()
credential.Set("secret=a")
flags := new(flag.FlagSet)
o := NewSetOptions()
o.BindFlags(flags)
flags.Parse([]string{"--cacert", cacert})
flags.Parse([]string{"--credential", credential.String()})
flags.Parse([]string{"--default"})
args := []string{backupName}
o.Complete(args, f)
e := o.Validate(c, args, f)
assert.Equal(t, e, nil)
e = o.Run(c, f)
assert.Contains(t, e.Error(), fmt.Sprintf("%s: no such file or directory", cacert))
// verify all options are set as expected
assert.Equal(t, backupName, o.Name)
assert.Equal(t, cacert, o.CACertFile)
assert.Equal(t, defaultBackupStorageLocation, o.DefaultBackupStorageLocation)
assert.Equal(t, true, reflect.DeepEqual(credential, o.Credential))
assert.Contains(t, e.Error(), fmt.Sprintf("%s: no such file or directory", cacert))
}
func TestSetCommand_Execute(t *testing.T) {
bsl := "bsl-1"
if os.Getenv(cmdtest.CaptureFlag) == "1" {
// create a config for factory
f := &factorymocks.Factory{}
backups := &velerov1mocks.BackupInterface{}
veleroV1 := &velerov1mocks.VeleroV1Interface{}
client := &versionedmocks.Interface{}
bk := &velerov1api.Backup{}
kbclient := fake.NewClientBuilder().WithScheme(scheme.Scheme).Build()
backups.On("Create", mock.Anything, mock.Anything, mock.Anything).Return(bk, nil)
veleroV1.On("Backups", mock.Anything).Return(backups, nil)
client.On("VeleroV1").Return(veleroV1, nil)
f.On("Client").Return(client, nil)
f.On("Namespace").Return(mock.Anything)
f.On("KubebuilderClient").Return(kbclient, nil)
// create command
c := NewSetCommand(f, "velero backup-location set")
c.SetArgs([]string{bsl})
c.Execute()
return
}
cmd := exec.Command(os.Args[0], []string{"-test.run=TestSetCommand_Execute"}...)
cmd.Env = append(os.Environ(), fmt.Sprintf("%s=1", cmdtest.CaptureFlag))
_, stderr, err := veleroexec.RunCommand(cmd)
if err != nil {
assert.Contains(t, stderr, fmt.Sprintf("backupstoragelocations.velero.io \"%s\" not found", bsl))
return
}
t.Fatalf("process ran with err %v, want backup delete successfully", err)
}